Current File : /home/mmdealscpanel/yummmdeals.com/test.zip
PK�R�Z�E[//__init__.pynu�[���# Dummy file to make this directory a package.
PK�R�ZB�u�xx)__pycache__/__init__.cpython-36.opt-2.pycnu�[���3


 \/�@sdS)N�rrr�%/usr/lib64/python3.6/test/__init__.py�<module>sPK�R�ZB�u�xx#__pycache__/__init__.cpython-36.pycnu�[���3


 \/�@sdS)N�rrr�%/usr/lib64/python3.6/test/__init__.py�<module>sPK�R�ZB�u�xx)__pycache__/__init__.cpython-36.opt-1.pycnu�[���3


 \/�@sdS)N�rrr�%/usr/lib64/python3.6/test/__init__.py�<module>sPK�R�ZC敏.�.support/__init__.pynu�[���"""Supporting definitions for the Python regression tests."""

if __name__ != 'test.support':
    raise ImportError('test.support must be imported from the test package')

import contextlib
import errno
import fnmatch
import functools
import gc
import socket
import stat
import sys
import os
import platform
import shutil
import warnings
import unittest
import importlib
import UserDict
import re
import time
import struct
import sysconfig
import types

try:
    import thread
except ImportError:
    thread = None

__all__ = ["Error", "TestFailed", "TestDidNotRun", "ResourceDenied", "import_module",
           "verbose", "use_resources", "max_memuse", "record_original_stdout",
           "get_original_stdout", "unload", "unlink", "rmtree", "forget",
           "is_resource_enabled", "requires", "requires_mac_ver",
           "find_unused_port", "bind_port",
           "fcmp", "have_unicode", "is_jython", "TESTFN", "HOST", "FUZZ",
           "SAVEDCWD", "temp_cwd", "findfile", "sortdict", "check_syntax_error",
           "open_urlresource", "check_warnings", "check_py3k_warnings",
           "CleanImport", "EnvironmentVarGuard", "captured_output",
           "captured_stdout", "TransientResource", "transient_internet",
           "run_with_locale", "set_memlimit", "bigmemtest", "bigaddrspacetest",
           "BasicTestRunner", "run_unittest", "run_doctest", "threading_setup",
           "threading_cleanup", "reap_threads", "start_threads", "cpython_only",
           "check_impl_detail", "get_attribute", "py3k_bytes",
           "import_fresh_module", "threading_cleanup", "reap_children",
           "strip_python_stderr", "IPV6_ENABLED", "run_with_tz",
           "SuppressCrashReport"]

SHORT_TIMEOUT = 30.0  # Added to make backporting from 3.x easier

class Error(Exception):
    """Base class for regression test exceptions."""

class TestFailed(Error):
    """Test failed."""

class TestDidNotRun(Error):
    """Test did not run any subtests."""

class ResourceDenied(unittest.SkipTest):
    """Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not been enabled.  It is used to distinguish between expected
    and unexpected skips.
    """

@contextlib.contextmanager
def _ignore_deprecated_imports(ignore=True):
    """Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect."""
    if ignore:
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", ".+ (module|package)",
                                    DeprecationWarning)
            yield
    else:
        yield


def import_module(name, deprecated=False):
    """Import and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed."""
    with _ignore_deprecated_imports(deprecated):
        try:
            return importlib.import_module(name)
        except ImportError, msg:
            raise unittest.SkipTest(str(msg))


def _save_and_remove_module(name, orig_modules):
    """Helper function to save and remove a module from sys.modules

       Raise ImportError if the module can't be imported."""
    # try to import the module and raise an error if it can't be imported
    if name not in sys.modules:
        __import__(name)
        del sys.modules[name]
    for modname in list(sys.modules):
        if modname == name or modname.startswith(name + '.'):
            orig_modules[modname] = sys.modules[modname]
            del sys.modules[modname]

def _save_and_block_module(name, orig_modules):
    """Helper function to save and block a module in sys.modules

       Return True if the module was in sys.modules, False otherwise."""
    saved = True
    try:
        orig_modules[name] = sys.modules[name]
    except KeyError:
        saved = False
    sys.modules[name] = None
    return saved


def import_fresh_module(name, fresh=(), blocked=(), deprecated=False):
    """Imports and returns a module, deliberately bypassing the sys.modules cache
    and importing a fresh copy of the module. Once the import is complete,
    the sys.modules cache is restored to its original state.

    Modules named in fresh are also imported anew if needed by the import.
    If one of these modules can't be imported, None is returned.

    Importing of modules named in blocked is prevented while the fresh import
    takes place.

    If deprecated is True, any module or package deprecation messages
    will be suppressed."""
    # NOTE: test_heapq, test_json, and test_warnings include extra sanity
    # checks to make sure that this utility function is working as expected
    with _ignore_deprecated_imports(deprecated):
        # Keep track of modules saved for later restoration as well
        # as those which just need a blocking entry removed
        orig_modules = {}
        names_to_remove = []
        _save_and_remove_module(name, orig_modules)
        try:
            for fresh_name in fresh:
                _save_and_remove_module(fresh_name, orig_modules)
            for blocked_name in blocked:
                if not _save_and_block_module(blocked_name, orig_modules):
                    names_to_remove.append(blocked_name)
            fresh_module = importlib.import_module(name)
        except ImportError:
            fresh_module = None
        finally:
            for orig_name, module in orig_modules.items():
                sys.modules[orig_name] = module
            for name_to_remove in names_to_remove:
                del sys.modules[name_to_remove]
        return fresh_module


def get_attribute(obj, name):
    """Get an attribute, raising SkipTest if AttributeError is raised."""
    try:
        attribute = getattr(obj, name)
    except AttributeError:
        if isinstance(obj, types.ModuleType):
            msg = "module %r has no attribute %r" % (obj.__name__, name)
        elif isinstance(obj, types.ClassType):
            msg = "class %s has no attribute %r" % (obj.__name__, name)
        elif isinstance(obj, types.InstanceType):
            msg = "%s instance has no attribute %r" % (obj.__class__.__name__, name)
        elif isinstance(obj, type):
            msg = "type object %r has no attribute %r" % (obj.__name__, name)
        else:
            msg = "%r object has no attribute %r" % (type(obj).__name__, name)
        raise unittest.SkipTest(msg)
    else:
        return attribute


verbose = 1              # Flag set to 0 by regrtest.py
use_resources = None     # Flag set to [] by regrtest.py
max_memuse = 0           # Disable bigmem tests (they will still be run with
                         # small sizes, to make sure they work.)
real_max_memuse = 0
failfast = False

# _original_stdout is meant to hold stdout at the time regrtest began.
# This may be "the real" stdout, or IDLE's emulation of stdout, or whatever.
# The point is to have some flavor of stdout the user can actually see.
_original_stdout = None
def record_original_stdout(stdout):
    global _original_stdout
    _original_stdout = stdout

def get_original_stdout():
    return _original_stdout or sys.stdout

def unload(name):
    try:
        del sys.modules[name]
    except KeyError:
        pass

def _force_run(path, func, *args):
    try:
        return func(*args)
    except EnvironmentError as err:
        if verbose >= 2:
            print('%s: %s' % (err.__class__.__name__, err))
            print('re-run %s%r' % (func.__name__, args))
        os.chmod(path, stat.S_IRWXU)
        return func(*args)

if sys.platform.startswith("win"):
    def _waitfor(func, pathname, waitall=False):
        # Perform the operation
        func(pathname)
        # Now setup the wait loop
        if waitall:
            dirname = pathname
        else:
            dirname, name = os.path.split(pathname)
            dirname = dirname or '.'
        # Check for `pathname` to be removed from the filesystem.
        # The exponential backoff of the timeout amounts to a total
        # of ~1 second after which the deletion is probably an error
        # anyway.
        # Testing on an i7@4.3GHz shows that usually only 1 iteration is
        # required when contention occurs.
        timeout = 0.001
        while timeout < 1.0:
            # Note we are only testing for the existence of the file(s) in
            # the contents of the directory regardless of any security or
            # access rights.  If we have made it this far, we have sufficient
            # permissions to do that much using Python's equivalent of the
            # Windows API FindFirstFile.
            # Other Windows APIs can fail or give incorrect results when
            # dealing with files that are pending deletion.
            L = os.listdir(dirname)
            if not (L if waitall else name in L):
                return
            # Increase the timeout and try again
            time.sleep(timeout)
            timeout *= 2
        warnings.warn('tests may fail, delete still pending for ' + pathname,
                      RuntimeWarning, stacklevel=4)

    def _unlink(filename):
        _waitfor(os.unlink, filename)

    def _rmdir(dirname):
        _waitfor(os.rmdir, dirname)

    def _rmtree(path):
        def _rmtree_inner(path):
            for name in _force_run(path, os.listdir, path):
                fullname = os.path.join(path, name)
                if os.path.isdir(fullname):
                    _waitfor(_rmtree_inner, fullname, waitall=True)
                    _force_run(fullname, os.rmdir, fullname)
                else:
                    _force_run(fullname, os.unlink, fullname)
        _waitfor(_rmtree_inner, path, waitall=True)
        _waitfor(lambda p: _force_run(p, os.rmdir, p), path)
else:
    _unlink = os.unlink
    _rmdir = os.rmdir

    def _rmtree(path):
        try:
            shutil.rmtree(path)
            return
        except EnvironmentError:
            pass

        def _rmtree_inner(path):
            for name in _force_run(path, os.listdir, path):
                fullname = os.path.join(path, name)
                try:
                    mode = os.lstat(fullname).st_mode
                except EnvironmentError:
                    mode = 0
                if stat.S_ISDIR(mode):
                    _rmtree_inner(fullname)
                    _force_run(path, os.rmdir, fullname)
                else:
                    _force_run(path, os.unlink, fullname)
        _rmtree_inner(path)
        os.rmdir(path)

def unlink(filename):
    try:
        _unlink(filename)
    except OSError as exc:
        if exc.errno not in (errno.ENOENT, errno.ENOTDIR):
            raise

def rmdir(dirname):
    try:
        _rmdir(dirname)
    except OSError as error:
        # The directory need not exist.
        if error.errno != errno.ENOENT:
            raise

def rmtree(path):
    try:
        _rmtree(path)
    except OSError, e:
        # Unix returns ENOENT, Windows returns ESRCH.
        if e.errno not in (errno.ENOENT, errno.ESRCH):
            raise

def forget(modname):
    '''"Forget" a module was ever imported by removing it from sys.modules and
    deleting any .pyc and .pyo files.'''
    unload(modname)
    for dirname in sys.path:
        unlink(os.path.join(dirname, modname + os.extsep + 'pyc'))
        # Deleting the .pyo file cannot be within the 'try' for the .pyc since
        # the chance exists that there is no .pyc (and thus the 'try' statement
        # is exited) but there is a .pyo file.
        unlink(os.path.join(dirname, modname + os.extsep + 'pyo'))

# Check whether a gui is actually available
def _is_gui_available():
    if hasattr(_is_gui_available, 'result'):
        return _is_gui_available.result
    reason = None
    if sys.platform.startswith('win'):
        # if Python is running as a service (such as the buildbot service),
        # gui interaction may be disallowed
        import ctypes
        import ctypes.wintypes
        UOI_FLAGS = 1
        WSF_VISIBLE = 0x0001
        class USEROBJECTFLAGS(ctypes.Structure):
            _fields_ = [("fInherit", ctypes.wintypes.BOOL),
                        ("fReserved", ctypes.wintypes.BOOL),
                        ("dwFlags", ctypes.wintypes.DWORD)]
        dll = ctypes.windll.user32
        h = dll.GetProcessWindowStation()
        if not h:
            raise ctypes.WinError()
        uof = USEROBJECTFLAGS()
        needed = ctypes.wintypes.DWORD()
        res = dll.GetUserObjectInformationW(h,
            UOI_FLAGS,
            ctypes.byref(uof),
            ctypes.sizeof(uof),
            ctypes.byref(needed))
        if not res:
            raise ctypes.WinError()
        if not bool(uof.dwFlags & WSF_VISIBLE):
            reason = "gui not available (WSF_VISIBLE flag not set)"
    elif sys.platform == 'darwin':
        # The Aqua Tk implementations on OS X can abort the process if
        # being called in an environment where a window server connection
        # cannot be made, for instance when invoked by a buildbot or ssh
        # process not running under the same user id as the current console
        # user.  To avoid that, raise an exception if the window manager
        # connection is not available.
        from ctypes import cdll, c_int, pointer, Structure
        from ctypes.util import find_library

        app_services = cdll.LoadLibrary(find_library("ApplicationServices"))

        if app_services.CGMainDisplayID() == 0:
            reason = "gui tests cannot run without OS X window manager"
        else:
            class ProcessSerialNumber(Structure):
                _fields_ = [("highLongOfPSN", c_int),
                            ("lowLongOfPSN", c_int)]
            psn = ProcessSerialNumber()
            psn_p = pointer(psn)
            if (  (app_services.GetCurrentProcess(psn_p) < 0) or
                  (app_services.SetFrontProcess(psn_p) < 0) ):
                reason = "cannot run without OS X gui process"

    # check on every platform whether tkinter can actually do anything
    if not reason:
        try:
            from Tkinter import Tk
            root = Tk()
            root.withdraw()
            root.update()
            root.destroy()
        except Exception as e:
            err_string = str(e)
            if len(err_string) > 50:
                err_string = err_string[:50] + ' [...]'
            reason = 'Tk unavailable due to {}: {}'.format(type(e).__name__,
                                                           err_string)

    _is_gui_available.reason = reason
    _is_gui_available.result = not reason

    return _is_gui_available.result

def is_resource_enabled(resource):
    """Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    """
    return use_resources is None or resource in use_resources

def requires(resource, msg=None):
    """Raise ResourceDenied if the specified resource is not available."""
    if not is_resource_enabled(resource):
        if msg is None:
            msg = "Use of the `%s' resource not enabled" % resource
        raise ResourceDenied(msg)
    if resource == 'gui' and not _is_gui_available():
        raise ResourceDenied(_is_gui_available.reason)

def requires_mac_ver(*min_version):
    """Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    """
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kw):
            if sys.platform == 'darwin':
                version_txt = platform.mac_ver()[0]
                try:
                    version = tuple(map(int, version_txt.split('.')))
                except ValueError:
                    pass
                else:
                    if version < min_version:
                        min_version_txt = '.'.join(map(str, min_version))
                        raise unittest.SkipTest(
                            "Mac OS X %s or higher required, not %s"
                            % (min_version_txt, version_txt))
            return func(*args, **kw)
        wrapper.min_version = min_version
        return wrapper
    return decorator


# Don't use "localhost", since resolving it uses the DNS under recent
# Windows versions (see issue #18792).
HOST = "127.0.0.1"
HOSTv6 = "::1"


def find_unused_port(family=socket.AF_INET, socktype=socket.SOCK_STREAM):
    """Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    socket.error will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it."""
    tempsock = socket.socket(family, socktype)
    port = bind_port(tempsock)
    tempsock.close()
    del tempsock
    return port

def bind_port(sock, host=HOST):
    """Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    """
    if sock.family == socket.AF_INET and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, 'SO_REUSEADDR'):
            if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
                raise TestFailed("tests should never set the SO_REUSEADDR "   \
                                 "socket option on TCP/IP sockets!")
        if hasattr(socket, 'SO_REUSEPORT'):
            try:
                if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
                    raise TestFailed("tests should never set the SO_REUSEPORT "   \
                                     "socket option on TCP/IP sockets!")
            except EnvironmentError:
                # Python's socket module was compiled using modern headers
                # thus defining SO_REUSEPORT but this process is running
                # under an older kernel that does not support SO_REUSEPORT.
                pass
        if hasattr(socket, 'SO_EXCLUSIVEADDRUSE'):
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)

    sock.bind((host, 0))
    port = sock.getsockname()[1]
    return port

def _is_ipv6_enabled():
    """Check whether IPv6 is enabled on this host."""
    if socket.has_ipv6:
        sock = None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            sock.bind((HOSTv6, 0))
            return True
        except socket.error:
            pass
        finally:
            if sock:
                sock.close()
    return False

IPV6_ENABLED = _is_ipv6_enabled()

def system_must_validate_cert(f):
    """Skip the test on TLS certificate validation failures."""
    @functools.wraps(f)
    def dec(*args, **kwargs):
        try:
            f(*args, **kwargs)
        except IOError as e:
            if "CERTIFICATE_VERIFY_FAILED" in str(e):
                raise unittest.SkipTest("system does not contain "
                                        "necessary certificates")
            raise
    return dec

FUZZ = 1e-6

def fcmp(x, y): # fuzzy comparison function
    if isinstance(x, float) or isinstance(y, float):
        try:
            fuzz = (abs(x) + abs(y)) * FUZZ
            if abs(x-y) <= fuzz:
                return 0
        except:
            pass
    elif type(x) == type(y) and isinstance(x, (tuple, list)):
        for i in range(min(len(x), len(y))):
            outcome = fcmp(x[i], y[i])
            if outcome != 0:
                return outcome
        return (len(x) > len(y)) - (len(x) < len(y))
    return (x > y) - (x < y)


# A constant likely larger than the underlying OS pipe buffer size, to
# make writes blocking.
# Windows limit seems to be around 512 B, and many Unix kernels have a
# 64 KiB pipe buffer size or 16 * PAGE_SIZE: take a few megs to be sure.
# (see issue #17835 for a discussion of this number).
PIPE_MAX_SIZE = 4 * 1024 * 1024 + 1

# A constant likely larger than the underlying OS socket buffer size, to make
# writes blocking.
# The socket buffer sizes can usually be tuned system-wide (e.g. through sysctl
# on Linux), or on a per-socket basis (SO_SNDBUF/SO_RCVBUF). See issue #18643
# for a discussion of this number).
SOCK_MAX_SIZE = 16 * 1024 * 1024 + 1

is_jython = sys.platform.startswith('java')

try:
    unicode
    have_unicode = True
except NameError:
    have_unicode = False

requires_unicode = unittest.skipUnless(have_unicode, 'no unicode support')

def u(s):
    return unicode(s, 'unicode-escape')

# FS_NONASCII: non-ASCII Unicode character encodable by
# sys.getfilesystemencoding(), or None if there is no such character.
FS_NONASCII = None
if have_unicode:
    for character in (
        # First try printable and common characters to have a readable filename.
        # For each character, the encoding list are just example of encodings able
        # to encode the character (the list is not exhaustive).

        # U+00E6 (Latin Small Letter Ae): cp1252, iso-8859-1
        unichr(0x00E6),
        # U+0130 (Latin Capital Letter I With Dot Above): cp1254, iso8859_3
        unichr(0x0130),
        # U+0141 (Latin Capital Letter L With Stroke): cp1250, cp1257
        unichr(0x0141),
        # U+03C6 (Greek Small Letter Phi): cp1253
        unichr(0x03C6),
        # U+041A (Cyrillic Capital Letter Ka): cp1251
        unichr(0x041A),
        # U+05D0 (Hebrew Letter Alef): Encodable to cp424
        unichr(0x05D0),
        # U+060C (Arabic Comma): cp864, cp1006, iso8859_6, mac_arabic
        unichr(0x060C),
        # U+062A (Arabic Letter Teh): cp720
        unichr(0x062A),
        # U+0E01 (Thai Character Ko Kai): cp874
        unichr(0x0E01),

        # Then try more "special" characters. "special" because they may be
        # interpreted or displayed differently depending on the exact locale
        # encoding and the font.

        # U+00A0 (No-Break Space)
        unichr(0x00A0),
        # U+20AC (Euro Sign)
        unichr(0x20AC),
    ):
        try:
            # In Windows, 'mbcs' is used, and encode() returns '?'
            # for characters missing in the ANSI codepage
            if character.encode(sys.getfilesystemencoding())\
                        .decode(sys.getfilesystemencoding())\
                    != character:
                raise UnicodeError
        except UnicodeError:
            pass
        else:
            FS_NONASCII = character
            break

# Filename used for testing
if os.name == 'java':
    # Jython disallows @ in module names
    TESTFN = '$test'
elif os.name == 'riscos':
    TESTFN = 'testfile'
else:
    TESTFN = '@test'
    # Unicode name only used if TEST_FN_ENCODING exists for the platform.
    if have_unicode:
        # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding()
        # TESTFN_UNICODE is a filename that can be encoded using the
        # file system encoding, but *not* with the default (ascii) encoding
        if isinstance('', unicode):
            # python -U
            # XXX perhaps unicode() should accept Unicode strings?
            TESTFN_UNICODE = "@test-\xe0\xf2"
        else:
            # 2 latin characters.
            TESTFN_UNICODE = unicode("@test-\xe0\xf2", "latin-1")
        TESTFN_ENCODING = sys.getfilesystemencoding()
        # TESTFN_UNENCODABLE is a filename that should *not* be
        # able to be encoded by *either* the default or filesystem encoding.
        # This test really only makes sense on Windows NT platforms
        # which have special Unicode support in posixmodule.
        if (not hasattr(sys, "getwindowsversion") or
                sys.getwindowsversion()[3] < 2): #  0=win32s or 1=9x/ME
            TESTFN_UNENCODABLE = None
        else:
            # Japanese characters (I think - from bug 846133)
            TESTFN_UNENCODABLE = eval('u"@test-\u5171\u6709\u3055\u308c\u308b"')
            try:
                # XXX - Note - should be using TESTFN_ENCODING here - but for
                # Windows, "mbcs" currently always operates as if in
                # errors=ignore' mode - hence we get '?' characters rather than
                # the exception.  'Latin1' operates as we expect - ie, fails.
                # See [ 850997 ] mbcs encoding ignores errors
                TESTFN_UNENCODABLE.encode("Latin1")
            except UnicodeEncodeError:
                pass
            else:
                print \
                'WARNING: The filename %r CAN be encoded by the filesystem.  ' \
                'Unicode filename tests may not be effective' \
                % TESTFN_UNENCODABLE


# Disambiguate TESTFN for parallel testing, while letting it remain a valid
# module name.
TESTFN = "{}_{}_tmp".format(TESTFN, os.getpid())

# Define the URL of a dedicated HTTP server for the network tests.
# The URL must use clear-text HTTP: no redirection to encrypted HTTPS.
TEST_HTTP_URL = "http://www.pythontest.net"

# Save the initial cwd
SAVEDCWD = os.getcwd()

@contextlib.contextmanager
def temp_dir(path=None, quiet=False):
    """Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    """
    dir_created = False
    if path is None:
        import tempfile
        path = tempfile.mkdtemp()
        dir_created = True
        path = os.path.realpath(path)
    else:
        if (have_unicode and isinstance(path, unicode) and
            not os.path.supports_unicode_filenames):
            try:
                path = path.encode(sys.getfilesystemencoding() or 'ascii')
            except UnicodeEncodeError:
                if not quiet:
                    raise unittest.SkipTest('unable to encode the cwd name with '
                                            'the filesystem encoding.')
        try:
            os.mkdir(path)
            dir_created = True
        except OSError:
            if not quiet:
                raise
            warnings.warn('tests may fail, unable to create temp dir: ' + path,
                          RuntimeWarning, stacklevel=3)
    if dir_created:
        pid = os.getpid()
    try:
        yield path
    finally:
        # In case the process forks, let only the parent remove the
        # directory. The child has a diffent process id. (bpo-30028)
        if dir_created and pid == os.getpid():
            rmtree(path)

@contextlib.contextmanager
def change_cwd(path, quiet=False):
    """Return a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    """
    saved_dir = os.getcwd()
    try:
        os.chdir(path)
    except OSError:
        if not quiet:
            raise
        warnings.warn('tests may fail, unable to change CWD to: ' + path,
                      RuntimeWarning, stacklevel=3)
    try:
        yield os.getcwd()
    finally:
        os.chdir(saved_dir)


@contextlib.contextmanager
def temp_cwd(name='tempcwd', quiet=False):
    """
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    """
    with temp_dir(path=name, quiet=quiet) as temp_path:
        with change_cwd(temp_path, quiet=quiet) as cwd_dir:
            yield cwd_dir

# TEST_HOME_DIR refers to the top level directory of the "test" package
# that contains Python's regression test suite
TEST_SUPPORT_DIR = os.path.dirname(os.path.abspath(__file__))
TEST_HOME_DIR = os.path.dirname(TEST_SUPPORT_DIR)

# TEST_DATA_DIR is used as a target download location for remote resources
TEST_DATA_DIR = os.path.join(TEST_HOME_DIR, "data")

def findfile(file, subdir=None):
    """Try to find a file on sys.path and the working directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path)."""
    if os.path.isabs(file):
        return file
    if subdir is not None:
        file = os.path.join(subdir, file)
    path = [TEST_HOME_DIR] + sys.path
    for dn in path:
        fn = os.path.join(dn, file)
        if os.path.exists(fn): return fn
    return file

def sortdict(dict):
    "Like repr(dict), but in sorted order."
    items = dict.items()
    items.sort()
    reprpairs = ["%r: %r" % pair for pair in items]
    withcommas = ", ".join(reprpairs)
    return "{%s}" % withcommas

def make_bad_fd():
    """
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    """
    file = open(TESTFN, "wb")
    try:
        return file.fileno()
    finally:
        file.close()
        unlink(TESTFN)

def check_syntax_error(testcase, statement, errtext='', lineno=None, offset=None):
    with testcase.assertRaisesRegexp(SyntaxError, errtext) as cm:
        compile(statement, '<test string>', 'exec')
    err = cm.exception
    if lineno is not None:
        testcase.assertEqual(err.lineno, lineno)
    if offset is not None:
        testcase.assertEqual(err.offset, offset)

def open_urlresource(url, check=None):
    import urlparse, urllib2

    filename = urlparse.urlparse(url)[2].split('/')[-1] # '/': it's URL!

    fn = os.path.join(TEST_DATA_DIR, filename)

    def check_valid_file(fn):
        f = open(fn)
        if check is None:
            return f
        elif check(f):
            f.seek(0)
            return f
        f.close()

    if os.path.exists(fn):
        f = check_valid_file(fn)
        if f is not None:
            return f
        unlink(fn)

    # Verify the requirement before downloading the file
    requires('urlfetch')

    print >> get_original_stdout(), '\tfetching %s ...' % url
    f = urllib2.urlopen(url, timeout=15)
    try:
        with open(fn, "wb") as out:
            s = f.read()
            while s:
                out.write(s)
                s = f.read()
    finally:
        f.close()

    f = check_valid_file(fn)
    if f is not None:
        return f
    raise TestFailed('invalid resource "%s"' % fn)


class WarningsRecorder(object):
    """Convenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    """
    def __init__(self, warnings_list):
        self._warnings = warnings_list
        self._last = 0

    def __getattr__(self, attr):
        if len(self._warnings) > self._last:
            return getattr(self._warnings[-1], attr)
        elif attr in warnings.WarningMessage._WARNING_DETAILS:
            return None
        raise AttributeError("%r has no attribute %r" % (self, attr))

    @property
    def warnings(self):
        return self._warnings[self._last:]

    def reset(self):
        self._last = len(self._warnings)


def _filterwarnings(filters, quiet=False):
    """Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    """
    # Clear the warning registry of the calling module
    # in order to re-raise the warnings.
    frame = sys._getframe(2)
    registry = frame.f_globals.get('__warningregistry__')
    if registry:
        registry.clear()
    with warnings.catch_warnings(record=True) as w:
        # Set filter "always" to record all warnings.  Because
        # test_warnings swap the module, we need to look up in
        # the sys.modules dictionary.
        sys.modules['warnings'].simplefilter("always")
        yield WarningsRecorder(w)
    # Filter the recorded warnings
    reraise = [warning.message for warning in w]
    missing = []
    for msg, cat in filters:
        seen = False
        for exc in reraise[:]:
            message = str(exc)
            # Filter out the matching messages
            if (re.match(msg, message, re.I) and
                issubclass(exc.__class__, cat)):
                seen = True
                reraise.remove(exc)
        if not seen and not quiet:
            # This filter caught nothing
            missing.append((msg, cat.__name__))
    if reraise:
        raise AssertionError("unhandled warning %r" % reraise[0])
    if missing:
        raise AssertionError("filter (%r, %s) did not catch any warning" %
                             missing[0])


@contextlib.contextmanager
def check_warnings(*filters, **kwargs):
    """Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    """
    quiet = kwargs.get('quiet')
    if not filters:
        filters = (("", Warning),)
        # Preserve backward compatibility
        if quiet is None:
            quiet = True
    return _filterwarnings(filters, quiet)


@contextlib.contextmanager
def check_py3k_warnings(*filters, **kwargs):
    """Context manager to silence py3k warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default False)

    Without argument, it defaults to:
        check_py3k_warnings(("", DeprecationWarning), quiet=False)
    """
    if sys.py3kwarning:
        if not filters:
            filters = (("", DeprecationWarning),)
    else:
        # It should not raise any py3k warning
        filters = ()
    return _filterwarnings(filters, kwargs.get('quiet'))


class CleanImport(object):
    """Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    """

    def __init__(self, *module_names):
        self.original_modules = sys.modules.copy()
        for module_name in module_names:
            if module_name in sys.modules:
                module = sys.modules[module_name]
                # It is possible that module_name is just an alias for
                # another module (e.g. stub for modules renamed in 3.x).
                # In that case, we also need delete the real module to clear
                # the import cache.
                if module.__name__ != module_name:
                    del sys.modules[module.__name__]
                del sys.modules[module_name]

    def __enter__(self):
        return self

    def __exit__(self, *ignore_exc):
        sys.modules.update(self.original_modules)


class EnvironmentVarGuard(UserDict.DictMixin):

    """Class to help protect the environment variable properly.  Can be used as
    a context manager."""

    def __init__(self):
        self._environ = os.environ
        self._changed = {}

    def __getitem__(self, envvar):
        return self._environ[envvar]

    def __setitem__(self, envvar, value):
        # Remember the initial value on the first access
        if envvar not in self._changed:
            self._changed[envvar] = self._environ.get(envvar)
        self._environ[envvar] = value

    def __delitem__(self, envvar):
        # Remember the initial value on the first access
        if envvar not in self._changed:
            self._changed[envvar] = self._environ.get(envvar)
        if envvar in self._environ:
            del self._environ[envvar]

    def keys(self):
        return self._environ.keys()

    def set(self, envvar, value):
        self[envvar] = value

    def unset(self, envvar):
        del self[envvar]

    def __enter__(self):
        return self

    def __exit__(self, *ignore_exc):
        for (k, v) in self._changed.items():
            if v is None:
                if k in self._environ:
                    del self._environ[k]
            else:
                self._environ[k] = v
        os.environ = self._environ


class DirsOnSysPath(object):
    """Context manager to temporarily add directories to sys.path.

    This makes a copy of sys.path, appends any directories given
    as positional arguments, then reverts sys.path to the copied
    settings when the context ends.

    Note that *all* sys.path modifications in the body of the
    context manager, including replacement of the object,
    will be reverted at the end of the block.
    """

    def __init__(self, *paths):
        self.original_value = sys.path[:]
        self.original_object = sys.path
        sys.path.extend(paths)

    def __enter__(self):
        return self

    def __exit__(self, *ignore_exc):
        sys.path = self.original_object
        sys.path[:] = self.original_value


class TransientResource(object):

    """Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes."""

    def __init__(self, exc, **kwargs):
        self.exc = exc
        self.attrs = kwargs

    def __enter__(self):
        return self

    def __exit__(self, type_=None, value=None, traceback=None):
        """If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any)."""
        if type_ is not None and issubclass(self.exc, type_):
            for attr, attr_value in self.attrs.iteritems():
                if not hasattr(value, attr):
                    break
                if getattr(value, attr) != attr_value:
                    break
            else:
                raise ResourceDenied("an optional resource is not available")


@contextlib.contextmanager
def transient_internet(resource_name, timeout=30.0, errnos=()):
    """Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions."""
    default_errnos = [
        ('ECONNREFUSED', 111),
        ('ECONNRESET', 104),
        ('EHOSTUNREACH', 113),
        ('ENETUNREACH', 101),
        ('ETIMEDOUT', 110),
        # socket.create_connection() fails randomly with
        # EADDRNOTAVAIL on Travis CI.
        ('EADDRNOTAVAIL', 99),
    ]
    default_gai_errnos = [
        ('EAI_AGAIN', -3),
        ('EAI_FAIL', -4),
        ('EAI_NONAME', -2),
        ('EAI_NODATA', -5),
        # Windows defines EAI_NODATA as 11001 but idiotic getaddrinfo()
        # implementation actually returns WSANO_DATA i.e. 11004.
        ('WSANO_DATA', 11004),
    ]

    denied = ResourceDenied("Resource '%s' is not available" % resource_name)
    captured_errnos = errnos
    gai_errnos = []
    if not captured_errnos:
        captured_errnos = [getattr(errno, name, num)
                           for (name, num) in default_errnos]
        gai_errnos = [getattr(socket, name, num)
                      for (name, num) in default_gai_errnos]

    def filter_error(err):
        n = getattr(err, 'errno', None)
        if (isinstance(err, socket.timeout) or
            (isinstance(err, socket.gaierror) and n in gai_errnos) or
            n in captured_errnos):
            if not verbose:
                sys.stderr.write(denied.args[0] + "\n")
            raise denied

    old_timeout = socket.getdefaulttimeout()
    try:
        if timeout is not None:
            socket.setdefaulttimeout(timeout)
        yield
    except IOError as err:
        # urllib can wrap original socket errors multiple times (!), we must
        # unwrap to get at the original error.
        while True:
            a = err.args
            if len(a) >= 1 and isinstance(a[0], IOError):
                err = a[0]
            # The error can also be wrapped as args[1]:
            #    except socket.error as msg:
            #        raise IOError('socket error', msg).with_traceback(sys.exc_info()[2])
            elif len(a) >= 2 and isinstance(a[1], IOError):
                err = a[1]
            else:
                break
        filter_error(err)
        raise
    # XXX should we catch generic exceptions and look for their
    # __cause__ or __context__?
    finally:
        socket.setdefaulttimeout(old_timeout)


@contextlib.contextmanager
def captured_output(stream_name):
    """Return a context manager used by captured_stdout and captured_stdin
    that temporarily replaces the sys stream *stream_name* with a StringIO."""
    import StringIO
    orig_stdout = getattr(sys, stream_name)
    setattr(sys, stream_name, StringIO.StringIO())
    try:
        yield getattr(sys, stream_name)
    finally:
        setattr(sys, stream_name, orig_stdout)

def captured_stdout():
    """Capture the output of sys.stdout:

       with captured_stdout() as s:
           print "hello"
       self.assertEqual(s.getvalue(), "hello")
    """
    return captured_output("stdout")

def captured_stderr():
    return captured_output("stderr")

def captured_stdin():
    return captured_output("stdin")

def gc_collect():
    """Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    """
    gc.collect()
    if is_jython:
        time.sleep(0.1)
    gc.collect()
    gc.collect()


_header = '2P'
if hasattr(sys, "gettotalrefcount"):
    _header = '2P' + _header
_vheader = _header + 'P'

def calcobjsize(fmt):
    return struct.calcsize(_header + fmt + '0P')

def calcvobjsize(fmt):
    return struct.calcsize(_vheader + fmt + '0P')


_TPFLAGS_HAVE_GC = 1<<14
_TPFLAGS_HEAPTYPE = 1<<9

def check_sizeof(test, o, size):
    import _testcapi
    result = sys.getsizeof(o)
    # add GC header size
    if ((type(o) == type) and (o.__flags__ & _TPFLAGS_HEAPTYPE) or\
        ((type(o) != type) and (type(o).__flags__ & _TPFLAGS_HAVE_GC))):
        size += _testcapi.SIZEOF_PYGC_HEAD
    msg = 'wrong size for %s: got %d, expected %d' \
            % (type(o), result, size)
    test.assertEqual(result, size, msg)


#=======================================================================
# Decorator for running a function in a different locale, correctly resetting
# it afterwards.

def run_with_locale(catstr, *locales):
    def decorator(func):
        def inner(*args, **kwds):
            try:
                import locale
                category = getattr(locale, catstr)
                orig_locale = locale.setlocale(category)
            except AttributeError:
                # if the test author gives us an invalid category string
                raise
            except:
                # cannot retrieve original locale, so do nothing
                locale = orig_locale = None
            else:
                for loc in locales:
                    try:
                        locale.setlocale(category, loc)
                        break
                    except:
                        pass

            # now run the function, resetting the locale on exceptions
            try:
                return func(*args, **kwds)
            finally:
                if locale and orig_locale:
                    locale.setlocale(category, orig_locale)
        inner.func_name = func.func_name
        inner.__doc__ = func.__doc__
        return inner
    return decorator

#=======================================================================
# Decorator for running a function in a specific timezone, correctly
# resetting it afterwards.

def run_with_tz(tz):
    def decorator(func):
        def inner(*args, **kwds):
            try:
                tzset = time.tzset
            except AttributeError:
                raise unittest.SkipTest("tzset required")
            if 'TZ' in os.environ:
                orig_tz = os.environ['TZ']
            else:
                orig_tz = None
            os.environ['TZ'] = tz
            tzset()

            # now run the function, resetting the tz on exceptions
            try:
                return func(*args, **kwds)
            finally:
                if orig_tz is None:
                    del os.environ['TZ']
                else:
                    os.environ['TZ'] = orig_tz
                time.tzset()

        inner.__name__ = func.__name__
        inner.__doc__ = func.__doc__
        return inner
    return decorator

#=======================================================================
# Big-memory-test support. Separate from 'resources' because memory use should be configurable.

# Some handy shorthands. Note that these are used for byte-limits as well
# as size-limits, in the various bigmem tests
_1M = 1024*1024
_1G = 1024 * _1M
_2G = 2 * _1G
_4G = 4 * _1G

MAX_Py_ssize_t = sys.maxsize

def set_memlimit(limit):
    global max_memuse
    global real_max_memuse
    sizes = {
        'k': 1024,
        'm': _1M,
        'g': _1G,
        't': 1024*_1G,
    }
    m = re.match(r'(\d+(\.\d+)?) (K|M|G|T)b?$', limit,
                 re.IGNORECASE | re.VERBOSE)
    if m is None:
        raise ValueError('Invalid memory limit %r' % (limit,))
    memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
    real_max_memuse = memlimit
    if memlimit > MAX_Py_ssize_t:
        memlimit = MAX_Py_ssize_t
    if memlimit < _2G - 1:
        raise ValueError('Memory limit %r too low to be useful' % (limit,))
    max_memuse = memlimit

def bigmemtest(minsize, memuse, overhead=5*_1M):
    """Decorator for bigmem tests.

    'minsize' is the minimum useful size for the test (in arbitrary,
    test-interpreted units.) 'memuse' is the number of 'bytes per size' for
    the test, or a good estimate of it. 'overhead' specifies fixed overhead,
    independent of the testsize, and defaults to 5Mb.

    The decorator tries to guess a good value for 'size' and passes it to
    the decorated test function. If minsize * memuse is more than the
    allowed memory use (as defined by max_memuse), the test is skipped.
    Otherwise, minsize is adjusted upward to use up to max_memuse.
    """
    def decorator(f):
        def wrapper(self):
            if not max_memuse:
                # If max_memuse is 0 (the default),
                # we still want to run the tests with size set to a few kb,
                # to make sure they work. We still want to avoid using
                # too much memory, though, but we do that noisily.
                maxsize = 5147
                self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
            else:
                maxsize = int((max_memuse - overhead) / memuse)
                if maxsize < minsize:
                    # Really ought to print 'test skipped' or something
                    if verbose:
                        sys.stderr.write("Skipping %s because of memory "
                                         "constraint\n" % (f.__name__,))
                    return
                # Try to keep some breathing room in memory use
                maxsize = max(maxsize - 50 * _1M, minsize)
            return f(self, maxsize)
        wrapper.minsize = minsize
        wrapper.memuse = memuse
        wrapper.overhead = overhead
        return wrapper
    return decorator

def precisionbigmemtest(size, memuse, overhead=5*_1M, dry_run=True):
    def decorator(f):
        def wrapper(self):
            if not real_max_memuse:
                maxsize = 5147
            else:
                maxsize = size

            if ((real_max_memuse or not dry_run)
                and real_max_memuse < maxsize * memuse):
                if verbose:
                    sys.stderr.write("Skipping %s because of memory "
                                     "constraint\n" % (f.__name__,))
                return

            return f(self, maxsize)
        wrapper.size = size
        wrapper.memuse = memuse
        wrapper.overhead = overhead
        return wrapper
    return decorator

def bigaddrspacetest(f):
    """Decorator for tests that fill the address space."""
    def wrapper(self):
        if max_memuse < MAX_Py_ssize_t:
            if verbose:
                sys.stderr.write("Skipping %s because of memory "
                                 "constraint\n" % (f.__name__,))
        else:
            return f(self)
    return wrapper

#=======================================================================
# unittest integration.

class BasicTestRunner:
    def run(self, test):
        result = unittest.TestResult()
        test(result)
        return result

def _id(obj):
    return obj

def requires_resource(resource):
    if resource == 'gui' and not _is_gui_available():
        return unittest.skip(_is_gui_available.reason)
    if is_resource_enabled(resource):
        return _id
    else:
        return unittest.skip("resource {0!r} is not enabled".format(resource))

def cpython_only(test):
    """
    Decorator for tests only applicable on CPython.
    """
    return impl_detail(cpython=True)(test)

def impl_detail(msg=None, **guards):
    if check_impl_detail(**guards):
        return _id
    if msg is None:
        guardnames, default = _parse_guards(guards)
        if default:
            msg = "implementation detail not available on {0}"
        else:
            msg = "implementation detail specific to {0}"
        guardnames = sorted(guardnames.keys())
        msg = msg.format(' or '.join(guardnames))
    return unittest.skip(msg)

def _parse_guards(guards):
    # Returns a tuple ({platform_name: run_me}, default_value)
    if not guards:
        return ({'cpython': True}, False)
    is_true = guards.values()[0]
    assert guards.values() == [is_true] * len(guards)   # all True or all False
    return (guards, not is_true)

# Use the following check to guard CPython's implementation-specific tests --
# or to run them only on the implementation(s) guarded by the arguments.
def check_impl_detail(**guards):
    """This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    """
    guards, default = _parse_guards(guards)
    return guards.get(platform.python_implementation().lower(), default)


def _filter_suite(suite, pred):
    """Recursively filter test cases in a suite based on a predicate."""
    newtests = []
    for test in suite._tests:
        if isinstance(test, unittest.TestSuite):
            _filter_suite(test, pred)
            newtests.append(test)
        else:
            if pred(test):
                newtests.append(test)
    suite._tests = newtests

def _run_suite(suite):
    """Run tests from a unittest.TestSuite-derived class."""
    if verbose:
        runner = unittest.TextTestRunner(sys.stdout, verbosity=2,
                                         failfast=failfast)
    else:
        runner = BasicTestRunner()

    result = runner.run(suite)
    if not result.testsRun and not result.skipped:
        raise TestDidNotRun
    if not result.wasSuccessful():
        if len(result.errors) == 1 and not result.failures:
            err = result.errors[0][1]
        elif len(result.failures) == 1 and not result.errors:
            err = result.failures[0][1]
        else:
            err = "multiple errors occurred"
            if not verbose:
                err += "; run in verbose mode for details"
        raise TestFailed(err)


# By default, don't filter tests
_match_test_func = None
_match_test_patterns = None


def match_test(test):
    # Function used by support.run_unittest() and regrtest --list-cases
    if _match_test_func is None:
        return True
    else:
        return _match_test_func(test.id())


def _is_full_match_test(pattern):
    # If a pattern contains at least one dot, it's considered
    # as a full test identifier.
    # Example: 'test.test_os.FileTests.test_access'.
    #
    # Reject patterns which contain fnmatch patterns: '*', '?', '[...]'
    # or '[!...]'. For example, reject 'test_access*'.
    return ('.' in pattern) and (not re.search(r'[?*\[\]]', pattern))


def set_match_tests(patterns):
    global _match_test_func, _match_test_patterns

    if patterns == _match_test_patterns:
        # No change: no need to recompile patterns.
        return

    if not patterns:
        func = None
        # set_match_tests(None) behaves as set_match_tests(())
        patterns = ()
    elif all(map(_is_full_match_test, patterns)):
        # Simple case: all patterns are full test identifier.
        # The test.bisect utility only uses such full test identifiers.
        func = set(patterns).__contains__
    else:
        regex = '|'.join(map(fnmatch.translate, patterns))
        # The search *is* case sensitive on purpose:
        # don't use flags=re.IGNORECASE
        regex_match = re.compile(regex).match

        def match_test_regex(test_id):
            if regex_match(test_id):
                # The regex matchs the whole identifier like
                # 'test.test_os.FileTests.test_access'
                return True
            else:
                # Try to match parts of the test identifier.
                # For example, split 'test.test_os.FileTests.test_access'
                # into: 'test', 'test_os', 'FileTests' and 'test_access'.
                return any(map(regex_match, test_id.split(".")))

        func = match_test_regex

    # Create a copy since patterns can be mutable and so modified later
    _match_test_patterns = tuple(patterns)
    _match_test_func = func



def run_unittest(*classes):
    """Run tests from unittest.TestCase-derived classes."""
    valid_types = (unittest.TestSuite, unittest.TestCase)
    suite = unittest.TestSuite()
    for cls in classes:
        if isinstance(cls, str):
            if cls in sys.modules:
                suite.addTest(unittest.findTestCases(sys.modules[cls]))
            else:
                raise ValueError("str arguments must be keys in sys.modules")
        elif isinstance(cls, valid_types):
            suite.addTest(cls)
        else:
            suite.addTest(unittest.makeSuite(cls))
    _filter_suite(suite, match_test)
    _run_suite(suite)

#=======================================================================
# Check for the presence of docstrings.

HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or
                   sys.platform == 'win32' or
                   sysconfig.get_config_var('WITH_DOC_STRINGS'))

requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
                                          "test requires docstrings")


#=======================================================================
# doctest driver.

def run_doctest(module, verbosity=None):
    """Run doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    test.support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    """

    import doctest

    if verbosity is None:
        verbosity = verbose
    else:
        verbosity = None

    # Direct doctest output (normally just errors) to real stdout; doctest
    # output shouldn't be compared by regrtest.
    save_stdout = sys.stdout
    sys.stdout = get_original_stdout()
    try:
        f, t = doctest.testmod(module, verbose=verbosity)
        if f:
            raise TestFailed("%d of %d doctests failed" % (f, t))
    finally:
        sys.stdout = save_stdout
    if verbose:
        print 'doctest (%s) ... %d tests with zero failures' % (module.__name__, t)
    return f, t

#=======================================================================
# Threading support to prevent reporting refleaks when running regrtest.py -R

# Flag used by saved_test_environment of test.libregrtest.save_env,
# to check if a test modified the environment. The flag should be set to False
# before running a new test.
#
# For example, threading_cleanup() sets the flag is the function fails
# to cleanup threads.
environment_altered = False

# NOTE: we use thread._count() rather than threading.enumerate() (or the
# moral equivalent thereof) because a threading.Thread object is still alive
# until its __bootstrap() method has returned, even after it has been
# unregistered from the threading module.
# thread._count(), on the other hand, only gets decremented *after* the
# __bootstrap() method has returned, which gives us reliable reference counts
# at the end of a test run.

def threading_setup():
    if thread:
        return thread._count(),
    else:
        return 1,

def threading_cleanup(nb_threads):
    if not thread:
        return

    _MAX_COUNT = 10
    for count in range(_MAX_COUNT):
        n = thread._count()
        if n == nb_threads:
            break
        time.sleep(0.1)
    # XXX print a warning in case of failure?

def reap_threads(func):
    """Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    """
    if not thread:
        return func

    @functools.wraps(func)
    def decorator(*args):
        key = threading_setup()
        try:
            return func(*args)
        finally:
            threading_cleanup(*key)
    return decorator


@contextlib.contextmanager
def wait_threads_exit(timeout=60.0):
    """
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    """
    old_count = thread._count()
    try:
        yield
    finally:
        start_time = time.time()
        deadline = start_time + timeout
        while True:
            count = thread._count()
            if count <= old_count:
                break
            if time.time() > deadline:
                dt = time.time() - start_time
                msg = ("wait_threads() failed to cleanup %s "
                       "threads after %.1f seconds "
                       "(count: %s, old count: %s)"
                       % (count - old_count, dt, count, old_count))
                raise AssertionError(msg)
            time.sleep(0.010)
            gc_collect()


def reap_children():
    """Use this function at the end of test_main() whenever sub-processes
    are started.  This will help ensure that no extra children (zombies)
    stick around to hog resources and create problems when looking
    for refleaks.
    """

    # Reap all our dead child processes so we don't leave zombies around.
    # These hog resources and might be causing some of the buildbots to die.
    if hasattr(os, 'waitpid'):
        any_process = -1
        while True:
            try:
                # This will raise an exception on Windows.  That's ok.
                pid, status = os.waitpid(any_process, os.WNOHANG)
                if pid == 0:
                    break
            except:
                break

@contextlib.contextmanager
def start_threads(threads, unlock=None):
    threads = list(threads)
    started = []
    try:
        try:
            for t in threads:
                t.start()
                started.append(t)
        except:
            if verbose:
                print("Can't start %d threads, only %d threads started" %
                      (len(threads), len(started)))
            raise
        yield
    finally:
        if unlock:
            unlock()
        endtime = starttime = time.time()
        for timeout in range(1, 16):
            endtime += 60
            for t in started:
                t.join(max(endtime - time.time(), 0.01))
            started = [t for t in started if t.isAlive()]
            if not started:
                break
            if verbose:
                print('Unable to join %d threads during a period of '
                      '%d minutes' % (len(started), timeout))
    started = [t for t in started if t.isAlive()]
    if started:
        raise AssertionError('Unable to join %d threads' % len(started))

@contextlib.contextmanager
def swap_attr(obj, attr, new_val):
    """Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        This will set obj.attr to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `attr` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    """
    if hasattr(obj, attr):
        real_val = getattr(obj, attr)
        setattr(obj, attr, new_val)
        try:
            yield real_val
        finally:
            setattr(obj, attr, real_val)
    else:
        setattr(obj, attr, new_val)
        try:
            yield
        finally:
            if hasattr(obj, attr):
                delattr(obj, attr)

@contextlib.contextmanager
def swap_item(obj, item, new_val):
    """Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    """
    if item in obj:
        real_val = obj[item]
        obj[item] = new_val
        try:
            yield real_val
        finally:
            obj[item] = real_val
    else:
        obj[item] = new_val
        try:
            yield
        finally:
            if item in obj:
                del obj[item]

def py3k_bytes(b):
    """Emulate the py3k bytes() constructor.

    NOTE: This is only a best effort function.
    """
    try:
        # memoryview?
        return b.tobytes()
    except AttributeError:
        try:
            # iterable of ints?
            return b"".join(chr(x) for x in b)
        except TypeError:
            return bytes(b)

requires_type_collecting = unittest.skipIf(hasattr(sys, 'getcounts'),
                        'types are immortal if COUNT_ALLOCS is defined')

def args_from_interpreter_flags():
    """Return a list of command-line arguments reproducing the current
    settings in sys.flags."""
    import subprocess
    return subprocess._args_from_interpreter_flags()

def strip_python_stderr(stderr):
    """Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    """
    stderr = re.sub(br"\[\d+ refs\]\r?\n?$", b"", stderr).strip()
    return stderr


def check_free_after_iterating(test, iter, cls, args=()):
    class A(cls):
        def __del__(self):
            done[0] = True
            try:
                next(it)
            except StopIteration:
                pass

    done = [False]
    it = iter(A(*args))
    # Issue 26494: Shouldn't crash
    test.assertRaises(StopIteration, next, it)
    # The sequence should be deallocated just after the end of iterating
    gc_collect()
    test.assertTrue(done[0])

@contextlib.contextmanager
def disable_gc():
    have_gc = gc.isenabled()
    gc.disable()
    try:
        yield
    finally:
        if have_gc:
            gc.enable()


def python_is_optimized():
    """Find if Python was built with optimizations."""
    cflags = sysconfig.get_config_var('PY_CFLAGS') or ''
    final_opt = ""
    for opt in cflags.split():
        if opt.startswith('-O'):
            final_opt = opt
    return final_opt not in ('', '-O0', '-Og')


class SuppressCrashReport:
    """Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    """
    old_value = None
    old_modes = None

    def __enter__(self):
        """On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        """
        if sys.platform.startswith('win'):
            # see http://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx
            # GetErrorMode is not available on Windows XP and Windows Server 2003,
            # but SetErrorMode returns the previous value, so we can use that
            import ctypes
            self._k32 = ctypes.windll.kernel32
            SEM_NOGPFAULTERRORBOX = 0x02
            self.old_value = self._k32.SetErrorMode(SEM_NOGPFAULTERRORBOX)
            self._k32.SetErrorMode(self.old_value | SEM_NOGPFAULTERRORBOX)

            # Suppress assert dialogs in debug builds
            # (see http://bugs.python.org/issue23314)
            try:
                import _testcapi
                _testcapi.CrtSetReportMode
            except (AttributeError, ImportError):
                # no _testcapi or a release build
                pass
            else:
                self.old_modes = {}
                for report_type in [_testcapi.CRT_WARN,
                                    _testcapi.CRT_ERROR,
                                    _testcapi.CRT_ASSERT]:
                    old_mode = _testcapi.CrtSetReportMode(report_type,
                            _testcapi.CRTDBG_MODE_FILE)
                    old_file = _testcapi.CrtSetReportFile(report_type,
                            _testcapi.CRTDBG_FILE_STDERR)
                    self.old_modes[report_type] = old_mode, old_file

        else:
            try:
                import resource
            except ImportError:
                resource = None

            if resource is not None:
                try:
                    self.old_value = resource.getrlimit(resource.RLIMIT_CORE)
                    resource.setrlimit(resource.RLIMIT_CORE,
                                       (0, self.old_value[1]))
                except (ValueError, OSError):
                    pass

            if sys.platform == 'darwin':
                # Check if the 'Crash Reporter' on OSX was configured
                # in 'Developer' mode and warn that it will get triggered
                # when it is.
                #
                # This assumes that this context manager is used in tests
                # that might trigger the next manager.
                import subprocess
                cmd = ['/usr/bin/defaults', 'read',
                       'com.apple.CrashReporter', 'DialogType']
                proc = subprocess.Popen(cmd,
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE)
                stdout = proc.communicate()[0]
                if stdout.strip() == b'developer':
                    sys.stdout.write("this test triggers the Crash Reporter, "
                                     "that is intentional")
                    sys.stdout.flush()

        return self

    def __exit__(self, *ignore_exc):
        """Restore Windows ErrorMode or core file behavior to initial value."""
        if self.old_value is None:
            return

        if sys.platform.startswith('win'):
            self._k32.SetErrorMode(self.old_value)

            if self.old_modes:
                import _testcapi
                for report_type, (old_mode, old_file) in self.old_modes.items():
                    _testcapi.CrtSetReportMode(report_type, old_mode)
                    _testcapi.CrtSetReportFile(report_type, old_file)
        else:
            import resource
            try:
                resource.setrlimit(resource.RLIMIT_CORE, self.old_value)
            except (ValueError, OSError):
                pass


def _crash_python():
    """Deliberate crash of Python.

    Python can be killed by a segmentation fault (SIGSEGV), a bus error
    (SIGBUS), or a different error depending on the platform.

    Use SuppressCrashReport() to prevent a crash report from popping up.
    """

    import _testcapi
    with SuppressCrashReport():
        _testcapi._read_null()


def fd_count():
    """Count the number of open file descriptors.
    """
    if sys.platform.startswith(('linux', 'freebsd')):
        try:
            names = os.listdir("/proc/self/fd")
            # Substract one because listdir() opens internally a file
            # descriptor to list the content of the /proc/self/fd/ directory.
            return len(names) - 1
        except OSError as exc:
            if exc.errno != errno.ENOENT:
                raise

    MAXFD = 256
    if hasattr(os, 'sysconf'):
        try:
            MAXFD = os.sysconf("SC_OPEN_MAX")
        except OSError:
            pass

    old_modes = None
    if sys.platform == 'win32':
        # bpo-25306, bpo-31009: Call CrtSetReportMode() to not kill the process
        # on invalid file descriptor if Python is compiled in debug mode
        try:
            import msvcrt
            msvcrt.CrtSetReportMode
        except (AttributeError, ImportError):
            # no msvcrt or a release build
            pass
        else:
            old_modes = {}
            for report_type in (msvcrt.CRT_WARN,
                                msvcrt.CRT_ERROR,
                                msvcrt.CRT_ASSERT):
                old_modes[report_type] = msvcrt.CrtSetReportMode(report_type, 0)

    try:
        count = 0
        for fd in range(MAXFD):
            try:
                # Prefer dup() over fstat(). fstat() can require input/output
                # whereas dup() doesn't.
                fd2 = os.dup(fd)
            except OSError as e:
                if e.errno != errno.EBADF:
                    raise
            else:
                os.close(fd2)
                count += 1
    finally:
        if old_modes is not None:
            for report_type in (msvcrt.CRT_WARN,
                                msvcrt.CRT_ERROR,
                                msvcrt.CRT_ASSERT):
                msvcrt.CrtSetReportMode(report_type, old_modes[report_type])

    return count


class SaveSignals:
    """
    Save an restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    """

    def __init__(self):
        import signal
        self.signal = signal
        self.signals = list(range(1, signal.NSIG))
        # SIGKILL and SIGSTOP signals cannot be ignored nor catched
        for signame in ('SIGKILL', 'SIGSTOP'):
            try:
                signum = getattr(signal, signame)
            except AttributeError:
                continue
            self.signals.remove(signum)
        self.handlers = {}

    def save(self):
        for signum in self.signals:
            handler = self.signal.getsignal(signum)
            if handler is None:
                # getsignal() returns None if a signal handler was not
                # registered by the Python signal module,
                # and the handler is not SIG_DFL nor SIG_IGN.
                #
                # Ignore the signal: we cannot restore the handler.
                continue
            self.handlers[signum] = handler

    def restore(self):
        for signum, handler in self.handlers.items():
            self.signal.signal(signum, handler)
PK�R�ZO?
�V�V�1support/__pycache__/__init__.cpython-36.opt-2.pycnu�[���3

�\dh����@sX
edkred��ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
ZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z!ddl"Z"ddl#m$Z$yddl%Z%ddl&Z&Wnek
�r>dZ%dZ&YnXyddl'Z(Wnek
�rfdZ(YnXyddl)Z)Wnek
�r�dZ)YnXyddl*Z*Wnek
�r�dZ*YnXyddl+Z+Wnek
�r�dZ+YnXyddl,Z,Wnek
�rdZ,YnXyddl-Z-Wnek
�r.dZ-YnXyddl.Z.Wnek
�rVdZ.YnXdddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dag\Z/Gdbd�de0�Z1Gdcd�de1�Z2Gddd
�d
e1�Z3Gded�dej4�Z5ej6�dedgdh��Z7�dffdj�dkd�Z8dldm�Z9dndo�Z:dpd<�Z;dqd=�Z<ffdifdrd�Z=dsd8�Z>dZ?dZ@daAdaBdZCdiZDdaEdtd�ZFdud�ZGdvd�ZHdwdx�ZIejjJdy��r*�dgdzd{�ZKd|d}�ZLd~d�ZMd�d��ZNd�d��ZOnejPZLejQZMd�d��ZNd�d��ZOd�d�ZPd�d��ZQd�d�ZRd�d��ZSd�d�ZTd�d��ZUd�d"�ZV�dhd�d#�ZWd�d��ZXd�d$�ZYd�d%�ZZd�d&�Z[�did�d'�Z\d�Z]d�Z^ej_ej`fd�dI�Zae]fd�dJ�Zbd�dL�Zcd�d��Zded�Zed�d��Zf�dlZg�doZhejiejjkd��jJd��d��Zlejie)d��Zmejie*d��Znejie+d��Zoejie,d��ZpejjJd��Zqejrd��Zsesdk	�otesdkZtejd�k�r�et�r�d�nd�ZundZuejvd�k�r�d�Zwnd�Zwd�jxewejy��ZwdZzxL�dpD]BZ{yej|ej}e{��e{k�r�e~�Wne~k
�rYnXe{ZzP�q�Wewd�Zejd�k�r6ddl�Z�e�j�d�e�Zej��Z�dZ�ejvd�k�r�ej��jd�k�r�ewd�Z�ye�j�e��Wne�k
�r�YnXe�d�e�e�f�dZ�nBejd�k�r�yd�j�e��Wn&e�k
�r�ewd�j�e�dƃZ�YnXdZ�xF�dqD]<Zvyevj�e��Wn&e�k
�r(ej}ew�evZ�PYnX�q�Wez�rDewd�ezZ�ndZ�ej��Z�diZ�diZ�ej6�drd�d̈́�Z�ej6�dsd�dτ�Z�ej6�dtd�d��Z�e�ed҃�r�ej6d�dM��Z�ej�j�ej�j�e���Z�ej�j�e��Z�ej�j�e�dԃZ��dud�d�Z�d�d�Z�d�d]�Z�d�dلZ�dddڜd�d(�Z�d�dK�Z�Gd�dބd�e��Z��dvd�d�Z�ej6d�dT��Z�ej6d�e�difd�d��Z�ej6d�dU��Z�Gd�d�de��Z�Gd�dV�dVej�j��Z�Gd�d�d�e��Z�Gd�d)�d)e��Z�e�e�ej�d�Z�e�e�ej�d�Z�e�e�ej�d�Z�ej6d�fd�d�d-��Z�ej6d�d��Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�ej6d�d���Z�d�d��Z�d�Z�d�Z�e�ed���	rHd�e�Z�d�Z�e�d�Z��d�d�Zd�d�ZÐdwZĐdxZŐd�d�ZƐddW�Zǐd	d^�ZȐdyZ�d�e�Z�d�e�Z�d�e�Z�ej�Zΐd
d[�Z�G�d�d��d�ZАdz�d
d5�Zѐdd6�Z�G�dd.�d.�ZӐd�d�ZԐd�d�ZՐdd@�Z֐dd7�Zאd{�d�d�Z�daِddA�Zڐd�d�ZېddD�Zܐd�d�Zݐd�d�Zސd �d!�Zߐd"�d#�Z�da�da�d$�d%�Z�d&�d'�Z�d(�d)�Z�d*d/�Z�d+�d,�Z�e܃�
o�ejd�k�
o�ejr�d-�Z�e�j�dk	�oe�Z�ejie�d.�Z�d|�d/d0�Z�d0�d1�Z�d2�d3�Z�diZ�d4dP�Z�d5dQ�Z�d6dR�Z�ej6�d}�d8�d9��Z�d:dN�Z�ej6�d~�d;dS��Z�ej6�d<dY��Z�ej6�d=dX��Z��d>�d?�Z�ej�e�e�d@��dA�Z��dB�dC�Z��dD�dE�Z�G�dFdO�dOej�j��Z�G�dGdZ�dZe���Zd�a�dHd ��Z�dId1��Zd�a�dJ�dK��Z�dLd:��Z�dM�dN��Z�dOd!��Zf�dP��dQd>��Z	dfff�dRd?��Z
G�dSd\�d\��Z�dT�dU��Z�dV�dW��Z
ff�dX�dY��Zgf�dZd`��Zd�a�d[dF��Zej6�d\�d]���Z�d^da��ZG�d_�d`��d`��ZG�da�db��db��Zej6�dc�dd���ZdS(ztest.supportz.support must be imported from the test package�N�)�get_test_runner�
PIPE_MAX_SIZE�verbose�
max_memuse�
use_resources�failfast�Error�
TestFailed�
TestDidNotRun�ResourceDenied�
import_module�import_fresh_module�CleanImport�unload�forget�record_original_stdout�get_original_stdout�captured_stdout�captured_stdin�captured_stderr�TESTFN�SAVEDCWD�unlink�rmtree�temp_cwd�findfile�create_empty_file�can_symlink�fs_is_case_insensitive�is_resource_enabled�requires�requires_freebsd_version�requires_linux_version�requires_mac_ver�requires_hashdigest�check_syntax_error�TransientResource�time_out�socket_peer_reset�ioerror_peer_reset�transient_internet�BasicTestRunner�run_unittest�run_doctest�skip_unless_symlink�
requires_gzip�requires_bz2�
requires_lzma�
bigmemtest�bigaddrspacetest�cpython_only�
get_attribute�requires_IEEE_754�skip_unless_xattr�
requires_zlib�anticipate_failure�load_package_tests�detect_api_mismatch�check__all__�requires_android_level�requires_multiprocessing_queue�	is_jython�
is_android�check_impl_detail�
unix_shell�setswitchinterval�HOST�IPV6_ENABLED�find_unused_port�	bind_port�open_urlresource�bind_unix_socket�
temp_umask�
reap_children�TestHandler�threading_setup�threading_cleanup�reap_threads�
start_threads�check_warnings�check_no_resource_warning�EnvironmentVarGuard�run_with_locale�	swap_item�	swap_attr�Matcher�set_memlimit�SuppressCrashReport�sortdict�run_with_tz�PGO�missing_compiler_executable�fd_countc@seZdZdS)r	N)�__name__�
__module__�__qualname__�rcrc�-/usr/lib64/python3.6/test/support/__init__.pyr	|sc@seZdZdS)r
N)r`rarbrcrcrcrdr
sc@seZdZdS)rN)r`rarbrcrcrcrdr�sc@seZdZdS)rN)r`rarbrcrcrcrdr�sTccs8|r.tj��tjddt�dVWdQRXndVdS)N�ignorez.+ (module|package))�warnings�catch_warnings�filterwarnings�DeprecationWarning)rercrcrd�_ignore_deprecated_imports�s
rjF)�required_oncCsft|��Ty
tj|�Stk
rV}z&tjjt|��r8�tj	t
|���WYdd}~XnXWdQRXdS)N)rj�	importlibr
�ImportError�sys�platform�
startswith�tuple�unittest�SkipTest�str)�name�
deprecatedrk�msgrcrcrdr
�s	

cCs^|tjkrt|�tj|=x>ttj�D]0}||ks@|j|d�r&tj|||<tj|=q&WdS)N�.)rn�modules�
__import__�listrp)ru�orig_modules�modnamercrcrd�_save_and_remove_module�s
r~cCs>d}ytj|||<Wntk
r.d}YnXdtj|<|S)NTF)rnry�KeyError)rur|Zsavedrcrcrd�_save_and_block_module�s

r�cCs|r
tjSdd�S)NcSs|S)Nrc)�frcrcrd�<lambda>�sz$anticipate_failure.<locals>.<lambda>)rrZexpectedFailure)Z	conditionrcrcrdr:�scCsF|dkrd}tjjtjjtjjt���}|j|||d�}|j|�|S)Nztest*)Z	start_dirZ
top_level_dir�pattern)�os�path�dirname�__file__ZdiscoverZaddTests)Zpkg_dir�loaderZstandard_testsr�Ztop_dirZ
package_testsrcrcrdr;�s
cCs�t|���i}g}t||�zfyHx|D]}t||�q&Wx |D]}t||�s>|j|�q>Wtj|�}Wntk
r~d}YnXWdx|j�D]\}	}
|
tj	|	<q�Wx|D]}tj	|=q�WX|SQRXdS)N)
rjr~r��appendrlr
rm�itemsrnry)ruZfreshZblockedrvr|Znames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_name�moduleZname_to_removercrcrdr�s$





cCs>yt||�}Wn&tk
r4tjd||f��YnX|SdS)Nzobject %r has no attribute %r)�getattr�AttributeErrorrrrs)�objruZ	attributercrcrdr6s
cCs|adS)N)�_original_stdout)�stdoutrcrcrdr0scCs
tptjS)N)r�rnr�rcrcrcrdr4scCs&ytj|=Wntk
r YnXdS)N)rnryr)rurcrcrdr7scGsny||�Stk
rh}zDtdkrHtd|jj|f�td|j|f�tj|tj�||�Sd}~XnXdS)N�z%s: %szre-run %s%r)	�OSErrorr�print�	__class__r`r��chmod�stat�S_IRWXU)r��func�args�errrcrcrd�
_force_run=sr��wincCs�||�|r|}ntjj|�\}}|p(d}d}x<|dkrjtj|�}|rJ|n||ksVdStj|�|d9}q0Wtjd|tdd�dS)Nrxg����MbP?g�?r�z)tests may fail, delete still pending for �)�
stacklevel)	r�r��split�listdir�time�sleeprf�warn�RuntimeWarning)r��pathname�waitallr�ru�timeout�Lrcrcrd�_waitforHs



r�cCsttj|�dS)N)r�r�r)�filenamercrcrd�_unlinkisr�cCsttj|�dS)N)r�r��rmdir)r�rcrcrd�_rmdirlsr�cs,�fdd��t�|dd�tdd�|�dS)Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}Wn<tk
rn}z td||ft	j
d�d}WYdd}~XnXtj|�r�t
�|dd�t|tj|�qt|tj|�qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)�filerT)r�)r�r�r�r��join�lstat�st_moder�r�rn�
__stderr__r��S_ISDIRr�r�r)r�ru�fullname�mode�exc)�
_rmtree_innerrcrdr�ps

z_rmtree.<locals>._rmtree_innerT)r�cSst|tj|�S)N)r�r�r�)�prcrcrdr�sz_rmtree.<locals>.<lambda>)r�)r�rc)r�rd�_rmtreeosr�c
Cs^yddl}Wntk
r Yn:X|jt|�d�}|jjj||t|��}|rZ|d|�S|S)Nrr�)�ctypesrmZcreate_unicode_buffer�len�windll�kernel32ZGetLongPathNameW)r�r��bufferZlengthrcrcrd�	_longpath�s
r�csFytj|�dStk
r"YnX�fdd���|�tj|�dS)Nc
s�x~t|tj|�D]l}tjj||�}ytj|�j}Wntk
rJd}YnXtj	|�rn�|�t|tj
|�qt|tj|�qWdS)Nr)r�r�r�r�r�r�r�r�r�r�r�r)r�rur�r�)r�rcrdr��s

z_rmtree.<locals>._rmtree_inner)�shutilrr�r�r�)r�rc)r�rdr��s
cCs|S)Nrc)r�rcrcrdr��scCs*yt|�Wnttfk
r$YnXdS)N)r��FileNotFoundError�NotADirectoryError)r�rcrcrdr�scCs&yt|�Wntk
r YnXdS)N)r�r�)r�rcrcrdr��sr�cCs&yt|�Wntk
r YnXdS)N)r�r�)r�rcrcrdr�scCsBtjj|�}tjjtjj|��}tjj||d�}tj||�|S)N�c)	rl�util�cache_from_sourcer�r�r��abspathr��rename)�sourceZpyc_fileZup_oneZ
legacy_pycrcrcrd�make_legacy_pyc�s
r�cCs\t|�xNtjD]D}tjj||d�}t|d�x dD]}ttjj||d��q8WqWdS)Nz.pyr��rr�)�optimization)r�rr�)	rrnr�r�r�rrlr�r�)r}r�r��optrcrcrdr�s
cs�ttd�rtjSd}tjjd�r�ddl�ddl�d}d}G�fdd�d�j�}�j	j
}|j�}|sj�j��|�}�j
j�}|j||�j|��j|��j|��}|s��j��t|j|@�s�d}n�tjdk�rVdd	lm}	m�m}
m}dd
lm}|	j|d��}
|
j�dk�rd}nFG�fd
d�d|�}|�}|
|�}|
j|�dk�sR|
j|�dk�rVd}|�s�y.ddlm}|�}|j�|j �|j!�Wn\t"k
�r�}z>t#|�}t$|�dk�r�|dd�d}dj%t&|�j'|�}WYdd}~XnX|t_(|t_tjS)N�resultr�rrcs.eZdZd�jjfd�jjfd�jjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserved�dwFlagsN)r`rarb�wintypesZBOOL�DWORD�_fields_rc)r�rcrd�USEROBJECTFLAGS�s

r�z,gui not available (WSF_VISIBLE flag not set)�darwin)�cdll�c_int�pointer�	Structure)�find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercseZdZd�fd�fgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)r`rarbr�rc)r�rcrd�ProcessSerialNumbersr�z#cannot run without OS X gui process)�Tk�2z [...]zTk unavailable due to {}: {}))�hasattr�_is_gui_availabler�rnrorpr�Zctypes.wintypesr�r�Zuser32ZGetProcessWindowStationZWinErrorr�r�ZGetUserObjectInformationWZbyrefZsizeof�boolr�r�r�r�Zctypes.utilr�ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr�Zwithdraw�updateZdestroy�	Exceptionrtr��format�typer`�reason)r�Z	UOI_FLAGSZWSF_VISIBLEr�Zdll�hZuofZneeded�resr�r�r�r�Zapp_servicesr�ZpsnZpsn_pr��root�eZ
err_stringrc)r�r�rdr��sh

r�cCstdkp|tkS)N)r)�resourcercrcrdr $scCs>t|�s |dkrd|}t|��|dkr:t�r:ttj��dS)Nz"Use of the %r resource not enabled�gui)r rr�r�)r�rwrcrcrdr!,scs��fdd�}|S)Ncs$tj�����fdd��}�|_|S)Nc
s�tj��krztj�jdd�d}yttt|jd���}Wntk
rLYn.X|�krzdjtt	���}t
jd�||f���||�S)N�-rrrxz(%s version %s or higher required, not %s)ro�system�releaser�rq�map�int�
ValueErrorr�rtrrrs)r��kw�version_txt�version�min_version_txt)r��min_version�sysnamercrd�wrapper=sz:_requires_unix_version.<locals>.decorator.<locals>.wrapper)�	functools�wrapsr�)r�r�)r�r�)r�rd�	decorator<sz)_requires_unix_version.<locals>.decoratorrc)r�r�r�rc)r�r�rd�_requires_unix_version5sr�cGs
td|�S)NZFreeBSD)r�)r�rcrcrdr"PscGs
td|�S)NZLinux)r�)r�rcrcrdr#Yscs�fdd�}|S)Ncs"tj����fdd��}�|_|S)Ncsxtjdkrntj�d}yttt|jd���}Wntk
rBYn,X|�krndjtt	���}t
jd||f���||�S)Nr�rrxz&Mac OS X %s or higher required, not %s)rnroZmac_verrqr�r�r�r�r�rtrrrs)r�r�r�r�r�)r�r�rcrdr�js
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r�r�r�)r�r�)r�)r�rdr�isz#requires_mac_ver.<locals>.decoratorrc)r�r�rc)r�rdr$bscs��fdd�}|S)Ncstj�����fdd��}|S)NcsXy&�rtdk	rtj��n
tj��Wn&tk
rLtjd��d���YnX�||�S)Nz
hash digest 'z' is not available.)�_hashlib�new�hashlibr�rrrs)r��kwargs)�
digestnamer��opensslrcrdr��sz7requires_hashdigest.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)r�r)r�rdr��sz&requires_hashdigest.<locals>.decoratorrc)r�rr�rc)r�rrdr%}s
z	127.0.0.1z::1cCs"tj||�}t|�}|j�~|S)N)�socketrH�close)�familyZsocktypeZtempsock�portrcrcrdrG�s
8cCs�|jtjkr�|jtjkr�ttd�r>|jtjtj�dkr>t	d��ttd�r~y |jtjtj
�dkrft	d��Wntk
r|YnXttd�r�|jtjtj
d�|j|df�|j�d}|S)N�SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!�SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!�SO_EXCLUSIVEADDRUSEr)rr�AF_INETr��SOCK_STREAMr�Z
getsockoptZ
SOL_SOCKETrr
rr�Z
setsockoptr�bindZgetsockname)�sock�hostrrcrcrdrH�s


cCs:y|j|�Wn&tk
r4|j�tjd��YnXdS)Nzcannot bind AF_UNIX sockets)r
�PermissionErrorrrrrs)rZaddrrcrcrdrJs
cCsZtjrVd}z<y"tjtjtj�}|jtdf�dStk
rBYnXWd|rT|j�XdS)NrTF)rZhas_ipv6ZAF_INET6r	r
�HOSTv6r�r)rrcrcrd�_is_ipv6_enableds

rcstj���fdd��}|S)NcsNy�||�Wn:tk
rH}zdt|�kr6tjd���WYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)�IOErrorrtrrrs)r�r�r�)r�rcrd�decs
z&system_must_validate_cert.<locals>.dec)r�r�)r�rrc)r�rd�system_must_validate_certs	rr�i�ZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzma�java�ANDROID_API_LEVEL�win32z/system/bin/shz/bin/shz$testz@testz	{}_{}_tmp�æ�İ�Ł�φ�К�א�،�ت�ก� �€u-àòɘŁğr�ZNFD�ntr�u-共Ł♡ͣ�ztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective��s-��surrogateescape��w����������r�ccs�d}|dkr&tj�}d}tjj|�}nBytj|�d}Wn.tk
rf|sN�tjd|t	dd�YnX|rttj
�}z
|VWd|r�|tj
�kr�t|�XdS)NFTz+tests may fail, unable to create temp dir: �)r�)�tempfile�mkdtempr�r��realpath�mkdirr�rfr�r��getpidr)r��quietZdir_created�pidrcrcrd�temp_dir�s&


r1ccsftj�}ytj|�Wn.tk
rD|s,�tjd|tdd�YnXztj�VWdtj|�XdS)Nz)tests may fail, unable to change CWD to: r))r�)r��getcwd�chdirr�rfr�r�)r�r/Z	saved_dirrcrcrd�
change_cwd	s

r4�tempcwdccs:t||d��$}t||d��}|VWdQRXWdQRXdS)N)r�r/)r/)r1r4)rur/Z	temp_pathZcwd_dirrcrcrdr$s�umaskccs&tj|�}z
dVWdtj|�XdS)N)r�r6)r6ZoldmaskrcrcrdrK8s

�datacCsbtjj|�r|S|dk	r&tjj||�}tgtj}x*|D]"}tjj||�}tjj|�r8|Sq8W|S)N)r�r��isabsr��
TEST_HOME_DIRrn�exists)r�Zsubdirr�Zdn�fnrcrcrdrIs
cCs(tj|tjtjBtjB�}tj|�dS)N)r��open�O_WRONLY�O_CREAT�O_TRUNCr)r��fdrcrcrdr[scCs,t|j��}dd�|D�}dj|�}d|S)NcSsg|]}d|�qS)z%r: %rrc)�.0Zpairrcrcrd�
<listcomp>cszsortdict.<locals>.<listcomp>z, z{%s})�sortedr�r�)�dictr�Z	reprpairsZ
withcommasrcrcrdr[`s
cCs*ttd�}z|j�S|j�tt�XdS)N�wb)r<r�filenorr)r�rcrcrd�make_bad_fdgs

rG)�lineno�offsetcCsp|jt��}t|dd�WdQRX|j}|j|j�|dk	rJ|j|j|�|j|j�|dk	rl|j|j|�dS)Nz
<test string>�exec)�assertRaises�SyntaxError�compileZ	exceptionZassertIsNotNonerH�assertEqualrI)�testcaseZ	statementrHrI�cmr�rcrcrdr&sscsVddl}ddl}�jdd��|jj|�djd�d}tjjt	|�}���fdd�}tjj
|�r|||�}|dk	rt|St|�td�t
r�td	|t�d
�|jj�}tr�|jjd�|j|d
d�}tr�|jjd�dkr�tj|d�}zBt|d��.}	|j�}
x|
�r|	j|
�|j�}
�q�WWdQRXWd|j�X||�}|dk	�rF|Std|��dS)Nr�checkr��/rcs>t|f����}�dkr|S�|�r2|jd�|S|j�dS)Nr)r<�seekr)r;r�)r�rQr�rcrd�check_valid_file�s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...)r��Accept-Encoding�gzip�)r�zContent-Encoding)ZfileobjrEzinvalid resource %r���)rUrV)Zurllib.requestZurllib.parse�pop�parseZurlparser�r�r�r��
TEST_DATA_DIRr:rr!rr�rZrequestZbuild_openerrVZ
addheadersr�r<Zheaders�getZGzipFile�read�writerr
)Zurlr�r��urllibr�r;rTr��opener�out�src)r�rQr�rdrI~s<	



c@s0eZdZdd�Zdd�Zedd��Zdd�Zd	S)
�WarningsRecordercCs||_d|_dS)Nr)�	_warnings�_last)�selfZ
warnings_listrcrcrd�__init__�szWarningsRecorder.__init__cCsDt|j�|jkr t|jd|�S|tjjkr0dStd||f��dS)Nrz%r has no attribute %rrX)r�rdrer�rf�WarningMessage�_WARNING_DETAILSr�)rf�attrrcrcrd�__getattr__�s
zWarningsRecorder.__getattr__cCs|j|jd�S)N)rdre)rfrcrcrdrf�szWarningsRecorder.warningscCst|j�|_dS)N)r�rdre)rfrcrcrd�reset�szWarningsRecorder.resetN)r`rarbrgrk�propertyrfrlrcrcrcrdrc�srcc
cs
tjd�}|jjd�}|r"|j�tjdd�� }tjdjd�t	|�VWdQRXt
|�}g}xz|D]r\}}d}	xH|dd�D]8}|j}
tj
|t|
�tj�r�t|
j|�r�d}	|j|�q�W|	rf|rf|j||jf�qfW|r�td|d	��|�rtd
|d	��dS)Nr�Z__warningregistry__T)�recordrf�alwaysFzunhandled warning %srz)filter (%r, %s) did not catch any warning)rn�	_getframe�	f_globalsr\�clearrfrgry�simplefilterrcr{�message�re�matchrt�I�
issubclassr��remover�r`�AssertionError)�filtersr/�frame�registry�wZreraiseZmissingrw�cat�seenZwarningrcrcrd�_filterwarnings�s0
r�cOs.|jd�}|s$dtff}|dkr$d}t||�S)Nr/r�T)r\�Warningr�)r{r�r/rcrcrdrR�s

r�ccsHtjdd��&}tjd||d�dV|r.t�WdQRX|j|g�dS)NT)rnro)rt�category)rfrgrh�
gc_collectrN)rOrtr�Zforce_gc�warnsrcrcrd�check_no_warningssr�ccsBtjdd�� }tjdtd�dVt�WdQRX|j|g�dS)NT)rnro)r�)rfrgrh�ResourceWarningr�rN)rOr�rcrcrdrSs
c@s$eZdZdd�Zdd�Zdd�ZdS)rcGsNtjj�|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rnry�copy�original_modulesr`)rfZmodule_namesZmodule_namer�rcrcrdrg?s




zCleanImport.__init__cCs|S)Nrc)rfrcrcrd�	__enter__LszCleanImport.__enter__cGstjj|j�dS)N)rnryr�r�)rf�
ignore_excrcrcrd�__exit__OszCleanImport.__exit__N)r`rarbrgr�r�rcrcrcrdr3s
c@sdeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dd�Z
dd�Zdd�Zdd�Z
dS)rTcCstj|_i|_dS)N)r��environ�_environ�_changed)rfrcrcrdrgXszEnvironmentVarGuard.__init__cCs
|j|S)N)r�)rf�envvarrcrcrd�__getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj|�|j|<||j|<dS)N)r�r�r\)rfr��valuercrcrd�__setitem___s
zEnvironmentVarGuard.__setitem__cCs2||jkr|jj|�|j|<||jkr.|j|=dS)N)r�r�r\)rfr�rcrcrd�__delitem__es

zEnvironmentVarGuard.__delitem__cCs
|jj�S)N)r��keys)rfrcrcrdr�lszEnvironmentVarGuard.keyscCs
t|j�S)N)�iterr�)rfrcrcrd�__iter__oszEnvironmentVarGuard.__iter__cCs
t|j�S)N)r�r�)rfrcrcrd�__len__rszEnvironmentVarGuard.__len__cCs|||<dS)Nrc)rfr�r�rcrcrd�setuszEnvironmentVarGuard.setcCs
||=dS)Nrc)rfr�rcrcrd�unsetxszEnvironmentVarGuard.unsetcCs|S)Nrc)rfrcrcrdr�{szEnvironmentVarGuard.__enter__cGsJx<|jj�D].\}}|dkr0||jkr:|j|=q||j|<qW|jt_dS)N)r�r�r�r�r�)rfr��k�vrcrcrdr�~s

zEnvironmentVarGuard.__exit__N)r`rarbrgr�r�r�r�r�r�r�r�r�r�rcrcrcrdrTSsc@s$eZdZdd�Zdd�Zdd�ZdS)�
DirsOnSysPathcGs(tjdd�|_tj|_tjj|�dS)N)rnr��original_value�original_object�extend)rf�pathsrcrcrdrg�szDirsOnSysPath.__init__cCs|S)Nrc)rfrcrcrdr��szDirsOnSysPath.__enter__cGs|jt_|jtjdd�<dS)N)r�rnr�r�)rfr�rcrcrdr��szDirsOnSysPath.__exit__N)r`rarbrgr�r�rcrcrcrdr��sr�c@s&eZdZdd�Zdd�Zddd�ZdS)	r'cKs||_||_dS)N)r��attrs)rfr�r�rcrcrdrg�szTransientResource.__init__cCs|S)Nrc)rfrcrcrdr��szTransientResource.__enter__NcCsT|dk	rPt|j|�rPx:|jj�D]$\}}t||�s4Pt||�|kr Pq Wtd��dS)Nz%an optional resource is not available)rxr�r�r�r�r�r)rfZtype_r��	tracebackrjZ
attr_valuercrcrdr��s
zTransientResource.__exit__)NNN)r`rarbrgr�r�rcrcrcrdr'�s)�errnog>@)r��errnosc	#spd d!d"d#d$d%g}d'd)d+d-d.g}td|��|�g��sRdd�|D��dd�|D�����fdd�}tj�}z�y|dk	r�tj|�dVWn�tjk
�r�}z&tr�tjj	�j
dd��|�WYdd}~Xn�tk
�rZ}zpx^|j
}t|�dk�rt
|dt��r|d}n*t|�dk�r8t
|dt��r8|d}nP�q�W||��WYdd}~XnXWdtj|�XdS)/N�ECONNREFUSED�o�
ECONNRESET�h�EHOSTUNREACH�q�ENETUNREACH�e�	ETIMEDOUT�n�
EADDRNOTAVAIL�c�	EAI_AGAINr)�EAI_FAILr��
EAI_NONAMEr��
EAI_NODATA��
WSANO_DATA�*zResource %r is not availablecSsg|]\}}tt||��qSrc)r�r�)rAru�numrcrcrdrB�sz&transient_internet.<locals>.<listcomp>cSsg|]\}}tt||��qSrc)r�r)rArur�rcrcrdrB�scs�t|dd�}t|tj�s�t|tj�r,|�ks�t|tjj�rTd|jkoNdkns�t|tjj	�r�d|j
ks�d|j
ks�d|j
ks�|�kr�ts�tj
j�jdd��|�dS)	Nr�i�iW�ConnectionRefusedError�TimeoutError�EOFErrorr�
)r��
isinstancerr�Zgaierrorr_�errorZ	HTTPError�codeZURLErrorr�rrn�stderrr^r�)r��n)�captured_errnos�denied�
gai_errnosrcrd�filter_error�s


z(transient_internet.<locals>.filter_errorrr�r)r�r�)r�r�)r�r�)r�r�)r�r�)r�r����)r�r����)r�r����)r�r����)r�r�)r�r�)rrZgetdefaulttimeoutZsetdefaulttimeout�nntplibZNNTPTemporaryErrorrrnr�r^r�r�r�r�)	Z
resource_namer�r�Zdefault_errnosZdefault_gai_errnosr�Zold_timeoutr��arc)r�r�r�rdr+�sP



c
csFddl}tt|�}tt||j��ztt|�VWdtt||�XdS)Nr)�ior�rn�setattr�StringIO)Zstream_namer�Zorig_stdoutrcrcrd�captured_outputs
r�cCstd�S)Nr�)r�rcrcrcrdrscCstd�S)Nr�)r�rcrcrcrdr%scCstd�S)N�stdin)r�rcrcrcrdr.s
cCs*tj�trtjd�tj�tj�dS)Ng�������?)�gcZcollectr@r�r�rcrcrcrdr�;s


r�c
cs.tj�}tj�z
dVWd|r(tj�XdS)N)r��	isenabled�disable�enable)Zhave_gcrcrcrd�
disable_gcKs
r�cCs:tjd�pd}d}x|j�D]}|jd�r|}qW|dkS)N�	PY_CFLAGSr�z-O�-O0�-Og)r�r�r�)�	sysconfig�get_config_varr�rp)ZcflagsZ	final_optr�rcrcrd�python_is_optimizedVs
r�ZnPZ0n�gettotalrefcountZ2PZ0Pr�cCstjt|t�S)N)�struct�calcsize�_header�_align)�fmtrcrcrd�calcobjsizegsr�cCstjt|t�S)N)r�r��_vheaderr�)r�rcrcrd�calcvobjsizejsr���	cCspddl}tj|�}t|�tkr(|jt@sBt|�tkrLt|�jt@rL||j7}dt|�||f}|j|||�dS)Nrz&wrong size for %s: got %d, expected %d)	�	_testcapirn�	getsizeofr��	__flags__�_TPFLAGS_HEAPTYPE�_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrN)�test�o�sizer�r�rwrcrcrd�check_sizeofqs

r�cs��fdd�}|S)Ncs$���fdd�}�j|_�j|_|S)Ncs�y ddl}t|��}|j|�}Wn(tk
r6�YnBd}}Yn0Xx,�D]$}y|j||�PWqPYqPXqPWz
�||�S|r�|r�|j||�XdS)Nr)�localer��	setlocaler�)r��kwdsr�r�Zorig_locale�loc)�catstrr��localesrcrd�inner�s$



z1run_with_locale.<locals>.decorator.<locals>.inner)r`�__doc__)r�r�)r�r�)r�rdr��sz"run_with_locale.<locals>.decoratorrc)r�r�r�rc)r�r�rdrU�scs�fdd�}|S)Ncs"��fdd�}�j|_�j|_|S)Ncs�y
tj}Wntk
r(tjd��YnXdtjkr@tjd}nd}�tjd<|�z
�||�S|dkrrtjd=n
|tjd<tj�XdS)Nztzset requiredZTZ)r��tzsetr�rrrsr�r�)r�r�r�Zorig_tz)r��tzrcrdr��s





z-run_with_tz.<locals>.decorator.<locals>.inner)r`r�)r�r�)r�)r�rdr��szrun_with_tz.<locals>.decoratorrc)r�r�rc)r�rdr\�scCs�dttdtd�}tjd|tjtjB�}|dkr>td|f��tt|j	d��||j	d�j
��}|a|tkrrt}|t
dkr�td|f��|adS)Ni)r��m�g�tz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr)z$Memory limit %r too low to be useful)�_1M�_1Grurv�
IGNORECASE�VERBOSEr�r��float�group�lower�real_max_memuse�MAX_Py_ssize_t�_2Gr)�limitZsizesr�ZmemlimitrcrcrdrY�s$c@s$eZdZdd�Zdd�Zdd�ZdS)�_MemoryWatchdogcCsdjtj�d�|_d|_dS)Nz/proc/{pid}/statm)r0F)r�r�r.�procfile�started)rfrcrcrdrg�sz_MemoryWatchdog.__init__cCs�yt|jd�}Wn<tk
rL}z tjdj|�t�tjj	�dSd}~XnXt
d�}tjtj
|g|tjd�|_|j�d|_dS)N�rz!/proc not available for stats: {}zmemory_watchdog.py)r�r�T)r<r
r�rfr�r�r�rnr��flushr�
subprocess�Popen�
executableZDEVNULL�mem_watchdogrr)rfr�r�Zwatchdog_scriptrcrcrd�start�s
z_MemoryWatchdog.startcCs|jr|jj�|jj�dS)N)rrZ	terminate�wait)rfrcrcrd�stop�s
z_MemoryWatchdog.stopN)r`rarbrgrrrcrcrcrdr	�sr	cs���fdd�}|S)Ncs ���fdd����_��_�S)Nc
s��j}�j}tsd}n|}ts$�rFt||krFtjd||d��tr|tr|t�tdj||dd��t�}|j	�nd}z
�||�S|r�|j
�XdS)	Niz'not enough memory: %.1fG minimum neededir)z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@)r��memuserrrrsrr�r�r	rr)rfr�r�maxsizeZwatchdog)�dry_runr�r�rcrdr�s*


z.bigmemtest.<locals>.decorator.<locals>.wrapper)r�r)r�)rrr�)r�r�rdr�szbigmemtest.<locals>.decoratorrc)r�rrr�rc)rrr�rdr3s
!cs�fdd�}|S)NcsDttkr8td
kr$tdkr$tjd��q@tjdtd��n�|�SdS)
Nr��?r�z-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir)ll����li@)rrrrrs)rf)r�rcrdr�3sz!bigaddrspacetest.<locals>.wrapperrc)r�r�rc)r�rdr41sc@seZdZdd�ZdS)r,cCstj�}||�|S)N)rrZ
TestResult)rfr�r�rcrcrd�runDszBasicTestRunner.runN)r`rarbrrcrcrcrdr,CscCs|S)Nrc)r�rcrcrd�_idIsrcCs<|dkrt�rtjtj�St|�r(tStjdj|��SdS)Nr�zresource {0!r} is not enabled)r�rr�skipr�r rr�)r�rcrcrd�requires_resourceLs
rcCs&trt|krtjd|tf�StSdS)Nz%s at Android API level %d)rA�_ANDROID_API_LEVELrrrr)�levelr�rcrcrdr>TscCstdd�|�S)NT)�cpython)�impl_detail)r�rcrcrdr5[scKsVtf|�rtS|dkrLt|�\}}|r,d}nd}t|j��}|jdj|��}tj|�S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rBr�
_parse_guardsrCr�r�r�rrr)rw�guardsZ
guardnames�defaultrcrcrdr!as
r!cCsTtdkr:ddl}y|j�daWntk
r8daYnXd}trF|Stj|�|�S)NrTFz6requires a functioning shared semaphore implementation)�_have_mp_queue�multiprocessingZQueuermrrr)r�r&rwrcrcrdr?os
cCs*|sddidfSt|j��d}||fS)Nr TFr)r{�values)r#Zis_truercrcrdr"~sr"cKs t|�\}}|jtj�j�|�S)N)r"r\roZpython_implementationr)r#r$rcrcrdrB�scs,ttd�s�Stj���fdd��}|SdS)N�gettracecs.tj�}ztjd��||�Stj|�XdS)N)rnr(�settrace)r�r�Zoriginal_trace)r�rcrdr��s


zno_tracing.<locals>.wrapper)r�rnr�r�)r�r�rc)r�rd�
no_tracing�s
r*cCstt|��S)N)r*r5)r�rcrcrd�
refcount_test�sr+cCsRg}xB|jD]8}t|tj�r2t||�|j|�q||�r|j|�qW||_dS)N)Z_testsr�rr�	TestSuite�
_filter_suiter�)�suiteZpredZnewtestsr�rcrcrdr-�s
r-cCs�ttjttdk	d�}|j|�}tdk	r4tj|j��|js>t	�|j
�s�t|j�dkrl|j
rl|jdd}n6t|j
�dkr�|jr�|j
dd}nd}ts�|d7}t|��dS)N)�	verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rrnr�r�junit_xml_listrr�Zget_xml_elementZtestsRunrZ
wasSuccessfulr��errorsZfailuresr
)r.Zrunnerr�r�rcrcrd�
_run_suite�s"
r2cCstdkrdSt|j��SdS)NT)�_match_test_func�id)r�rcrcrd�
match_test�sr5cCsd|kotjd|�S)Nrxz[?*\[\]])ru�search)r�rcrcrd�_is_full_match_test�sr7csr|tkrdS|sd}f}nHttt|��r4t|�j}n.djttj|��}t	j
|�j��fdd�}|}t|�a|a
dS)N�|cs$�|�rdStt�|jd���SdS)NTrx)�anyr�r�)Ztest_id)�regex_matchrcrd�match_test_regex�sz)set_match_tests.<locals>.match_test_regex)�_match_test_patterns�allr�r7r��__contains__r��fnmatch�	translaterurMrvrqr3)Zpatternsr�Zregexr;rc)r:rd�set_match_tests�srAcGs�tjtjf}tj�}xh|D]`}t|t�rT|tjkrJ|jtjtj|��qzt	d��qt||�rj|j|�q|jtj
|��qWt|t�t
|�dS)Nz)str arguments must be keys in sys.modules)rrr,ZTestCaser�rtrnryZaddTestZ
findTestCasesr�Z	makeSuiter-r5r2)�classesZvalid_typesr.�clsrcrcrdr-s





cCsdS)Nrcrcrcrcrd�_check_docstrings(srD�WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d�\}}|rBtd||f��trXtd|j|f�||fS)Nr)r�optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)�doctestrZtestmodr
r�r`)r�r/rFrGr�r�rcrcrdr.9scCstjj�fS)N)rnryr�rcrcrcrd�
modules_setupTsrHcCs:dd�tjj�D�}tjj�tjj|�tjj|�dS)NcSs"g|]\}}|jd�r||f�qS)z
encodings.)rp)rAr�r�rcrcrdrB[sz#modules_cleanup.<locals>.<listcomp>)rnryr�rrr�)Z
oldmodulesZ	encodingsrcrcrd�modules_cleanupWs
rIcCs"trtj�tjj�fSdffSdS)Nr)�_thread�_count�	threading�	_danglingr�rcrcrcrdrNzscGsJtsdSd}x8t|�D],}tj�tjf}||kr2Ptjd�t�qWdS)N�dg{�G�z�?)rJ�rangerKrLrMr�r�r�)Zoriginal_valuesZ
_MAX_COUNT�countr'rcrcrdrO�s
cs"ts�Stj���fdd��}|S)Ncst�}z�|�St|�XdS)N)rNrO)r��key)r�rcrdr��szreap_threads.<locals>.decorator)rJr�r�)r�r�rc)r�rdrP�s�N@ccs�tj�}z
dVWdtj�}||}xjtj�}||kr8Ptj�|kr|tj�|}d||�d|d�d|�d|�d�	}t|��tjd�t�q&WXdS)Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z
, old count: �)g{�G�z�?)rJrKr�Z	monotonicrzr�r�)r�Z	old_countZ
start_timeZdeadlinerPZdtrwrcrcrd�wait_threads_exit�s
$
rTc
CsZttd�rVd}xFy2tj|tj�\}}|dkr.Ptd|tjd�WqPYqXqWdS)N�waitpidrrz2Warning -- reap_children() reaped child process %s)r�rX)r�r�rU�WNOHANGr�rnr�)Zany_processr0ZstatusrcrcrdrL�s
ccs*t|�}g}zZy$x|D]}|j�|j|�qWWn*trVtdt|�t|�f��YnXdVWdz�|rt|�tj�}}xltdd�D]^}|d7}x$|D]}|jt	|tj�d��q�Wdd�|D�}|s�Ptr�tdt|�|f�q�WWdd	d�|D�}|�r"t
jtj
�td
t|���XXdS)Nz/Can't start %d threads, only %d threads startedrr�<g{�G�z�?cSsg|]}|j�r|�qSrc)�isAlive)rAr�rcrcrdrB�sz!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSsg|]}|j�r|�qSrc)rX)rAr�rcrcrdrB�szUnable to join %d threads)r{rr�rr�r�r�rOr��max�faulthandlerZdump_tracebackrnr�rz)ZthreadsZunlockrr�ZendtimeZ	starttimer�rcrcrdrQ�s>


c
csnt||�r<t||�}t|||�z
|VWdt|||�Xn.t|||�z
dVWdt||�rht||�XdS)N)r�r�r��delattr)r�rj�new_val�real_valrcrcrdrW�s




ccsX||kr0||}|||<z
|VWd|||<Xn$|||<z
dVWd||krR||=XdS)Nrc)r��itemr\r]rcrcrdrV	s

cCstjdd|�j�}|S)Ns\[\d+ refs, \d+ blocks\]\r?\n?�)ru�sub�strip)r�rcrcrd�strip_python_stderr8	srbZ	getcountsz-types are immortal if COUNT_ALLOCS is definedcCstj�S)N)rZ_args_from_interpreter_flagsrcrcrcrd�args_from_interpreter_flagsE	srccCstj�S)N)rZ"_optim_args_from_interpreter_flagsrcrcrcrd�!optim_args_from_interpreter_flagsJ	srdc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rMcCstjjj|d�||_dS)Nr)�logging�handlers�BufferingHandlerrg�matcher)rfrhrcrcrdrgT	szTestHandler.__init__cCsdS)NFrc)rfrcrcrd�shouldFlush]	szTestHandler.shouldFlushcCs|j|�|jj|j�dS)N)r�r�r��__dict__)rfrnrcrcrd�emit`	s
zTestHandler.emitcKs.d}x$|jD]}|jj|f|�rd}PqW|S)NFT)r�rh�matches)rfr�r��drcrcrdrld	szTestHandler.matchesN)r`rarbrgrirkrlrcrcrcrdrMS	s	c@s eZdZdZdd�Zdd�ZdS)	rXrwrtcKs<d}x2|D]*}||}|j|�}|j|||�s
d}Pq
W|S)NTF)r\�match_value)rfrmr�r�r�r��dvrcrcrdrls	s

zMatcher.matchescCsHt|�t|�krd}n.t|�tk	s,||jkr6||k}n|j|�dk}|S)NFr)r�rt�_partial_matches�find)rfr�ror�r�rcrcrdrn�	s
zMatcher.match_valueN)rwrt)r`rarbrprlrnrcrcrcrdrXo	sc
CsZtdk	rtStd}ytjt|�d}Wntttfk
rFd}YnXtj|�|a|S)NrTF)�_can_symlinkrr��symlinkr��NotImplementedErrorr�ry)Zsymlink_path�canrcrcrdr�	s

cCs t�}d}|r|Stj|�|�S)Nz*Requires functional symlink implementation)rrrr)r��okrwrcrcrdr/�	scCs�tdk	rtSttd�sd}n�tj�}tj|d�\}}z�ttd���}y`tj|dd�tj|dd�tj|j	�dd�t
j�}tj
d	|�}|dkp�t|jd
��dk}Wntk
r�d}YnXWdQRXWdtt�t|�t|�X|a|S)N�setxattrF)�dirrEs	user.testr_strusted.foos42z
2.6.(\d{1,2})r�')�
_can_xattrr�r�r*r+Zmkstempr<rrwrFror�rurvr�rr�rr�)ruZtmp_dirZtmp_fpZtmp_name�fpZkernel_versionr�rcrcrd�	can_xattr�	s,

r|cCs t�}d}|r|Stj|�|�S)Nz(no non-broken extended attribute support)r|rrr)r�rvrwrcrcrdr8�	scCs$tpt}d}|r|Stj|�|�S)Nz#Not run for (non-extended) PGO task)r]�PGO_EXTENDEDrrr)r�rvrwrcrcrd�skip_if_pgo_task�	s
r~cCs^tj|d��H}|j}|j�}||kr,|j�}ytjj||�Stk
rNdSXWdQRXdS)N)rxF)	r*ZNamedTemporaryFileru�upperrr�r��samefiler�)Z	directory�base�	base_pathZ	case_pathrcrcrdr�	s)recCs>tt|��tt|��}|r(|t|�8}tdd�|D��}|S)Ncss(|] }|jd�s|jd�r|VqdS)�_�__N)rp�endswith)rAr�rcrcrd�	<genexpr>�	sz&detect_api_mismatch.<locals>.<genexpr>)r�rx)Zref_apiZ	other_apireZ
missing_itemsrcrcrdr<�	s
cCs�|dkr|jf}nt|t�r"|f}t|�}xbt|�D]V}|jd�s4||krLq4t||�}t|dd�|ks�t|d�r4t|tj	�r4|j
|�q4W|j|j|�dS)Nr�ra)
r`r�rtr�rxrpr�r��types�
ModuleType�addZassertCountEqual�__all__)Z	test_caser�Zname_of_moduleZextraZ	blacklistZexpectedrur�rcrcrdr=�	s)


c@s$eZdZdZdZdd�Zdd�ZdS)rZNc
Csrtjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
rlYnLXi|_
x�|j|j|jgD].}|j
||j�}|j||j�}||f|j
|<q�Wn�tdk	�r
y*tjtj�|_tjtjd|jdf�Wnttfk
�rYnXtjdk�rndddd	g}tj|tjtjd
�}|�|j�d}	WdQRX|	j�dk�rntdd
dd�|S)Nr�rr�rr�z/usr/bin/defaultsr]zcom.apple.CrashReporterZ
DialogType)r�r�s	developerz:this test triggers the Crash Reporter, that is intentionalr�T)�endr
) rnrorpr�r�r��_k32�SetErrorMode�	old_value�msvcrt�CrtSetReportModer�rm�	old_modes�CRT_WARN�	CRT_ERROR�
CRT_ASSERTZCRTDBG_MODE_FILE�CrtSetReportFileZCRTDBG_FILE_STDERRr�Z	getrlimit�RLIMIT_CORE�	setrlimitr�r�rr�PIPEZcommunicaterar�)
rfr�ZSEM_NOGPFAULTERRORBOXr��report_type�old_mode�old_file�cmd�procr�rcrcrdr�2
sN




zSuppressCrashReport.__enter__cGs�|jdkrdStjjd�rl|jj|j�|jr�ddl}xj|jj�D]$\}\}}|j	||�|j
||�qBWn6tdk	r�ytjtj
|j�Wnttfk
r�YnXdS)Nr�r)r�rnrorpr�r�r�r�r�r�r�r�r�r�r�r�)rfr�r�r�r�r�rcrcrdr�s
s
zSuppressCrashReport.__exit__)r`rarbr�r�r�r�rcrcrcrdrZ)
sAcsrt���d�y�j��Wn$ttfk
r@t��d��YnXd�����fdd�}|j|�t��|�dS)NFTcs �rt����n
t���dS)N)r�r[rc)�
attr_is_local�	attr_name�object_to_patchr�rcrd�cleanup�
szpatch.<locals>.cleanup)r�rjr�rZ
addCleanupr�)Z
test_instancer�r�Z	new_valuer�rc)r�r�r�r�rd�patch�
s


r�cCsFyddl}Wntk
r YnX|j�r4tjd��ddl}|j|�S)NrzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)�tracemallocrmZ
is_tracingrrrsr��run_in_subinterp)r�r�r�rcrcrdr��
s
r�csHG��fdd�d|�}d�|||���|jtt��t�|j��dS)NcseZdZ��fdd�ZdS)z%check_free_after_iterating.<locals>.Acs*d�yt��Wntk
r$YnXdS)NT)�next�
StopIteration)rf)�done�itrcrd�__del__�
s
z-check_free_after_iterating.<locals>.A.__del__N)r`rarbr�rc)r�r�rcrd�A�
sr�F)rKr�r�r�Z
assertTrue)r�r�rCr�r�rc)r�r�rd�check_free_after_iterating�
s	r�cCs|ddlm}m}m}|j�}|j|�xP|jD]F}|r@||kr@q.t||�}|rPn
|dkrZq.|j|d�dkr.|dSq.WdS)Nr)�	ccompilerr��spawn)	Z	distutilsr�r�r�Znew_compilerZcustomize_compilerZexecutablesr�Zfind_executable)Z	cmd_namesr�r�r�Zcompilerrur�rcrcrdr^�
s	

cCs@d}tr6||kr6tdkr.tjddg�j�dkatr6|}tj|�S)Ng�h㈵��>Zgetpropzro.kernel.qemu�1)rA�_is_android_emulatorrZcheck_outputrarnrD)ZintervalZminimum_intervalrcrcrdrD�
sc
cs>tjj�}tj�}ztj�dVWd|r8tj|dd�XdS)NT)r�Zall_threads)rnr�rFrZ�
is_enabledr�r�)r@r�rcrcrd�disable_faulthandler�
s

r�c	/Cs�tjjd
�r8ytjd�}t|�dStk
r6YnXd}ttd�rjytjd�}Wnt	k
rhYnXd}tjdkr�yd	dl
}|jWntt
fk
r�Yn0Xi}x(|j|j|jfD]}|j|d	�||<q�Wzpd	}xft|�D]Z}ytj|�}Wn4t	k
�r(}z|jtjk�r�WYdd}~Xq�Xtj|�|d7}q�WWd|dk	�rzx*|j|j|jfD]}|j|||��q`WX|S)N�linux�freebsdz
/proc/self/fdr��sysconf�SC_OPEN_MAXrr)r�r�)rnrorpr�r�r�r�r�r�r�r�r�r�rmr�r�r�rO�dupr�ZEBADFr)	�namesZMAXFDr�r�r�rPr@Zfd2r�rcrcrdr_	sP





c@s$eZdZdd�Zdd�Zdd�ZdS)�SaveSignalscCsjddl}||_ttd|j��|_x>dD]6}yt||�}Wntk
rNw&YnX|jj|�q&Wi|_dS)Nrr�SIGKILL�SIGSTOP)r�r�)	�signalr{rO�NSIG�signalsr�r�ryrf)rfr�Zsigname�signumrcrcrdrgMs
zSaveSignals.__init__cCs4x.|jD]$}|jj|�}|dkr"q||j|<qWdS)N)r�r��	getsignalrf)rfr��handlerrcrcrd�saveZs
zSaveSignals.savecCs*x$|jj�D]\}}|jj||�qWdS)N)rfr�r�)rfr�r�rcrcrd�restorefszSaveSignals.restoreN)r`rarbrgr�r�rcrcrcrdr�Ds	
r�c@s$eZdZdd�Zdd�Zdd�ZdS)�FakePathcCs
||_dS)N)r�)rfr�rcrcrdrgnszFakePath.__init__cCsd|j�d�S)Nz
<FakePath �>)r�)rfrcrcrd�__repr__qszFakePath.__repr__cCs6t|jt�s$t|jt�r,t|jt�r,|j�n|jSdS)N)r�r��
BaseExceptionr�rx)rfrcrcrd�
__fspath__ts
zFakePath.__fspath__N)r`rarbrgr�r�rcrcrcrdr�ksr�ccs.tj�}ztj|�dVWdtj|�XdS)N)rn�get_int_max_str_digits�set_int_max_str_digits)Z
max_digitsZcurrentrcrcrd�adjust_int_max_str_digits|s


r�)T)F)F)N)Nii@i@i@ii)rrrrrrrrrr r!)r%r#r&r'r()NF)F)r5F)N)Fi@ii)T)N)Nr)rR)N(r`rm�collections.abc�collections�
contextlibZdatetimer�rZr?r�r�r�rl�importlib.utilr�Zlogging.handlersrer�r�rorur�rr�r�rrnr�r*r�r�rrZurllib.errorr_rfZ
testresultrrJrLZmultiprocessing.processr&�zlibrV�bz2Zlzmar�r�r�r�r	r
rrsr�contextmanagerrjr
r~r�r:r;rr6rrrrr0rr�rrrr�rpr�r�r�r�r�rr�rr�rr�r r!r�r"r#r$r%rErrr	rGrHrJrrFrrZ
SOCK_MAX_SIZEZ
skipUnlessr�
__getformat__r7r9r0r1r2r@r�rrArCrurr�r.ZFS_NONASCII�	character�fsdecode�fsencode�UnicodeErrorZTESTFN_UNICODEZunicodedata�	normalize�getfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversion�encode�UnicodeEncodeErrorr��decode�UnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr2rr]r}r1r4rr�rKr�r�r�r�ZTEST_SUPPORT_DIRr9r�r[rrr[rGr&rI�objectrcr�rRr�r�rSr�abc�MutableMappingrTr�r'r�r�r(r�r)r*r+r�rrrr�r�r�r�r�r�r�r�r�r�r�rUr\r�r�rZ_4GrrrYr	r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSr�ZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZr�r�r�r^r�rDr�r_r�r�r�rcrcrcrd�<module>s�











2	
!

J			>%	


%2' 5M		


$
#
0







(




"
#
	"
:_";'PK�R�Z)$����6support/__pycache__/script_helper.cpython-36.opt-2.pycnu�[���3

�\dh�)�@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddl
mZmZdadd�ZGdd�dejdd#��Zdd�Zd
d�Zdd�Zdd�Zejejd�dd�Zdd�Zd$dd�Zd%dd�Zd&dd�Zd'd!d"�ZdS)(�N)�source_from_cache)�make_legacy_pyc�strip_python_stderrcCsVtdkrRdtjkrdadSytjtjdddg�Wntjk
rLdaYnXdatS)NZ
PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)�$__cached_interp_requires_environment�os�environ�
subprocessZ
check_call�sys�
executableZCalledProcessError�rr�2/usr/lib64/python3.6/test/support/script_helper.py� interpreter_requires_environments


r
c@seZdZdd�ZdS)�_PythonRunResultcCs�d}|j|j}}t|�|kr0d||d�}t|�|krNd||d�}|jdd�j�}|jdd�j�}td|j|||f��dS)	N�P�ds(... truncated stdout ...)s(... truncated stderr ...)�ascii�replacezRProcess return code is %d
command line: %r

stdout:
---
%s
---

stderr:
---
%s
---i@)�out�err�len�decode�rstrip�AssertionError�rc)�self�cmd_line�maxlenrrrrr�fail>sz_PythonRunResult.failN)�__name__�
__module__�__qualname__rrrrrr;srrrrc
Ost�}d|kr|jd�}n|o$|}tjddg}|rB|jd�n|rX|rX|jd�|jdd�r�i}tjdkr�tjd|d<n
tjj�}d	|kr�d
|d	<|j	|�|j
|�tj|tj
tj
tj
|d�}|�*z|j�\}}Wd|j�tj�XWdQRX|j}	t|�}t|	||�|fS)NZ
__isolatedz-XZfaulthandlerz-Iz-EZ
__cleanenvZwin32Z
SYSTEMROOT�TERM�)�stdin�stdout�stderr�env)r
�popr	r
�append�platformrr�copy�update�extendr�Popen�PIPEZcommunicate�kill�_cleanup�
returncoderr)
�args�env_varsZenv_required�isolatedrr&�procrrrrrr�run_python_until_end[s:





r6cOs4t||�\}}|jr|s&|jr0|r0|j|�|S)N)r6rr)Zexpected_successr2r3�resrrrr�_assert_python�s
r8cOstd|�|�S)NT)T)r8)r2r3rrr�assert_python_ok�sr9cOstd|�|�S)NF)F)r8)r2r3rrr�assert_python_failure�sr:)r$r%cOsXtjg}t�s|jd�|j|�|jdttj��}d|d<t	j
|ft	j||d�|��S)Nz-Er&Zvt100r!)r#r$r%)r	r
r
r(r,�
setdefault�dictrrrr-r.)r$r%r2�kwrr&rrr�spawn_python�s

r>cCs2|jj�|jj�}|jj�|j�tj�|S)N)r#�closer$�read�waitrr0)�p�datarrr�kill_python�s


rDFcCsP|}|s|tjd7}tjj||�}t|ddd�}|j|�|j�tj�|S)N�py�wzutf-8)�encoding)	r�extsep�path�join�open�writer?�	importlib�invalidate_caches)Z
script_dir�script_basename�sourceZomit_suffixZscript_filename�script_nameZscript_filerrr�make_script�s
rRc	Cs�|tjd}tjj||�}tj|d�}|dkr~|jtj�}t|�dkrr|ddkrrt	t
|��}tjj|�}|}ntjj|�}|j||�|j
�|tjj||�fS)N�ziprF��__pycache__���)rrHrIrJ�zipfile�ZipFile�split�seprrr�basenamerLr?)	�zip_dir�zip_basenamerQZname_in_zip�zip_filename�zip_name�zip_file�partsZ
legacy_pycrrr�make_zip_script�srbr"cCstj|�t|d|�dS)N�__init__)r�mkdirrR)Zpkg_dirZinit_sourcerrr�make_pkg�s
re�cs0g}t|dd�}|j|�tjj|�}	t|||�}
|j|
�|rjtj|dd�}tj|
dd�}
|j||
f��fdd�td|d�D�}tjj	|d
tjj|
��}|tj
d}
tjj	||
�}tj|d	�}x&|D]}tjj	||	�}|j
||�q�W|j
|
|�|j�x|D]}tj|��q
W|tjj	||�fS)Nrcr"T)�doraisecsg|]}tjj�g|��qSr)rrZrJ)�.0�i)�pkg_namerr�
<listcomp>�sz make_zip_pkg.<locals>.<listcomp>rfrSrF���)rRr(rrIr[�
py_compile�compiler,�rangerJrHrWrXrLr?�unlink)r\r]rjrOrPZdepthZcompiledrpZ	init_nameZ
init_basenamerQZ	pkg_namesZscript_name_in_zipr^r_r`�nameZinit_name_in_zipr)rjr�make_zip_pkg�s.



rr)rrr)F)N)r")rfF) �collectionsrMr	rZos.pathZtempfilerrm�
contextlibZshutilrW�importlib.utilrZtest.supportrrrr
�
namedtuplerr6r8r9r:r.ZSTDOUTr>rDrRrbrerrrrrr�<module>s4$3




PK�R�Z� P

3support/__pycache__/testresult.cpython-36.opt-2.pycnu�[���3


 \
�@s2ddlZddlZddlZddlZddlZddlZddljjZ	ddl
m
Z
Gdd�dej�ZGdd�d�Z
ddd	�Zdd
d�Zedk�r.Gd
d�dej�Zej�Zejeje��ej�Zeedd�ejD���Zeej�Zeje�Ze dej!��e ddd�x(e	j"ej#��D]Z$e e$j%�dd��qWe �dS)�N)�datetimecs�eZdZdddZdddZ�fdd�Zedd��Z�fd	d
�Zd$dd
�Z	dd�Z
edd��Z�fdd�Z�fdd�Z
�fdd�Z�fdd�Z�fdd�Z�fdd�Zdd�Zd d!�Zd"d#�Z�ZS)%�RegressionTestResult�=�F�
�-cs\t�j||dd�d|_tjd�|_|jjdtj�j	d��d|_
d|_g|_t
|�|_dS)Nr)�stream�descriptions�	verbosityTZ	testsuite�start� )�super�__init__�buffer�ETZElement�_RegressionTestResult__suite�setrZutcnowZ	isoformat�_RegressionTestResult__e�!_RegressionTestResult__start_timeZ_RegressionTestResult__results�bool�_RegressionTestResult__verbose)�selfrr	r
)�	__class__��//usr/lib64/python3.6/test/support/testresult.pyrszRegressionTestResult.__init__cCsLy
|j}Wntk
r"t|�SXy|�Stk
rBt|�SXt|�S)N)�id�AttributeError�str�	TypeError�repr)�cls�testZtest_idrrrZ__getIds


zRegressionTestResult.__getIdcsVt�j|�tj|jd�|_}tj�|_|j	rR|j
j|j|��d��|j
j
�dS)NZtestcasez ... )r
�	startTestr�
SubElementrr�time�perf_counterrrr�write�getDescription�flush)rr!�e)rrrr"+s
zRegressionTestResult.startTestFcKsP|j}d|_|dkrdS|jd|jd|j|���|jd|jdd��|jd|jdd��|jrz|jdtj�|jd��|r�|jdk	r�|jj�j	�}|t
j|d�_|j
dk	r�|j
j�j	�}|t
j|d	�_x�|j�D]t\}}|s�|r�q�t
j||�}	t|d
��r>xD|j�D],\}
}|
�r,|	j|
t|��n
t|�|	_�qWq�t|�|	_q�WdS)N�nameZstatus�run�resultZ	completedr$z0.6fz
system-outz
system-err�items)rr�pop�_RegressionTestResult__getIdrr$r%Z_stdout_buffer�getvalue�rstriprr#�textZ_stderr_bufferr-�hasattrr)rr!Zcapture�argsr)�stdout�stderr�k�vZe2Zk2Zv2rrr�_add_result3s4

z RegressionTestResult._add_resultcCs|jr|jj|�d��dS)Nr)rrr&)r�cZwordrrrZ__writeSszRegressionTestResult.__writecCslt|t�r0|jdkr|j}q8|j�d|j��}nt|�}tj||d�}tj|||�}|dj|�dj|�d�S)N�builtins�.�)�type�messager=)�
isinstancer>�
__module__�__name__r�	traceback�format_exception�join)r Zerr_typeZ	err_valueZerr_tb�typename�msg�tbrrrZ__makeErrorDictWs

z$RegressionTestResult.__makeErrorDictcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�error�E�ERROR)r9�$_RegressionTestResult__makeErrorDictr
�addError�_RegressionTestResult__write)rr!�err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�output�xzexpected failure)r9rLr
�addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|�d�t�j||�|jdd�dS)NT)Zfailure�F�FAIL)r9rLr
�
addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||d�t�j||�|jdd|���dS)N)Zskipped�Szskipped )r9r
�addSkiprN)rr!�reason)rrrrWyszRegressionTestResult.addSkipcs&|j|�t�j|�|jdd�dS)Nr<�ok)r9r
�
addSuccessrN)rr!)rrrrZ~s
zRegressionTestResult.addSuccesscs*|j|dd�t�j|�|jdd�dS)NZUNEXPECTED_SUCCESS)Zoutcome�uzunexpected success)r9r
�addUnexpectedSuccessrN)rr!)rrrr\�sz)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd�|jd|j�|jd|j�dS)NrrKrT)rrr&�printErrorList�errors�failures)rrrr�printErrors�sz RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j�|jj|�d|j|��d��|jj|j�|jjd|�qWdS)Nz: rz%s
)rr&�
separator1r'�
separator2)rZflavorr^r!rOrrrr]�s
z#RegressionTestResult.printErrorListcCsH|j}|jdt|j��|jdtt|j���|jdtt|j���|S)NZtestsr^r_)rrrZtestsRun�lenr^r_)rr)rrr�get_xml_element�s
z$RegressionTestResult.get_xml_element)F)rBrA�__qualname__rarbr�classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd�
__classcell__rr)rrrs"
 rc@seZdZddd�Zdd�ZdS)�QuietRegressionTestRunnerFcCst|dd�|_||j_dS)Nr)rr,r)rrrrrrr�sz"QuietRegressionTestRunner.__init__cCs||j�|jS)N)r,)rr!rrrr+�s
zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrh�s
rhFcCs&|rtjtjt||d�Stjt|d�S)N)Zresultclassrr
)r)�	functools�partial�unittestZTextTestRunnerrrh)r
rrrr�get_test_runner_class�srlcCst||�|�S)N)rl)rr
Zcapture_outputrrr�get_test_runner�srm�__main__c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�	TestTestscCsdS)Nr)rrrr�	test_pass�szTestTests.test_passcCstjd�dS)Ng�?)r$Zsleep)rrrr�test_pass_slow�szTestTests.test_pass_slowcCs*tdtjd�tdtjd�|jd�dS)Nr5)�filer6zfailure message)�print�sysr5r6Zfail)rrrr�	test_fail�szTestTests.test_failcCs(tdtjd�tdtjd�td��dS)Nr5)rrr6z
error message)rsrtr5r6�RuntimeError)rrrr�
test_error�szTestTests.test_errorN)rBrArerprqrurwrrrrro�sroccs|]}|dkVqdS)z-vNr)�.0�arrr�	<genexpr>�srzzOutput:zXML: r=)�end)F)F)&ri�iortr$rCrkZxml.etree.ElementTreeZetreeZElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ	TestSuiteZsuiteZaddTestZ	makeSuite�StringIOr�sum�argvZ
runner_clsr5Zrunnerr+r,rsr0Ztostringlistrd�s�decoderrrr�<module>s2
	




PK�R�Z�N}���6support/__pycache__/script_helper.cpython-36.opt-1.pycnu�[���3

�\dh�)�@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddl
mZmZdadd�ZGdd�dejdd#��Zdd�Zd
d�Zdd�Zdd�Zejejd�dd�Zdd�Zd$dd�Zd%dd�Zd&dd�Zd'd!d"�ZdS)(�N)�source_from_cache)�make_legacy_pyc�strip_python_stderrcCsVtdkrRdtjkrdadSytjtjdddg�Wntjk
rLdaYnXdatS)a 
    Returns True if our sys.executable interpreter requires environment
    variables in order to be able to run at all.

    This is designed to be used with @unittest.skipIf() to annotate tests
    that need to use an assert_python*() function to launch an isolated
    mode (-I) or no environment mode (-E) sub-interpreter process.

    A normal build & test does not run into this situation but it can happen
    when trying to run the standard library test suite from an interpreter that
    doesn't have an obvious home with Python's current home finding logic.

    Setting PYTHONHOME is one way to get most of the testsuite to run in that
    situation.  PYTHONPATH or PYTHONUSERSITE are other common environment
    variables that might impact whether or not the interpreter can start.
    NZ
PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)�$__cached_interp_requires_environment�os�environ�
subprocessZ
check_call�sys�
executableZCalledProcessError�rr�2/usr/lib64/python3.6/test/support/script_helper.py� interpreter_requires_environments


r
c@seZdZdZdd�ZdS)�_PythonRunResultz2Helper for reporting Python subprocess run resultscCs�d	}|j|j}}t|�|kr0d||d�}t|�|krNd||d�}|jdd�j�}|jdd�j�}td|j|||f��dS)
z4Provide helpful details about failed subcommand runs�P�ds(... truncated stdout ...)Ns(... truncated stderr ...)�ascii�replacezRProcess return code is %d
command line: %r

stdout:
---
%s
---

stderr:
---
%s
---i@)�out�err�len�decode�rstrip�AssertionError�rc)�self�cmd_line�maxlenrrrrr�fail>sz_PythonRunResult.failN)�__name__�
__module__�__qualname__�__doc__rrrrrr;srrrrc
Ost�}d|kr|jd�}n|o$|}tjddg}|rB|jd�n|rX|rX|jd�|jdd�r�i}tjdkr�tjd|d<n
tjj�}d	|kr�d
|d	<|j	|�|j
|�tj|tj
tj
tj
|d�}|�*z|j�\}}Wd|j�tj�XWdQRX|j}	t|�}t|	||�|fS)NZ
__isolatedz-XZfaulthandlerz-Iz-EZ
__cleanenvZwin32Z
SYSTEMROOT�TERM�)�stdin�stdout�stderr�env)r
�popr	r
�append�platformrr�copy�update�extendr�Popen�PIPEZcommunicate�kill�_cleanup�
returncoderr)
�args�env_varsZenv_required�isolatedrr'�procrrrrrr�run_python_until_end[s:





r7cOs4t||�\}}|jr|s&|jr0|r0|j|�|S)N)r7rr)Zexpected_successr3r4�resrrrr�_assert_python�s
r9cOstd|�|�S)a|
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` succeeds (rc == 0) and return a (return code, stdout,
    stderr) tuple.

    If the __cleanenv keyword is set, env_vars is used as a fresh environment.

    Python is started in isolated mode (command line option -I),
    except if the __isolated keyword is set to False.
    T)T)r9)r3r4rrr�assert_python_ok�sr:cOstd|�|�S)z�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` fails (rc != 0) and return a (return code, stdout,
    stderr) tuple.

    See assert_python_ok() for more options.
    F)F)r9)r3r4rrr�assert_python_failure�sr;)r%r&cOsXtjg}t�s|jd�|j|�|jdttj��}d|d<t	j
|ft	j||d�|��S)z�Run a Python subprocess with the given arguments.

    kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
    object.
    z-Er'Zvt100r")r$r%r&)r	r
r
r)r-�
setdefault�dictrrrr.r/)r%r&r3�kwrr'rrr�spawn_python�s

r?cCs2|jj�|jj�}|jj�|j�tj�|S)z?Run the given Popen process until completion and return stdout.)r$�closer%�read�waitrr1)�p�datarrr�kill_python�s


rEFcCsP|}|s|tjd7}tjj||�}t|ddd�}|j|�|j�tj�|S)N�py�wzutf-8)�encoding)	r�extsep�path�join�open�writer@�	importlib�invalidate_caches)Z
script_dir�script_basename�sourceZomit_suffixZscript_filename�script_nameZscript_filerrr�make_script�s
rSc	Cs�|tjd}tjj||�}tj|d�}|dkr~|jtj�}t|�dkrr|ddkrrt	t
|��}tjj|�}|}ntjj|�}|j||�|j
�|tjj||�fS)N�ziprG��__pycache__���)rrIrJrK�zipfile�ZipFile�split�seprrr�basenamerMr@)	�zip_dir�zip_basenamerRZname_in_zip�zip_filename�zip_name�zip_file�partsZ
legacy_pycrrr�make_zip_script�srcr#cCstj|�t|d|�dS)N�__init__)r�mkdirrS)Zpkg_dirZinit_sourcerrr�make_pkg�s
rf�cs0g}t|dd�}|j|�tjj|�}	t|||�}
|j|
�|rjtj|dd�}tj|
dd�}
|j||
f��fdd�td|d�D�}tjj	|d
tjj|
��}|tj
d}
tjj	||
�}tj|d	�}x&|D]}tjj	||	�}|j
||�q�W|j
|
|�|j�x|D]}tj|��q
W|tjj	||�fS)Nrdr#T)�doraisecsg|]}tjj�g|��qSr)rr[rK)�.0�i)�pkg_namerr�
<listcomp>�sz make_zip_pkg.<locals>.<listcomp>rgrTrG���)rSr)rrJr\�
py_compile�compiler-�rangerKrIrXrYrMr@�unlink)r]r^rkrPrQZdepthZcompiledrqZ	init_nameZ
init_basenamerRZ	pkg_namesZscript_name_in_zipr_r`ra�nameZinit_name_in_zipr)rkr�make_zip_pkg�s.



rs)rrr)F)N)r#)rgF) �collectionsrNr	rZos.pathZtempfilerrn�
contextlibZshutilrX�importlib.utilrZtest.supportrrrr
�
namedtuplerr7r9r:r;r/ZSTDOUTr?rErSrcrfrsrrrr�<module>s4$3




PK�R�Z�N}���0support/__pycache__/script_helper.cpython-36.pycnu�[���3

�\dh�)�@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZddl
mZmZdadd�ZGdd�dejdd#��Zdd�Zd
d�Zdd�Zdd�Zejejd�dd�Zdd�Zd$dd�Zd%dd�Zd&dd�Zd'd!d"�ZdS)(�N)�source_from_cache)�make_legacy_pyc�strip_python_stderrcCsVtdkrRdtjkrdadSytjtjdddg�Wntjk
rLdaYnXdatS)a 
    Returns True if our sys.executable interpreter requires environment
    variables in order to be able to run at all.

    This is designed to be used with @unittest.skipIf() to annotate tests
    that need to use an assert_python*() function to launch an isolated
    mode (-I) or no environment mode (-E) sub-interpreter process.

    A normal build & test does not run into this situation but it can happen
    when trying to run the standard library test suite from an interpreter that
    doesn't have an obvious home with Python's current home finding logic.

    Setting PYTHONHOME is one way to get most of the testsuite to run in that
    situation.  PYTHONPATH or PYTHONUSERSITE are other common environment
    variables that might impact whether or not the interpreter can start.
    NZ
PYTHONHOMETz-Ez-czimport sys; sys.exit(0)F)�$__cached_interp_requires_environment�os�environ�
subprocessZ
check_call�sys�
executableZCalledProcessError�rr�2/usr/lib64/python3.6/test/support/script_helper.py� interpreter_requires_environments


r
c@seZdZdZdd�ZdS)�_PythonRunResultz2Helper for reporting Python subprocess run resultscCs�d	}|j|j}}t|�|kr0d||d�}t|�|krNd||d�}|jdd�j�}|jdd�j�}td|j|||f��dS)
z4Provide helpful details about failed subcommand runs�P�ds(... truncated stdout ...)Ns(... truncated stderr ...)�ascii�replacezRProcess return code is %d
command line: %r

stdout:
---
%s
---

stderr:
---
%s
---i@)�out�err�len�decode�rstrip�AssertionError�rc)�self�cmd_line�maxlenrrrrr�fail>sz_PythonRunResult.failN)�__name__�
__module__�__qualname__�__doc__rrrrrr;srrrrc
Ost�}d|kr|jd�}n|o$|}tjddg}|rB|jd�n|rX|rX|jd�|jdd�r�i}tjdkr�tjd|d<n
tjj�}d	|kr�d
|d	<|j	|�|j
|�tj|tj
tj
tj
|d�}|�*z|j�\}}Wd|j�tj�XWdQRX|j}	t|�}t|	||�|fS)NZ
__isolatedz-XZfaulthandlerz-Iz-EZ
__cleanenvZwin32Z
SYSTEMROOT�TERM�)�stdin�stdout�stderr�env)r
�popr	r
�append�platformrr�copy�update�extendr�Popen�PIPEZcommunicate�kill�_cleanup�
returncoderr)
�args�env_varsZenv_required�isolatedrr'�procrrrrrr�run_python_until_end[s:





r7cOs4t||�\}}|jr|s&|jr0|r0|j|�|S)N)r7rr)Zexpected_successr3r4�resrrrr�_assert_python�s
r9cOstd|�|�S)a|
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` succeeds (rc == 0) and return a (return code, stdout,
    stderr) tuple.

    If the __cleanenv keyword is set, env_vars is used as a fresh environment.

    Python is started in isolated mode (command line option -I),
    except if the __isolated keyword is set to False.
    T)T)r9)r3r4rrr�assert_python_ok�sr:cOstd|�|�S)z�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` fails (rc != 0) and return a (return code, stdout,
    stderr) tuple.

    See assert_python_ok() for more options.
    F)F)r9)r3r4rrr�assert_python_failure�sr;)r%r&cOsXtjg}t�s|jd�|j|�|jdttj��}d|d<t	j
|ft	j||d�|��S)z�Run a Python subprocess with the given arguments.

    kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
    object.
    z-Er'Zvt100r")r$r%r&)r	r
r
r)r-�
setdefault�dictrrrr.r/)r%r&r3�kwrr'rrr�spawn_python�s

r?cCs2|jj�|jj�}|jj�|j�tj�|S)z?Run the given Popen process until completion and return stdout.)r$�closer%�read�waitrr1)�p�datarrr�kill_python�s


rEFcCsP|}|s|tjd7}tjj||�}t|ddd�}|j|�|j�tj�|S)N�py�wzutf-8)�encoding)	r�extsep�path�join�open�writer@�	importlib�invalidate_caches)Z
script_dir�script_basename�sourceZomit_suffixZscript_filename�script_nameZscript_filerrr�make_script�s
rSc	Cs�|tjd}tjj||�}tj|d�}|dkr~|jtj�}t|�dkrr|ddkrrt	t
|��}tjj|�}|}ntjj|�}|j||�|j
�|tjj||�fS)N�ziprG��__pycache__���)rrIrJrK�zipfile�ZipFile�split�seprrr�basenamerMr@)	�zip_dir�zip_basenamerRZname_in_zip�zip_filename�zip_name�zip_file�partsZ
legacy_pycrrr�make_zip_script�srcr#cCstj|�t|d|�dS)N�__init__)r�mkdirrS)Zpkg_dirZinit_sourcerrr�make_pkg�s
rf�cs0g}t|dd�}|j|�tjj|�}	t|||�}
|j|
�|rjtj|dd�}tj|
dd�}
|j||
f��fdd�td|d�D�}tjj	|d
tjj|
��}|tj
d}
tjj	||
�}tj|d	�}x&|D]}tjj	||	�}|j
||�q�W|j
|
|�|j�x|D]}tj|��q
W|tjj	||�fS)Nrdr#T)�doraisecsg|]}tjj�g|��qSr)rr[rK)�.0�i)�pkg_namerr�
<listcomp>�sz make_zip_pkg.<locals>.<listcomp>rgrTrG���)rSr)rrJr\�
py_compile�compiler-�rangerKrIrXrYrMr@�unlink)r]r^rkrPrQZdepthZcompiledrqZ	init_nameZ
init_basenamerRZ	pkg_namesZscript_name_in_zipr_r`ra�nameZinit_name_in_zipr)rkr�make_zip_pkg�s.



rs)rrr)F)N)r#)rgF) �collectionsrNr	rZos.pathZtempfilerrn�
contextlibZshutilrX�importlib.utilrZtest.supportrrrr
�
namedtuplerr7r9r:r;r/ZSTDOUTr?rErSrcrfrsrrrr�<module>s4$3




PK�R�Z�r�&XX-support/__pycache__/testresult.cpython-36.pycnu�[���3


 \
�@s6dZddlZddlZddlZddlZddlZddlZddljj	Z
ddlmZGdd�dej�Z
Gdd�d�Zdd	d
�Zddd�Zed
k�r2Gdd�dej�Zej�Zejeje��ej�Zeedd�ejD���Zeej�Zeje�Z e!dej"��e!ddd�x(e
j#e j$��D]Z%e!e%j&�dd��qWe!�dS)z=Test runner and result class for the regression test suite.

�N)�datetimecs�eZdZdddZdddZ�fdd�Zedd��Z�fd	d
�Zd$dd
�Z	dd�Z
edd��Z�fdd�Z�fdd�Z
�fdd�Z�fdd�Z�fdd�Z�fdd�Zdd�Zd d!�Zd"d#�Z�ZS)%�RegressionTestResult�=�F�
�-cs\t�j||dd�d|_tjd�|_|jjdtj�j	d��d|_
d|_g|_t
|�|_dS)Nr)�stream�descriptions�	verbosityTZ	testsuite�start� )�super�__init__�buffer�ETZElement�_RegressionTestResult__suite�setrZutcnowZ	isoformat�_RegressionTestResult__e�!_RegressionTestResult__start_timeZ_RegressionTestResult__results�bool�_RegressionTestResult__verbose)�selfrr	r
)�	__class__��//usr/lib64/python3.6/test/support/testresult.pyrszRegressionTestResult.__init__cCsLy
|j}Wntk
r"t|�SXy|�Stk
rBt|�SXt|�S)N)�id�AttributeError�str�	TypeError�repr)�cls�testZtest_idrrrZ__getIds


zRegressionTestResult.__getIdcsVt�j|�tj|jd�|_}tj�|_|j	rR|j
j|j|��d��|j
j
�dS)NZtestcasez ... )r
�	startTestr�
SubElementrr�time�perf_counterrrr�write�getDescription�flush)rr!�e)rrrr"+s
zRegressionTestResult.startTestFcKsP|j}d|_|dkrdS|jd|jd|j|���|jd|jdd��|jd|jdd��|jrz|jdtj�|jd��|r�|jdk	r�|jj�j	�}|t
j|d�_|j
dk	r�|j
j�j	�}|t
j|d	�_x�|j�D]t\}}|s�|r�q�t
j||�}	t|d
��r>xD|j�D],\}
}|
�r,|	j|
t|��n
t|�|	_�qWq�t|�|	_q�WdS)N�nameZstatus�run�resultZ	completedr$z0.6fz
system-outz
system-err�items)rr�pop�_RegressionTestResult__getIdrr$r%Z_stdout_buffer�getvalue�rstriprr#�textZ_stderr_bufferr-�hasattrr)rr!Zcapture�argsr)�stdout�stderr�k�vZe2Zk2Zv2rrr�_add_result3s4

z RegressionTestResult._add_resultcCs|jr|jj|�d��dS)Nr)rrr&)r�cZwordrrrZ__writeSszRegressionTestResult.__writecCslt|t�r0|jdkr|j}q8|j�d|j��}nt|�}tj||d�}tj|||�}|dj|�dj|�d�S)N�builtins�.�)�type�messager=)�
isinstancer>�
__module__�__name__r�	traceback�format_exception�join)r Zerr_typeZ	err_valueZerr_tb�typename�msg�tbrrrZ__makeErrorDictWs

z$RegressionTestResult.__makeErrorDictcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�error�E�ERROR)r9�$_RegressionTestResult__makeErrorDictr
�addError�_RegressionTestResult__write)rr!�err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�output�xzexpected failure)r9rLr
�addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|�d�t�j||�|jdd�dS)NT)Zfailure�F�FAIL)r9rLr
�
addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||d�t�j||�|jdd|���dS)N)Zskipped�Szskipped )r9r
�addSkiprN)rr!�reason)rrrrWyszRegressionTestResult.addSkipcs&|j|�t�j|�|jdd�dS)Nr<�ok)r9r
�
addSuccessrN)rr!)rrrrZ~s
zRegressionTestResult.addSuccesscs*|j|dd�t�j|�|jdd�dS)NZUNEXPECTED_SUCCESS)Zoutcome�uzunexpected success)r9r
�addUnexpectedSuccessrN)rr!)rrrr\�sz)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd�|jd|j�|jd|j�dS)NrrKrT)rrr&�printErrorList�errors�failures)rrrr�printErrors�sz RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j�|jj|�d|j|��d��|jj|j�|jjd|�qWdS)Nz: rz%s
)rr&�
separator1r'�
separator2)rZflavorr^r!rOrrrr]�s
z#RegressionTestResult.printErrorListcCsH|j}|jdt|j��|jdtt|j���|jdtt|j���|S)NZtestsr^r_)rrrZtestsRun�lenr^r_)rr)rrr�get_xml_element�s
z$RegressionTestResult.get_xml_element)F)rBrA�__qualname__rarbr�classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd�
__classcell__rr)rrrs"
 rc@seZdZddd�Zdd�ZdS)�QuietRegressionTestRunnerFcCst|dd�|_||j_dS)Nr)rr,r)rrrrrrr�sz"QuietRegressionTestRunner.__init__cCs||j�|jS)N)r,)rr!rrrr+�s
zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrh�s
rhFcCs&|rtjtjt||d�Stjt|d�S)N)Zresultclassrr
)r)�	functools�partial�unittestZTextTestRunnerrrh)r
rrrr�get_test_runner_class�srlcCst||�|�S)N)rl)rr
Zcapture_outputrrr�get_test_runner�srm�__main__c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�	TestTestscCsdS)Nr)rrrr�	test_pass�szTestTests.test_passcCstjd�dS)Ng�?)r$Zsleep)rrrr�test_pass_slow�szTestTests.test_pass_slowcCs*tdtjd�tdtjd�|jd�dS)Nr5)�filer6zfailure message)�print�sysr5r6Zfail)rrrr�	test_fail�szTestTests.test_failcCs(tdtjd�tdtjd�td��dS)Nr5)rrr6z
error message)rsrtr5r6�RuntimeError)rrrr�
test_error�szTestTests.test_errorN)rBrArerprqrurwrrrrro�sroccs|]}|dkVqdS)z-vNr)�.0�arrr�	<genexpr>�srzzOutput:zXML: r=)�end)F)F)'�__doc__ri�iortr$rCrkZxml.etree.ElementTreeZetreeZElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ	TestSuiteZsuiteZaddTestZ	makeSuite�StringIOr�sum�argvZ
runner_clsr5Zrunnerr+r,rsr0Ztostringlistrd�s�decoderrrr�<module>s4
	




PK�R�Z
�o��=�=+support/__pycache__/__init__.cpython-36.pycnu�[���3

�\dh����@s^
dZedkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZ
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z"ddl#Z#ddl$m%Z%yddl&Z&ddl'Z'Wnek
�rBdZ&dZ'YnXyddl(Z)Wnek
�rjdZ)YnXyddl*Z*Wnek
�r�dZ*YnXyddl+Z+Wnek
�r�dZ+YnXyddl,Z,Wnek
�r�dZ,YnXyddl-Z-Wnek
�r
dZ-YnXyddl.Z.Wnek
�r2dZ.YnXyddl/Z/Wnek
�rZdZ/YnXddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbg\Z0Gdcd�de1�Z2Gddd
�d
e2�Z3Gded�de2�Z4Gdfd�de j5�Z6ej7�dfdhdi��Z8�dgfdk�dld�Z9dmdn�Z:dodp�Z;dqd=�Z<drd>�Z=ffdjfdsd�Z>dtd9�Z?dZ@dZAdaBdaCdZDdjZEdaFdud�ZGdvd�ZHdwd�ZIdxdy�ZJejjKdz��r.�dhd{d|�ZLd}d~�ZMdd��ZNd�d��ZOd�d��ZPnejQZMejRZNd�d��ZOd�d��ZPd�d�ZQd�d��ZRd�d�ZSd�d��ZTd�d�ZUd�d��ZVd�d#�ZW�did�d$�ZXd�d��ZYd�d%�ZZd�d&�Z[d�d'�Z\�djd�d(�Z]d�Z^d�Z_ej`ejafd�dJ�Zbe^fd�dK�Zcd�dM�Zdd�d��Zeee�Zfd�d��Zg�dmZh�dpZie jjekjld��jKd��d��Zme jje*d��Zne jje+d��Zoe jje,d��Zpe jje-d��ZqejjKd��Zrejsd��Ztetdk	�oxetdkZuejd�k�r�eu�r�d�nd�ZvndZvejwd�k�r�d�Zxnd�Zxd�jyexejz��ZxdZ{xL�dqD]BZ|yej}ej~e|��e|k�r�e�Wnek
�rYnXe|Z{P�q�Wexd�Z�ejd�k�r:ddl�Z�e�j�d�e��Z�ej��Z�dZ�ejwd�k�r�ej��jd�k�r�exd�Z�ye�j�e��Wne�k
�r�YnXe�d�e�e�f�dZ�nBejd�k�r�yd�j�e��Wn&e�k
�r�exd�j�e�dǃZ�YnXdZ�xF�drD]<Zwyewj�e��Wn&e�k
�r,ej~ex�ewZ�PYnX�q�We{�rHexd�e{Z�ndZ�ej��Z�djZ�djZ�ej7�dsd�d΄�Z�ej7�dtd�dЄ�Z�ej7�dud�d��Z�e�edӃ�r�ej7d�dN��Z�ej�j�ej�j�e���Z�ej�j�e��Z�ej�j�e�dՃZ��dvd�d�Z�d�d �Z�d�d^�Z�d�dڄZ�dddۜd�d)�Z�d�dL�Z�Gd�d߄d�e��Z��dwd�d�Z�ej7d�dU��Z�ej7d�e�djfd�d��Z�ej7d�dV��Z�Gd�d�de��Z�Gd�dW�dWej�j��Z�Gd�d�d�e��Z�Gd�d*�d*e��Z�e�e�ej�d�Z�e�e�ej�d�Z�e�e�ej�d�Z�ej7d�fd�d�d.��Z�ej7d�d��Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�ej7d�d���Z�d�d��Z�d�Z�d�Z�e�ed���	rLd�e�Z�d�Z�e��dZd�d�ZÐd�d�ZĐdxZŐdyZƐd�d�Zǐd	dX�ZȐd
d_�ZɐdzZ�d�e�Z�d�e�Z�d�e�Z�ej�Zϐdd\�Z�G�d�d
��d
�Zѐd{�dd6�ZҐdd7�Z�G�dd/�d/�ZԐd�d�ZՐd�d�Z֐ddA�Zאdd8�Zؐd|�d�d�Z�daڐddB�Zېd�d�ZܐddE�Zݐd�d�Zސd�d �Zߐd!�d"�Z�d#�d$�Z�da�da�d%�d&�Z�d'�d(�Z�d)�d*�Z�d+d0�Z�d,�d-�Z�e݃�
o�ejd�k�
o�ejs�d.�Z�e�jdk	�oe�Z�e jje�d/�Z�d}�d0d1�Z�d1�d2�Z�d3�d4�Z�djZ�d5dQ�Z�d6dR�Z�d7dS�Z�ej7�d~�d9�d:��Z�d;dO�Z�ej7�d�d<dT��Z�ej7�d=dZ��Z�ej7�d>dY��Z��d?�d@�Z�e j�e�e�dA��dB�Z��dC�dD�Z��dE�dF�Z�G�dGdP�dPej�j��Z�G�dHd[�d[e���Zd�a�dId!��Z�dJd2��Zd�a�dK�dL��Z�dMd;��Z�dN�dO��Z�dPd"��Zf�dQ��dRd?��Z	dfff�dSd@��Z
G�dTd]�d]��Z�dU�dV��Z�dW�dX��Z
ff�dY�dZ��Zgf�d[da��Zd�a�d\dG��Zej7�d]�d^���Z�d_db��ZG�d`�da��da��ZG�db�dc��dc��Zej7�dd�de���ZdS(�z7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package�N�)�get_test_runner�
PIPE_MAX_SIZE�verbose�
max_memuse�
use_resources�failfast�Error�
TestFailed�
TestDidNotRun�ResourceDenied�
import_module�import_fresh_module�CleanImport�unload�forget�record_original_stdout�get_original_stdout�captured_stdout�captured_stdin�captured_stderr�TESTFN�SAVEDCWD�unlink�rmtree�temp_cwd�findfile�create_empty_file�can_symlink�fs_is_case_insensitive�is_resource_enabled�requires�requires_freebsd_version�requires_linux_version�requires_mac_ver�requires_hashdigest�check_syntax_error�TransientResource�time_out�socket_peer_reset�ioerror_peer_reset�transient_internet�BasicTestRunner�run_unittest�run_doctest�skip_unless_symlink�
requires_gzip�requires_bz2�
requires_lzma�
bigmemtest�bigaddrspacetest�cpython_only�
get_attribute�requires_IEEE_754�skip_unless_xattr�
requires_zlib�anticipate_failure�load_package_tests�detect_api_mismatch�check__all__�requires_android_level�requires_multiprocessing_queue�	is_jython�
is_android�check_impl_detail�
unix_shell�setswitchinterval�HOST�IPV6_ENABLED�find_unused_port�	bind_port�open_urlresource�bind_unix_socket�
temp_umask�
reap_children�TestHandler�threading_setup�threading_cleanup�reap_threads�
start_threads�check_warnings�check_no_resource_warning�EnvironmentVarGuard�run_with_locale�	swap_item�	swap_attr�Matcher�set_memlimit�SuppressCrashReport�sortdict�run_with_tz�PGO�missing_compiler_executable�fd_countc@seZdZdZdS)r	z*Base class for regression test exceptions.N)�__name__�
__module__�__qualname__�__doc__�rdrd�-/usr/lib64/python3.6/test/support/__init__.pyr	|sc@seZdZdZdS)r
zTest failed.N)r`rarbrcrdrdrdrer
sc@seZdZdZdS)rzTest did not run any subtests.N)r`rarbrcrdrdrdrer�sc@seZdZdZdS)rz�Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not be enabled.  It is used to distinguish between expected
    and unexpected skips.
    N)r`rarbrcrdrdrdrer�sTccs8|r.tj��tjddt�dVWdQRXndVdS)z�Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect.
    �ignorez.+ (module|package)N)�warnings�catch_warnings�filterwarnings�DeprecationWarning)rfrdrdre�_ignore_deprecated_imports�s
rkF)�required_oncCsft|��Ty
tj|�Stk
rV}z&tjjt|��r8�tj	t
|���WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed. If a module is required on a platform but optional for
    others, set required_on to an iterable of platform prefixes which will be
    compared against sys.platform.
    N)rk�	importlibr
�ImportError�sys�platform�
startswith�tuple�unittest�SkipTest�str)�name�
deprecatedrl�msgrdrdrer
�s	

cCs^|tjkrt|�tj|=x>ttj�D]0}||ks@|j|d�r&tj|||<tj|=q&WdS)zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    �.N)ro�modules�
__import__�listrq)rv�orig_modules�modnamerdrdre�_save_and_remove_module�s
rcCs>d}ytj|||<Wntk
r.d}YnXdtj|<|S)z�Helper function to save and block a module in sys.modules

    Return True if the module was in sys.modules, False otherwise.
    TFN)rorz�KeyError)rvr}Zsavedrdrdre�_save_and_block_module�s

r�cCs|r
tjSdd�S)z�Decorator to mark a test that is known to be broken in some cases

       Any use of this decorator should have a comment identifying the
       associated tracker issue.
    cSs|S)Nrd)�frdrdre�<lambda>�sz$anticipate_failure.<locals>.<lambda>)rsZexpectedFailure)Z	conditionrdrdrer:�scCsF|dkrd}tjjtjjtjjt���}|j|||d�}|j|�|S)z�Generic load_tests implementation for simple test packages.

    Most packages can implement load_tests using this function as follows:

       def load_tests(*args):
           return load_package_tests(os.path.dirname(__file__), *args)
    Nztest*)Z	start_dirZ
top_level_dir�pattern)�os�path�dirname�__file__ZdiscoverZaddTests)Zpkg_dir�loaderZstandard_testsr�Ztop_dirZ
package_testsrdrdrer;�s
cCs�t|���i}g}t||�zfyHx|D]}t||�q&Wx |D]}t||�s>|j|�q>Wtj|�}Wntk
r~d}YnXWdx|j�D]\}	}
|
tj	|	<q�Wx|D]}tj	|=q�WX|SQRXdS)a�Import and return a module, deliberately bypassing sys.modules.

    This function imports and returns a fresh copy of the named Python module
    by removing the named module from sys.modules before doing the import.
    Note that unlike reload, the original module is not affected by
    this operation.

    *fresh* is an iterable of additional module names that are also removed
    from the sys.modules cache before doing the import.

    *blocked* is an iterable of module names that are replaced with None
    in the module cache during the import to ensure that attempts to import
    them raise ImportError.

    The named module and any modules named in the *fresh* and *blocked*
    parameters are saved before starting the import and then reinserted into
    sys.modules when the fresh import is complete.

    Module and package deprecation messages are suppressed during this import
    if *deprecated* is True.

    This function will raise ImportError if the named module cannot be
    imported.
    N)
rkrr��appendrmr
rn�itemsrorz)rvZfreshZblockedrwr}Znames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_name�moduleZname_to_removerdrdrer�s$





cCs>yt||�}Wn&tk
r4tjd||f��YnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)�getattr�AttributeErrorrsrt)�objrvZ	attributerdrdrer6s
cCs|adS)N)�_original_stdout)�stdoutrdrdrer0scCs
tptjS)N)r�ror�rdrdrdrer4scCs&ytj|=Wntk
r YnXdS)N)rorzr�)rvrdrdrer7scGsny||�Stk
rh}zDtdkrHtd|jj|f�td|j|f�tj|tj�||�Sd}~XnXdS)N�z%s: %szre-run %s%r)	�OSErrorr�print�	__class__r`r��chmod�stat�S_IRWXU)r��func�args�errrdrdre�
_force_run=sr��wincCs�||�|r|}ntjj|�\}}|p(d}d}x<|dkrjtj|�}|rJ|n||ksVdStj|�|d9}q0Wtjd|tdd�dS)Nryg����MbP?g�?r�z)tests may fail, delete still pending for �)�
stacklevel)	r�r��split�listdir�time�sleeprg�warn�RuntimeWarning)r��pathname�waitallr�rv�timeout�Lrdrdre�_waitforHs



r�cCsttj|�dS)N)r�r�r)�filenamerdrdre�_unlinkisr�cCsttj|�dS)N)r�r��rmdir)r�rdrdre�_rmdirlsr�cs,�fdd��t�|dd�tdd�|�dS)Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}Wn<tk
rn}z td||ft	j
d�d}WYdd}~XnXtj|�r�t
�|dd�t|tj|�qt|tj|�qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)�filerT)r�)r�r�r�r��join�lstat�st_moder�r�ro�
__stderr__r��S_ISDIRr�r�r)r�rv�fullname�mode�exc)�
_rmtree_innerrdrer�ps

z_rmtree.<locals>._rmtree_innerT)r�cSst|tj|�S)N)r�r�r�)�prdrdrer�sz_rmtree.<locals>.<lambda>)r�)r�rd)r�re�_rmtreeosr�c
Cs^yddl}Wntk
r Yn:X|jt|�d�}|jjj||t|��}|rZ|d|�S|S)Nrr�)�ctypesrnZcreate_unicode_buffer�len�windll�kernel32ZGetLongPathNameW)r�r��bufferZlengthrdrdre�	_longpath�s
r�csFytj|�dStk
r"YnX�fdd���|�tj|�dS)Nc
s�x~t|tj|�D]l}tjj||�}ytj|�j}Wntk
rJd}YnXtj	|�rn�|�t|tj
|�qt|tj|�qWdS)Nr)r�r�r�r�r�r�r�r�r�r�r�r)r�rvr�r�)r�rdrer��s

z_rmtree.<locals>._rmtree_inner)�shutilrr�r�r�)r�rd)r�rer��s
cCs|S)Nrd)r�rdrdrer��scCs*yt|�Wnttfk
r$YnXdS)N)r��FileNotFoundError�NotADirectoryError)r�rdrdrer�scCs&yt|�Wntk
r YnXdS)N)r�r�)r�rdrdrer��sr�cCs&yt|�Wntk
r YnXdS)N)r�r�)r�rdrdrer�scCsBtjj|�}tjjtjj|��}tjj||d�}tj||�|S)aMove a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    �c)	rm�util�cache_from_sourcer�r�r��abspathr��rename)�sourceZpyc_fileZup_oneZ
legacy_pycrdrdre�make_legacy_pyc�s
r�cCs\t|�xNtjD]D}tjj||d�}t|d�x dD]}ttjj||d��q8WqWdS)	z�'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    z.pyr��rr�)�optimizationN)r�rr�)	rror�r�r�rrmr�r�)r~r�r��optrdrdrer�s
cs�ttd�rtjSd}tjjd�r�ddl�ddl�d}d}G�fdd�d�j�}�j	j
}|j�}|sj�j��|�}�j
j�}|j||�j|��j|��j|��}|s��j��t|j|@�s�d}n�tjdk�rVdd	lm}	m�m}
m}dd
lm}|	j|d��}
|
j�dk�rd}nFG�fd
d�d|�}|�}|
|�}|
j|�dk�sR|
j|�dk�rVd}|�s�y.ddlm}|�}|j�|j �|j!�Wn\t"k
�r�}z>t#|�}t$|�dk�r�|dd�d}dj%t&|�j'|�}WYdd}~XnX|t_(|t_tjS)N�resultr�rrcs.eZdZd�jjfd�jjfd�jjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserved�dwFlagsN)r`rarb�wintypesZBOOL�DWORD�_fields_rd)r�rdre�USEROBJECTFLAGS�s

r�z,gui not available (WSF_VISIBLE flag not set)�darwin)�cdll�c_int�pointer�	Structure)�find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercseZdZd�fd�fgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)r`rarbr�rd)r�rdre�ProcessSerialNumbersr�z#cannot run without OS X gui process)�Tk�2z [...]zTk unavailable due to {}: {}))�hasattr�_is_gui_availabler�rorprqr�Zctypes.wintypesr�r�Zuser32ZGetProcessWindowStationZWinErrorr�r�ZGetUserObjectInformationWZbyrefZsizeof�boolr�r�r�r�Zctypes.utilr�ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr�Zwithdraw�updateZdestroy�	Exceptionrur��format�typer`�reason)r�Z	UOI_FLAGSZWSF_VISIBLEr�Zdll�hZuofZneeded�resr�r�r�r�Zapp_servicesr�ZpsnZpsn_pr��root�eZ
err_stringrd)r�r�rer��sh

r�cCstdkp|tkS)z�Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    N)r)�resourcerdrdrer $scCs>t|�s |dkrd|}t|��|dkr:t�r:ttj��dS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabled�gui)r rr�r�)r�rxrdrdrer!,scs��fdd�}|S)z�Decorator raising SkipTest if the OS is `sysname` and the version is less
    than `min_version`.

    For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
    the FreeBSD version is less than 7.2.
    cs$tj�����fdd��}�|_|S)Nc
s�tj��krztj�jdd�d}yttt|jd���}Wntk
rLYn.X|�krzdjtt	���}t
jd�||f���||�S)N�-rrryz(%s version %s or higher required, not %s)rp�system�releaser�rr�map�int�
ValueErrorr�rursrt)r��kw�version_txt�version�min_version_txt)r��min_version�sysnamerdre�wrapper=sz:_requires_unix_version.<locals>.decorator.<locals>.wrapper)�	functools�wrapsr�)r�r�)r�r�)r�re�	decorator<sz)_requires_unix_version.<locals>.decoratorrd)r�r�r�rd)r�r�re�_requires_unix_version5sr�cGs
td|�S)z�Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
    less than `min_version`.

    For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
    version is less than 7.2.
    ZFreeBSD)r�)r�rdrdrer"PscGs
td|�S)z�Decorator raising SkipTest if the OS is Linux and the Linux version is
    less than `min_version`.

    For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
    version is less than 2.6.32.
    ZLinux)r�)r�rdrdrer#Yscs�fdd�}|S)z�Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    cs"tj����fdd��}�|_|S)Ncsxtjdkrntj�d}yttt|jd���}Wntk
rBYn,X|�krndjtt	���}t
jd||f���||�S)Nr�rryz&Mac OS X %s or higher required, not %s)rorpZmac_verrrr�r�r�r�r�rursrt)r�r�r�r�r�)r�r�rdrer�js
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r�r�r�)r�r�)r�)r�rer�isz#requires_mac_ver.<locals>.decoratorrd)r�r�rd)r�rer$bscs��fdd�}|S)a�Decorator raising SkipTest if a hashing algorithm is not available

    The hashing algorithm could be missing or blocked by a strict crypto
    policy.

    If 'openssl' is True, then the decorator checks that OpenSSL provides
    the algorithm. Otherwise the check falls back to built-in
    implementations.

    ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
    ValueError: unsupported hash type md4
    cstj�����fdd��}|S)NcsXy&�rtdk	rtj��n
tj��Wn&tk
rLtjd��d���YnX�||�S)Nz
hash digest 'z' is not available.)�_hashlib�new�hashlibr�rsrt)r��kwargs)�
digestnamer��opensslrdrer��sz7requires_hashdigest.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)rr)r�rer��sz&requires_hashdigest.<locals>.decoratorrd)rrr�rd)rrrer%}s
z	127.0.0.1z::1cCs"tj||�}t|�}|j�~|S)a�
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    OSError will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.
    )�socketrH�close)�familyZsocktypeZtempsock�portrdrdrerG�s
8cCs�|jtjkr�|jtjkr�ttd�r>|jtjtj�dkr>t	d��ttd�r~y |jtjtj
�dkrft	d��Wntk
r|YnXttd�r�|jtjtj
d�|j|df�|j�d}|S)a%Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    �SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!�SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!�SO_EXCLUSIVEADDRUSEr)rr�AF_INETr��SOCK_STREAMr�Z
getsockoptZ
SOL_SOCKETrr
rr�Z
setsockoptr�bindZgetsockname)�sock�hostrrdrdrerH�s


cCsJ|jtjkst�y|j|�Wn&tk
rD|j�tjd��YnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN)	rrZAF_UNIX�AssertionErrorr�PermissionErrorrrsrt)rZaddrrdrdrerJscCsZtjrVd}z<y"tjtjtj�}|jtdf�dStk
rBYnXWd|rT|j�XdS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6r
r�HOSTv6r�r)rrdrdre�_is_ipv6_enableds

rcstj���fdd��}|S)z5Skip the test on TLS certificate validation failures.csNy�||�Wn:tk
rH}zdt|�kr6tjd���WYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)�IOErrorrursrt)r�r�r�)r�rdre�decs
z&system_must_validate_cert.<locals>.dec)r�r�)r�rrd)r�re�system_must_validate_certs	rr�i�ZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzma�java�ANDROID_API_LEVEL�win32z/system/bin/shz/bin/shz$testz@testz	{}_{}_tmp�æ�İ�Ł�φ�К�א�،�ت�ก� �€u-àòɘŁğr�ZNFD�ntr�u-共Ł♡ͣ�ztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective��s-��surrogateescape��w����������r�ccs�d}|dkr&tj�}d}tjj|�}nBytj|�d}Wn.tk
rf|sN�tjd|t	dd�YnX|rttj
�}z
|VWd|r�|tj
�kr�t|�XdS)a�Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    FNTz+tests may fail, unable to create temp dir: �)r�)�tempfile�mkdtempr�r��realpath�mkdirr�rgr�r��getpidr)r��quietZdir_created�pidrdrdre�temp_dir�s&


r3ccsftj�}ytj|�Wn.tk
rD|s,�tjd|tdd�YnXztj�VWdtj|�XdS)agReturn a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    z)tests may fail, unable to change CWD to: r+)r�N)r��getcwd�chdirr�rgr�r�)r�r1Z	saved_dirrdrdre�
change_cwd	s

r6�tempcwdccs:t||d��$}t||d��}|VWdQRXWdQRXdS)a�
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    )r�r1)r1N)r3r6)rvr1Z	temp_pathZcwd_dirrdrdrer$s�umaskccs&tj|�}z
dVWdtj|�XdS)z8Context manager that temporarily sets the process umask.N)r�r8)r8ZoldmaskrdrdrerK8s

�datacCsbtjj|�r|S|dk	r&tjj||�}tgtj}x*|D]"}tjj||�}tjj|�r8|Sq8W|S)a[Try to find a file on sys.path or in the test directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path).

    Setting *subdir* indicates a relative path to use to find the file
    rather than looking directly in the path directories.
    N)r�r��isabsr��
TEST_HOME_DIRro�exists)r�Zsubdirr�Zdn�fnrdrdrerIs
cCs(tj|tjtjBtjB�}tj|�dS)z>Create an empty file. If the file already exists, truncate it.N)r��open�O_WRONLY�O_CREAT�O_TRUNCr)r��fdrdrdrer[scCs,t|j��}dd�|D�}dj|�}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|�qS)z%r: %rrd)�.0Zpairrdrdre�
<listcomp>cszsortdict.<locals>.<listcomp>z, z{%s})�sortedr�r�)�dictr�Z	reprpairsZ
withcommasrdrdrer[`s
cCs*ttd�}z|j�S|j�tt�XdS)z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    �wbN)r>r�filenorr)r�rdrdre�make_bad_fdgs

rI)�lineno�offsetcCsp|jt��}t|dd�WdQRX|j}|j|j�|dk	rJ|j|j|�|j|j�|dk	rl|j|j|�dS)Nz
<test string>�exec)�assertRaises�SyntaxError�compileZ	exceptionZassertIsNotNonerJ�assertEqualrK)�testcaseZ	statementrJrK�cmr�rdrdrer&sscsVddl}ddl}�jdd��|jj|�djd�d}tjjt	|�}���fdd�}tjj
|�r|||�}|dk	rt|St|�td�t
r�td	|t�d
�|jj�}tr�|jjd�|j|d
d�}tr�|jjd�dkr�tj|d�}zBt|d��.}	|j�}
x|
�r|	j|
�|j�}
�q�WWdQRXWd|j�X||�}|dk	�rF|Std|��dS)Nr�checkr��/rcs>t|f����}�dkr|S�|�r2|jd�|S|j�dS)Nr)r>�seekr)r=r�)r�rSr�rdre�check_valid_file�s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...)r��Accept-Encoding�gzip�)r�zContent-Encoding)ZfileobjrGzinvalid resource %r���)rWrX)Zurllib.requestZurllib.parse�pop�parseZurlparser�r�r�r��
TEST_DATA_DIRr<rr!rr�rZrequestZbuild_openerrXZ
addheadersr�r>Zheaders�getZGzipFile�read�writerr
)Zurlr�r��urllibr�r=rVr��opener�out�srd)r�rSr�rerI~s<	



c@s4eZdZdZdd�Zdd�Zedd��Zdd	�Zd
S)�WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS)Nr)�	_warnings�_last)�selfZ
warnings_listrdrdre�__init__�szWarningsRecorder.__init__cCsDt|j�|jkr t|jd|�S|tjjkr0dStd||f��dS)Nrz%r has no attribute %rrZ)r�rfrgr�rg�WarningMessage�_WARNING_DETAILSr�)rh�attrrdrdre�__getattr__�s
zWarningsRecorder.__getattr__cCs|j|jd�S)N)rfrg)rhrdrdrerg�szWarningsRecorder.warningscCst|j�|_dS)N)r�rfrg)rhrdrdre�reset�szWarningsRecorder.resetN)	r`rarbrcrirm�propertyrgrnrdrdrdrere�s
rec
cs
tjd�}|jjd�}|r"|j�tjdd�� }tjdjd�t	|�VWdQRXt
|�}g}xz|D]r\}}d}	xH|dd�D]8}|j}
tj
|t|
�tj�r�t|
j|�r�d}	|j|�q�W|	rf|rf|j||jf�qfW|r�td	|d
��|�rtd|d
��dS)z�Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    r�Z__warningregistry__T)�recordrg�alwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)ro�	_getframe�	f_globalsr^�clearrgrhrz�simplefilterrer|�message�re�matchru�I�
issubclassr��remover�r`r)�filtersr1�frame�registry�wZreraiseZmissingrx�cat�seenZwarningrdrdre�_filterwarnings�s0
r�cOs.|jd�}|s$dtff}|dkr$d}t||�S)a�Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    r1r�NT)r^�Warningr�)r|r�r1rdrdrerR�s

r�ccsHtjdd��&}tjd||d�dV|r.t�WdQRX|j|g�dS)a�Context manager to check that no warnings are emitted.

    This context manager enables a given warning within its scope
    and checks that no warnings are emitted even with that warning
    enabled.

    If force_gc is True, a garbage collection is attempted before checking
    for warnings. This may help to catch warnings emitted when objects
    are deleted, such as ResourceWarning.

    Other keyword arguments are passed to warnings.filterwarnings().
    T)rprq)rv�categoryN)rgrhri�
gc_collectrP)rQrvr�Zforce_gc�warnsrdrdre�check_no_warningssr�ccsBtjdd�� }tjdtd�dVt�WdQRX|j|g�dS)a"Context manager to check that no ResourceWarning is emitted.

    Usage:

        with check_no_resource_warning(self):
            f = open(...)
            ...
            del f

    You must remove the object which may emit ResourceWarning before
    the end of the context manager.
    T)rprq)r�N)rgrhri�ResourceWarningr�rP)rQr�rdrdrerSs
c@s(eZdZdZdd�Zdd�Zdd�ZdS)	ra,Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsNtjj�|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rorz�copy�original_modulesr`)rhZmodule_namesZmodule_namer�rdrdreri?s




zCleanImport.__init__cCs|S)Nrd)rhrdrdre�	__enter__LszCleanImport.__enter__cGstjj|j�dS)N)rorzr�r�)rh�
ignore_excrdrdre�__exit__OszCleanImport.__exit__N)r`rarbrcrir�r�rdrdrdrer3s

c@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)rTz_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS)N)r��environ�_environ�_changed)rhrdrdreriXszEnvironmentVarGuard.__init__cCs
|j|S)N)r�)rh�envvarrdrdre�__getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj|�|j|<||j|<dS)N)r�r�r^)rhr��valuerdrdre�__setitem___s
zEnvironmentVarGuard.__setitem__cCs2||jkr|jj|�|j|<||jkr.|j|=dS)N)r�r�r^)rhr�rdrdre�__delitem__es

zEnvironmentVarGuard.__delitem__cCs
|jj�S)N)r��keys)rhrdrdrer�lszEnvironmentVarGuard.keyscCs
t|j�S)N)�iterr�)rhrdrdre�__iter__oszEnvironmentVarGuard.__iter__cCs
t|j�S)N)r�r�)rhrdrdre�__len__rszEnvironmentVarGuard.__len__cCs|||<dS)Nrd)rhr�r�rdrdre�setuszEnvironmentVarGuard.setcCs
||=dS)Nrd)rhr�rdrdre�unsetxszEnvironmentVarGuard.unsetcCs|S)Nrd)rhrdrdrer�{szEnvironmentVarGuard.__enter__cGsJx<|jj�D].\}}|dkr0||jkr:|j|=q||j|<qW|jt_dS)N)r�r�r�r�r�)rhr��k�vrdrdrer�~s

zEnvironmentVarGuard.__exit__N)r`rarbrcrir�r�r�r�r�r�r�r�r�r�rdrdrdrerTSsc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�
DirsOnSysPatha�Context manager to temporarily add directories to sys.path.

    This makes a copy of sys.path, appends any directories given
    as positional arguments, then reverts sys.path to the copied
    settings when the context ends.

    Note that *all* sys.path modifications in the body of the
    context manager, including replacement of the object,
    will be reverted at the end of the block.
    cGs(tjdd�|_tj|_tjj|�dS)N)ror��original_value�original_object�extend)rh�pathsrdrdreri�szDirsOnSysPath.__init__cCs|S)Nrd)rhrdrdrer��szDirsOnSysPath.__enter__cGs|jt_|jtjdd�<dS)N)r�ror�r�)rhr�rdrdrer��szDirsOnSysPath.__exit__N)r`rarbrcrir�r�rdrdrdrer��s
r�c@s*eZdZdZdd�Zdd�Zd	dd�ZdS)
r'z�Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS)N)r��attrs)rhr�r�rdrdreri�szTransientResource.__init__cCs|S)Nrd)rhrdrdrer��szTransientResource.__enter__NcCsT|dk	rPt|j|�rPx:|jj�D]$\}}t||�s4Pt||�|kr Pq Wtd��dS)z�If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any).Nz%an optional resource is not available)rzr�r�r�r�r�r)rhZtype_r��	tracebackrlZ
attr_valuerdrdrer��s
zTransientResource.__exit__)NNN)r`rarbrcrir�r�rdrdrdrer'�s)�errnog>@)r��errnosc	#spd!d"d#d$d%d&g}d(d*d,d.d/g}td|��|�g��sRdd�|D��dd�|D�����fdd�}tj�}z�y|dk	r�tj|�dVWn�tjk
�r�}z&tr�tjj	�j
dd��|�WYdd}~Xn�tk
�rZ}zpx^|j
}t|�d k�rt
|dt��r|d}n*t|�dk�r8t
|d t��r8|d }nP�q�W||��WYdd}~XnXWdtj|�XdS)0z�Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.�ECONNREFUSED�o�
ECONNRESET�h�EHOSTUNREACH�q�ENETUNREACH�e�	ETIMEDOUT�n�
EADDRNOTAVAIL�c�	EAI_AGAINr+�EAI_FAILr��
EAI_NONAMEr��
EAI_NODATA��
WSANO_DATA�*zResource %r is not availablecSsg|]\}}tt||��qSrd)r�r�)rCrv�numrdrdrerD�sz&transient_internet.<locals>.<listcomp>cSsg|]\}}tt||��qSrd)r�r)rCrvr�rdrdrerD�scs�t|dd�}t|tj�s�t|tj�r,|�ks�t|tjj�rTd|jkoNdkns�t|tjj	�r�d|j
ks�d|j
ks�d|j
ks�|�kr�ts�tj
j�jdd��|�dS)	Nr�i�iW�ConnectionRefusedError�TimeoutError�EOFErrorr�
)r��
isinstancerr�Zgaierrorra�errorZ	HTTPError�codeZURLErrorr�rro�stderrr`r�)r��n)�captured_errnos�denied�
gai_errnosrdre�filter_error�s


z(transient_internet.<locals>.filter_errorNrr�r)r�r�)r�r�)r�r�)r�r�)r�r�)r�r����)r�r����)r�r����)r�r����)r�r�)r�r�)rrZgetdefaulttimeoutZsetdefaulttimeout�nntplibZNNTPTemporaryErrorrror�r`r�r�r�r�)	Z
resource_namer�r�Zdefault_errnosZdefault_gai_errnosr�Zold_timeoutr��ard)r�r�r�rer+�sP



c
csFddl}tt|�}tt||j��ztt|�VWdtt||�XdS)z�Return a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.rN)�ior�ro�setattr�StringIO)Zstream_namer�Zorig_stdoutrdrdre�captured_outputs
r�cCstd�S)z�Capture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r�)r�rdrdrdrerscCstd�S)z�Capture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    r�)r�rdrdrdrer%scCstd�S)a	Capture the input to sys.stdin:

       with captured_stdin() as stdin:
           stdin.write('hello\n')
           stdin.seek(0)
           # call test code that consumes from sys.stdin
           captured = input()
       self.assertEqual(captured, "hello")
    �stdin)r�rdrdrdrer.s
cCs*tj�trtjd�tj�tj�dS)a�Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    g�������?N)�gcZcollectr@r�r�rdrdrdrer�;s


r�c
cs.tj�}tj�z
dVWd|r(tj�XdS)N)r��	isenabled�disable�enable)Zhave_gcrdrdre�
disable_gcKs
r�cCs:tjd�pd}d}x|j�D]}|jd�r|}qW|dkS)z,Find if Python was built with optimizations.�	PY_CFLAGSr�z-O�-O0�-Og)r�r�r�)�	sysconfig�get_config_varr�rq)ZcflagsZ	final_optr�rdrdre�python_is_optimizedVs
r�ZnPZ0n�gettotalrefcountZ2PZ0Pr�cCstjt|t�S)N)�struct�calcsize�_header�_align)�fmtrdrdre�calcobjsizegsr�cCstjt|t�S)N)r�r��_vheaderr�)r�rdrdre�calcvobjsizejsr���	cCspddl}tj|�}t|�tkr(|jt@sBt|�tkrLt|�jt@rL||j7}dt|�||f}|j|||�dS)Nrz&wrong size for %s: got %d, expected %d)	�	_testcapiro�	getsizeofr��	__flags__�_TPFLAGS_HEAPTYPE�_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrP)�test�o�sizer�r�rxrdrdre�check_sizeofqs

r�cs��fdd�}|S)Ncs$���fdd�}�j|_�j|_|S)Ncs�y ddl}t|��}|j|�}Wn(tk
r6�YnBd}}Yn0Xx,�D]$}y|j||�PWqPYqPXqPWz
�||�S|r�|r�|j||�XdS)Nr)�localer��	setlocaler�)r��kwdsr�r�Zorig_locale�loc)�catstrr��localesrdre�inner�s$



z1run_with_locale.<locals>.decorator.<locals>.inner)r`rc)r�r�)r�r�)r�rer��sz"run_with_locale.<locals>.decoratorrd)r�r�r�rd)r�r�rerU�scs�fdd�}|S)Ncs"��fdd�}�j|_�j|_|S)Ncs�y
tj}Wntk
r(tjd��YnXdtjkr@tjd}nd}�tjd<|�z
�||�S|dkrrtjd=n
|tjd<tj�XdS)Nztzset requiredZTZ)r��tzsetr�rsrtr�r�)r�r�r�Zorig_tz)r��tzrdrer��s





z-run_with_tz.<locals>.decorator.<locals>.inner)r`rc)r�r�)r�)r�rer��szrun_with_tz.<locals>.decoratorrd)r�r�rd)r�rer\�scCs�dttdtd�}tjd|tjtjB�}|dkr>td|f��tt|j	d��||j	d�j
��}|a|tkrrt}|t
dkr�td|f��|adS)Ni)r��m�g�tz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr+z$Memory limit %r too low to be useful)�_1M�_1Grwrx�
IGNORECASE�VERBOSEr�r��float�group�lower�real_max_memuse�MAX_Py_ssize_t�_2Gr)�limitZsizesr�ZmemlimitrdrdrerY�s$c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    cCsdjtj�d�|_d|_dS)Nz/proc/{pid}/statm)r2F)r�r�r0�procfile�started)rhrdrdreri�sz_MemoryWatchdog.__init__cCs�yt|jd�}Wn<tk
rL}z tjdj|�t�tjj	�dSd}~XnXt
d�}tjtj
|g|tjd�|_|j�d|_dS)N�rz!/proc not available for stats: {}zmemory_watchdog.py)r�r�T)r>r
r�rgr�r�r�ror��flushr�
subprocess�Popen�
executableZDEVNULL�mem_watchdogrr)rhr�r�Zwatchdog_scriptrdrdre�start�s
z_MemoryWatchdog.startcCs|jr|jj�|jj�dS)N)rrZ	terminate�wait)rhrdrdre�stop�s
z_MemoryWatchdog.stopN)r`rarbrcrirrrdrdrdrer	�sr	cs���fdd�}|S)atDecorator for bigmem tests.

    'size' is a requested size for the test (in arbitrary, test-interpreted
    units.) 'memuse' is the number of bytes per unit for the test, or a good
    estimate of it. For example, a test that needs two byte buffers, of 4 GiB
    each, could be decorated with @bigmemtest(size=_4G, memuse=2).

    The 'size' argument is normally passed to the decorated test method as an
    extra argument. If 'dry_run' is true, the value passed to the test method
    may be less than the requested value. If 'dry_run' is false, it means the
    test doesn't support dummy runs when -M is not specified.
    cs ���fdd����_��_�S)Nc
s��j}�j}tsd}n|}ts$�rFt||krFtjd||d��tr|tr|t�tdj||dd��t�}|j	�nd}z
�||�S|r�|j
�XdS)	Niz'not enough memory: %.1fG minimum neededir+z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@)r��memuserrsrtrr�r�r	rr)rhr�r�maxsizeZwatchdog)�dry_runr�r�rdrer�s*


z.bigmemtest.<locals>.decorator.<locals>.wrapper)r�r)r�)rrr�)r�r�rer�szbigmemtest.<locals>.decoratorrd)r�rrr�rd)rrr�rer3s
!cs�fdd�}|S)z0Decorator for tests that fill the address space.csDttkr8td
kr$tdkr$tjd��q@tjdtd��n�|�SdS)
Nr��?r�z-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir+ll����li@)rrrsrt)rh)r�rdrer�3sz!bigaddrspacetest.<locals>.wrapperrd)r�r�rd)r�rer41sc@seZdZdd�ZdS)r,cCstj�}||�|S)N)rsZ
TestResult)rhr�r�rdrdre�runDszBasicTestRunner.runN)r`rarbrrdrdrdrer,CscCs|S)Nrd)r�rdrdre�_idIsrcCs<|dkrt�rtjtj�St|�r(tStjdj|��SdS)Nr�zresource {0!r} is not enabled)r�rs�skipr�r rr�)r�rdrdre�requires_resourceLs
rcCs&trt|krtjd|tf�StSdS)Nz%s at Android API level %d)rA�_ANDROID_API_LEVELrsrr)�levelr�rdrdrer>TscCstdd�|�S)z9
    Decorator for tests only applicable on CPython.
    T)�cpython)�impl_detail)r�rdrdrer5[scKsVtf|�rtS|dkrLt|�\}}|r,d}nd}t|j��}|jdj|��}tj|�S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rBr�
_parse_guardsrEr�r�r�rsr)rx�guardsZ
guardnames�defaultrdrdrer!as
r!cCsTtdkr:ddl}y|j�daWntk
r8daYnXd}trF|Stj|�|�S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)�_have_mp_queue�multiprocessingZQueuernrsr)r�r&rxrdrdrer?os
cCsH|sddidfSt|j��d}t|j��|gt|�ks>t�||fS)Nr TFr)r|�valuesr�r)r#Zis_truerdrdrer"~s
r"cKs t|�\}}|jtj�j�|�S)a5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    )r"r^rpZpython_implementationr)r#r$rdrdrerB�scs,ttd�s�Stj���fdd��}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.�gettracecs.tj�}ztjd��||�Stj|�XdS)N)ror(�settrace)r�r�Zoriginal_trace)r�rdrer��s


zno_tracing.<locals>.wrapperN)r�ror�r�)r�r�rd)r�re�
no_tracing�s
r*cCstt|��S)aDecorator for tests which involve reference counting.

    To start, the decorator does not run the test if is not run by CPython.
    After that, any trace function is unset during the test to prevent
    unexpected refcounts caused by the trace function.

    )r*r5)r�rdrdre�
refcount_test�sr+cCsRg}xB|jD]8}t|tj�r2t||�|j|�q||�r|j|�qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsr�rs�	TestSuite�
_filter_suiter�)�suiteZpredZnewtestsr�rdrdrer-�s
r-cCs�ttjttdk	d�}|j|�}tdk	r4tj|j��|js>t	�|j
�s�t|j�dkrl|j
rl|jdd}n6t|j
�dkr�|jr�|j
dd}nd}ts�|d7}t|��dS)z2Run tests from a unittest.TestSuite-derived class.N)�	verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rror�r�junit_xml_listrr�Zget_xml_elementZtestsRunrZ
wasSuccessfulr��errorsZfailuresr
)r.Zrunnerr�r�rdrdre�
_run_suite�s"
r2cCstdkrdSt|j��SdS)NT)�_match_test_func�id)r�rdrdre�
match_test�sr5cCsd|kotjd|�S)Nryz[?*\[\]])rw�search)r�rdrdre�_is_full_match_test�sr7csr|tkrdS|sd}f}nHttt|��r4t|�j}n.djttj|��}t	j
|�j��fdd�}|}t|�a|a
dS)N�|cs$�|�rdStt�|jd���SdS)NTry)�anyr�r�)Ztest_id)�regex_matchrdre�match_test_regex�sz)set_match_tests.<locals>.match_test_regex)�_match_test_patterns�allr�r7r��__contains__r��fnmatch�	translaterwrOrxrrr3)Zpatternsr�Zregexr;rd)r:re�set_match_tests�srAcGs�tjtjf}tj�}xh|D]`}t|t�rT|tjkrJ|jtjtj|��qzt	d��qt||�rj|j|�q|jtj
|��qWt|t�t
|�dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rsr,ZTestCaser�rurorzZaddTestZ
findTestCasesr�Z	makeSuiter-r5r2)�classesZvalid_typesr.�clsrdrdrer-s





cCsdS)z,Just used to check if docstrings are enabledNrdrdrdrdre�_check_docstrings(srD�WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d�\}}|rBtd||f��trXtd|j|f�||fS)aRun doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    rN)r�optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)�doctestrZtestmodr
r�r`)r�r/rFrGr�r�rdrdrer.9scCstjj�fS)N)rorzr�rdrdrdre�
modules_setupTsrHcCs:dd�tjj�D�}tjj�tjj|�tjj|�dS)NcSs"g|]\}}|jd�r||f�qS)z
encodings.)rq)rCr�r�rdrdrerD[sz#modules_cleanup.<locals>.<listcomp>)rorzr�rtr�)Z
oldmodulesZ	encodingsrdrdre�modules_cleanupWs
rIcCs"trtj�tjj�fSdffSdS)Nr)�_thread�_count�	threading�	_danglingr�rdrdrdrerNzscGsJtsdSd}x8t|�D],}tj�tjf}||kr2Ptjd�t�qWdS)N�dg{�G�z�?)rJ�rangerKrLrMr�r�r�)Zoriginal_valuesZ
_MAX_COUNT�countr'rdrdrerO�s
cs"ts�Stj���fdd��}|S)z�Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cst�}z�|�St|�XdS)N)rNrO)r��key)r�rdrer��szreap_threads.<locals>.decorator)rJr�r�)r�r�rd)r�rerP�s�N@ccs�tj�}z
dVWdtj�}||}xjtj�}||kr8Ptj�|kr|tj�|}d||�d|d�d|�d|�d�	}t|��tjd�t�q&WXdS)	aH
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use _thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the _thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the _thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z
, old count: �)g{�G�z�?)rJrKr�Z	monotonicrr�r�)r�Z	old_countZ
start_timeZdeadlinerPZdtrxrdrdre�wait_threads_exit�s
$
rTc
CsZttd�rVd}xFy2tj|tj�\}}|dkr.Ptd|tjd�WqPYqXqWdS)z�Use this function at the end of test_main() whenever sub-processes
    are started.  This will help ensure that no extra children (zombies)
    stick around to hog resources and create problems when looking
    for refleaks.
    �waitpidrrz2Warning -- reap_children() reaped child process %s)r�NrZ)r�r�rU�WNOHANGr�ror�)Zany_processr2ZstatusrdrdrerL�s
ccs*t|�}g}zZy$x|D]}|j�|j|�qWWn*trVtdt|�t|�f��YnXdVWdz�|rt|�tj�}}xltdd�D]^}|d7}x$|D]}|jt	|tj�d��q�Wdd�|D�}|s�Ptr�tdt|�|f�q�WWdd	d�|D�}|�r"t
jtj
�td
t|���XXdS)Nz/Can't start %d threads, only %d threads startedrr�<g{�G�z�?cSsg|]}|j�r|�qSrd)�isAlive)rCr�rdrdrerD�sz!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSsg|]}|j�r|�qSrd)rX)rCr�rdrdrerD�szUnable to join %d threads)r|rr�rr�r�r�rOr��max�faulthandlerZdump_tracebackror�r)ZthreadsZunlockrr�ZendtimeZ	starttimer�rdrdrerQ�s>


c
csnt||�r<t||�}t|||�z
|VWdt|||�Xn.t|||�z
dVWdt||�rht||�XdS)a�Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        This will set obj.attr to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `attr` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N)r�r�r��delattr)r�rl�new_val�real_valrdrdrerW�s




ccsX||kr0||}|||<z
|VWd|||<Xn$|||<z
dVWd||krR||=XdS)a�Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    Nrd)r��itemr\r]rdrdrerV	s

cCstjdd|�j�}|S)z�Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs, \d+ blocks\]\r?\n?�)rw�sub�strip)r�rdrdre�strip_python_stderr8	srbZ	getcountsz-types are immortal if COUNT_ALLOCS is definedcCstj�S)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)rZ_args_from_interpreter_flagsrdrdrdre�args_from_interpreter_flagsE	srccCstj�S)zgReturn a list of command-line arguments reproducing the current
    optimization settings in sys.flags.)rZ"_optim_args_from_interpreter_flagsrdrdrdre�!optim_args_from_interpreter_flagsJ	srdc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rMcCstjjj|d�||_dS)Nr)�logging�handlers�BufferingHandlerri�matcher)rhrhrdrdreriT	szTestHandler.__init__cCsdS)NFrd)rhrdrdre�shouldFlush]	szTestHandler.shouldFlushcCs|j|�|jj|j�dS)N)r�r�r��__dict__)rhrprdrdre�emit`	s
zTestHandler.emitcKs.d}x$|jD]}|jj|f|�rd}PqW|S)zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)r�rh�matches)rhr�r��drdrdrerld	szTestHandler.matchesN)r`rarbririrkrlrdrdrdrerMS	s	c@s eZdZdZdd�Zdd�ZdS)	rXrxrvcKs<d}x2|D]*}||}|j|�}|j|||�s
d}Pq
W|S)a.
        Try to match a single dict with the supplied arguments.

        Keys whose values are strings and which are in self._partial_matches
        will be checked for partial (i.e. substring) matches. You can extend
        this scheme to (for example) do regular expression matching, etc.
        TF)r^�match_value)rhrmr�r�r�r��dvrdrdrerls	s

zMatcher.matchescCsHt|�t|�krd}n.t|�tk	s,||jkr6||k}n|j|�dk}|S)zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr)r�ru�_partial_matches�find)rhr�ror�r�rdrdrern�	s
zMatcher.match_valueN)rxrv)r`rarbrprlrnrdrdrdrerXo	sc
CsZtdk	rtStd}ytjt|�d}Wntttfk
rFd}YnXtj|�|a|S)NrTF)�_can_symlinkrr��symlinkr��NotImplementedErrorr�r{)Zsymlink_path�canrdrdrer�	s

cCs t�}d}|r|Stj|�|�S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrsr)r��okrxrdrdrer/�	scCs�tdk	rtSttd�sd}n�tj�}tj|d�\}}z�ttd���}y`tj|dd�tj|dd�tj|j	�dd�t
j�}tj
d	|�}|dkp�t|jd
��dk}Wntk
r�d}YnXWdQRXWdtt�t|�t|�X|a|S)N�setxattrF)�dirrGs	user.testr_strusted.foos42z
2.6.(\d{1,2})r�')�
_can_xattrr�r�r,r-Zmkstempr>rrwrHrpr�rwrxr�rr�rr�)ruZtmp_dirZtmp_fpZtmp_name�fpZkernel_versionr�rdrdre�	can_xattr�	s,

r|cCs t�}d}|r|Stj|�|�S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r|rsr)r�rvrxrdrdrer8�	scCs$tpt}d}|r|Stj|�|�S)z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r]�PGO_EXTENDEDrsr)r�rvrxrdrdre�skip_if_pgo_task�	s
r~cCs^tj|d��H}|j}|j�}||kr,|j�}ytjj||�Stk
rNdSXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.)rxFN)	r,ZNamedTemporaryFilerv�upperrr�r��samefiler�)Z	directory�base�	base_pathZ	case_pathrdrdrer�	s)rfcCs>tt|��tt|��}|r(|t|�8}tdd�|D��}|S)aReturns the set of items in ref_api not in other_api, except for a
    defined list of items to be ignored in this check.

    By default this skips private attributes beginning with '_' but
    includes all magic methods, i.e. those starting and ending in '__'.
    css(|] }|jd�s|jd�r|VqdS)�_�__N)rq�endswith)rCr�rdrdre�	<genexpr>�	sz&detect_api_mismatch.<locals>.<genexpr>)r�rx)Zref_apiZ	other_apirfZ
missing_itemsrdrdrer<�	s
cCs�|dkr|jf}nt|t�r"|f}t|�}xbt|�D]V}|jd�s4||krLq4t||�}t|dd�|ks�t|d�r4t|tj	�r4|j
|�q4W|j|j|�dS)aAssert that the __all__ variable of 'module' contains all public names.

    The module's public names (its API) are detected automatically based on
    whether they match the public name convention and were defined in
    'module'.

    The 'name_of_module' argument can specify (as a string or tuple thereof)
    what module(s) an API could be defined in in order to be detected as a
    public API. One case for this is when 'module' imports part of its public
    API from other modules, possibly a C backend (like 'csv' and its '_csv').

    The 'extra' argument can be a set of names that wouldn't otherwise be
    automatically detected as "public", like objects without a proper
    '__module__' attribute. If provided, it will be added to the
    automatically detected ones.

    The 'blacklist' argument can be a set of names that must not be treated
    as part of the public API even though their names indicate otherwise.

    Usage:
        import bar
        import foo
        import unittest
        from test import support

        class MiscTestCase(unittest.TestCase):
            def test__all__(self):
                support.check__all__(self, foo)

        class OtherTestCase(unittest.TestCase):
            def test__all__(self):
                extra = {'BAR_CONST', 'FOO_CONST'}
                blacklist = {'baz'}  # Undocumented name.
                # bar imports part of its API from _bar.
                support.check__all__(self, bar, ('bar', '_bar'),
                                     extra=extra, blacklist=blacklist)

    Nr�ra)
r`r�rur�rxrqr�r��types�
ModuleType�addZassertCountEqual�__all__)Z	test_caser�Zname_of_moduleZextraZ	blacklistZexpectedrvr�rdrdrer=�	s)


c@s(eZdZdZdZdZdd�Zdd�ZdS)rZz�Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    Nc
Csrtjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
rlYnLXi|_
x�|j|j|jgD].}|j
||j�}|j||j�}||f|j
|<q�Wn�tdk	�r
y*tjtj�|_tjtjd|jdf�Wnttfk
�rYnXtjdk�rnddd	d
g}tj|tjtjd�}|�|j�d}	WdQRX|	j�dk�rntd
ddd�|S)z�On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        r�rNr�rr�z/usr/bin/defaultsr_zcom.apple.CrashReporterZ
DialogType)r�r�s	developerz:this test triggers the Crash Reporter, that is intentionalr�T)�endr
) rorprqr�r�r��_k32�SetErrorMode�	old_value�msvcrt�CrtSetReportModer�rn�	old_modes�CRT_WARN�	CRT_ERROR�
CRT_ASSERTZCRTDBG_MODE_FILE�CrtSetReportFileZCRTDBG_FILE_STDERRr�Z	getrlimit�RLIMIT_CORE�	setrlimitr�r�rr�PIPEZcommunicaterar�)
rhr�ZSEM_NOGPFAULTERRORBOXr��report_type�old_mode�old_file�cmd�procr�rdrdrer�2
sN




zSuppressCrashReport.__enter__cGs�|jdkrdStjjd�rl|jj|j�|jr�ddl}xj|jj�D]$\}\}}|j	||�|j
||�qBWn6tdk	r�ytjtj
|j�Wnttfk
r�YnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nr�r)r�rorprqr�r�r�r�r�r�r�r�r�r�r�r�)rhr�r�r�r�r�rdrdrer�s
s
zSuppressCrashReport.__exit__)r`rarbrcr�r�r�r�rdrdrdrerZ)
s
Acsrt���d�y�j��Wn$ttfk
r@t��d��YnXd�����fdd�}|j|�t��|�dS)z�Override 'object_to_patch'.'attr_name' with 'new_value'.

    Also, add a cleanup procedure to 'test_instance' to restore
    'object_to_patch' value for 'attr_name'.
    The 'attr_name' should be a valid attribute for 'object_to_patch'.

    FNTcs �rt����n
t���dS)N)r�r[rd)�
attr_is_local�	attr_name�object_to_patchr�rdre�cleanup�
szpatch.<locals>.cleanup)r�rjr�r�Z
addCleanupr�)Z
test_instancer�r�Z	new_valuer�rd)r�r�r�r�re�patch�
s


r�cCsFyddl}Wntk
r YnX|j�r4tjd��ddl}|j|�S)zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)�tracemallocrnZ
is_tracingrsrtr��run_in_subinterp)r�r�r�rdrdrer��
s
r�csHG��fdd�d|�}d�|||���|jtt��t�|j��dS)NcseZdZ��fdd�ZdS)z%check_free_after_iterating.<locals>.Acs*d�yt��Wntk
r$YnXdS)NT)�next�
StopIteration)rh)�done�itrdre�__del__�
s
z-check_free_after_iterating.<locals>.A.__del__N)r`rarbr�rd)r�r�rdre�A�
sr�F)rMr�r�r�Z
assertTrue)r�r�rCr�r�rd)r�r�re�check_free_after_iterating�
s	r�cCs�ddlm}m}m}|j�}|j|�xd|jD]Z}|r@||kr@q.t||�}|rd|dk	sntd|��n
|dkrnq.|j	|d�dkr.|dSq.WdS)a<Check if the compiler components used to build the interpreter exist.

    Check for the existence of the compiler executables whose names are listed
    in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
    and return the first missing executable or None when none is found
    missing.

    r)�	ccompilerr��spawnNz%the '%s' executable is not configured)
Z	distutilsr�r�r�Znew_compilerZcustomize_compilerZexecutablesr�rZfind_executable)Z	cmd_namesr�r�r�Zcompilerrvr�rdrdrer^�
s	


cCs@d}tr6||kr6tdkr.tjddg�j�dkatr6|}tj|�S)Ng�h㈵��>Zgetpropzro.kernel.qemu�1)rA�_is_android_emulatorrZcheck_outputrarorD)ZintervalZminimum_intervalrdrdrerD�
sc
cs>tjj�}tj�}ztj�dVWd|r8tj|dd�XdS)NT)r�Zall_threads)ror�rHrZ�
is_enabledr�r�)rBr�rdrdre�disable_faulthandler�
s

r�c	/Cs�tjjd�r8ytjd�}t|�dStk
r6YnXd}ttd�rjytjd�}Wnt	k
rhYnXd}tjd	kr�yd
dl
}|jWntt
fk
r�Yn0Xi}x(|j|j|jfD]}|j|d
�||<q�Wzpd
}xft|�D]Z}ytj|�}Wn4t	k
�r(}z|jtjk�r�WYdd}~Xq�Xtj|�|d7}q�WWd|dk	�rzx*|j|j|jfD]}|j|||��q`WX|S)z/Count the number of open file descriptors.
    �linux�freebsdz
/proc/self/fdr��sysconf�SC_OPEN_MAXNrr)r�r�)rorprqr�r�r�r�r�r�r�r�r�r�rnr�r�r�rO�dupr�ZEBADFr)	�namesZMAXFDr�r�r�rPrBZfd2r�rdrdrer_	sP





c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�SaveSignalsz�
    Save an restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    cCsjddl}||_ttd|j��|_x>dD]6}yt||�}Wntk
rNw&YnX|jj|�q&Wi|_dS)Nrr�SIGKILL�SIGSTOP)r�r�)	�signalr|rO�NSIG�signalsr�r�r{rf)rhr�Zsigname�signumrdrdreriMs
zSaveSignals.__init__cCs4x.|jD]$}|jj|�}|dkr"q||j|<qWdS)N)r�r��	getsignalrf)rhr��handlerrdrdre�saveZs
zSaveSignals.savecCs*x$|jj�D]\}}|jj||�qWdS)N)rfr�r�)rhr�r�rdrdre�restorefszSaveSignals.restoreN)r`rarbrcrir�r�rdrdrdrer�Ds
r�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�FakePathz.Simple implementing of the path protocol.
    cCs
||_dS)N)r�)rhr�rdrdrerinszFakePath.__init__cCsd|j�d�S)Nz
<FakePath �>)r�)rhrdrdre�__repr__qszFakePath.__repr__cCs6t|jt�s$t|jt�r,t|jt�r,|j�n|jSdS)N)r�r��
BaseExceptionr�rz)rhrdrdre�
__fspath__ts
zFakePath.__fspath__N)r`rarbrcrir�r�rdrdrdrer�ksr�ccs.tj�}ztj|�dVWdtj|�XdS)z>Temporarily change the integer string conversion length limit.N)ro�get_int_max_str_digits�set_int_max_str_digits)Z
max_digitsZcurrentrdrdre�adjust_int_max_str_digits|s


r�)T)F)F)N)Nii@i@i@ii)rrrrrrrr r!r"r#)r'r%r(r)r*)NF)F)r7F)N)Fi@ii)T)N)Nr)rR)N(rcr`rn�collections.abc�collections�
contextlibZdatetimer�rZr?r�r�r�rm�importlib.utilr�Zlogging.handlersrer�r�rprwr�rr�r�rror�r,r�r�rsZurllib.errorrargZ
testresultrrJrLZmultiprocessing.processr&�zlibrX�bz2Zlzmar�r�r�r�r	r
rrtr�contextmanagerrkr
rr�r:r;rr6rrrrr0rr�rrrr�rqr�r�r�r�r�rr�rr�rr�r r!r�r"r#r$r%rErr	r
rGrHrJrrFrrZ
SOCK_MAX_SIZEZ
skipUnlessr�
__getformat__r7r9r0r1r2r@r�rrArCrvrr�r0ZFS_NONASCII�	character�fsdecode�fsencode�UnicodeErrorZTESTFN_UNICODEZunicodedataZ	normalize�getfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversion�encode�UnicodeEncodeErrorr��decode�UnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr4rr]r}r3r6rr�rKr�r�r�r�ZTEST_SUPPORT_DIRr;r�r]rrr[rIr&rI�objectrer�rRr�r�rSr�abc�MutableMappingrTr�r'r�r�r(r�r)r*r+r�rrrr�r�r�r�r�r�r�r�r�r�r�rUr\r�r�rZ_4GrrrYr	r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZr�r�r�r^r�rDr�r_r�r�r�rdrdrdre�<module>s�











2	
!

J			>%	


%2' 5M		



$
#
0







(




"
#
	"
:_";'PK�R�Z�r�&XX3support/__pycache__/testresult.cpython-36.opt-1.pycnu�[���3


 \
�@s6dZddlZddlZddlZddlZddlZddlZddljj	Z
ddlmZGdd�dej�Z
Gdd�d�Zdd	d
�Zddd�Zed
k�r2Gdd�dej�Zej�Zejeje��ej�Zeedd�ejD���Zeej�Zeje�Z e!dej"��e!ddd�x(e
j#e j$��D]Z%e!e%j&�dd��qWe!�dS)z=Test runner and result class for the regression test suite.

�N)�datetimecs�eZdZdddZdddZ�fdd�Zedd��Z�fd	d
�Zd$dd
�Z	dd�Z
edd��Z�fdd�Z�fdd�Z
�fdd�Z�fdd�Z�fdd�Z�fdd�Zdd�Zd d!�Zd"d#�Z�ZS)%�RegressionTestResult�=�F�
�-cs\t�j||dd�d|_tjd�|_|jjdtj�j	d��d|_
d|_g|_t
|�|_dS)Nr)�stream�descriptions�	verbosityTZ	testsuite�start� )�super�__init__�buffer�ETZElement�_RegressionTestResult__suite�setrZutcnowZ	isoformat�_RegressionTestResult__e�!_RegressionTestResult__start_timeZ_RegressionTestResult__results�bool�_RegressionTestResult__verbose)�selfrr	r
)�	__class__��//usr/lib64/python3.6/test/support/testresult.pyrszRegressionTestResult.__init__cCsLy
|j}Wntk
r"t|�SXy|�Stk
rBt|�SXt|�S)N)�id�AttributeError�str�	TypeError�repr)�cls�testZtest_idrrrZ__getIds


zRegressionTestResult.__getIdcsVt�j|�tj|jd�|_}tj�|_|j	rR|j
j|j|��d��|j
j
�dS)NZtestcasez ... )r
�	startTestr�
SubElementrr�time�perf_counterrrr�write�getDescription�flush)rr!�e)rrrr"+s
zRegressionTestResult.startTestFcKsP|j}d|_|dkrdS|jd|jd|j|���|jd|jdd��|jd|jdd��|jrz|jdtj�|jd��|r�|jdk	r�|jj�j	�}|t
j|d�_|j
dk	r�|j
j�j	�}|t
j|d	�_x�|j�D]t\}}|s�|r�q�t
j||�}	t|d
��r>xD|j�D],\}
}|
�r,|	j|
t|��n
t|�|	_�qWq�t|�|	_q�WdS)N�nameZstatus�run�resultZ	completedr$z0.6fz
system-outz
system-err�items)rr�pop�_RegressionTestResult__getIdrr$r%Z_stdout_buffer�getvalue�rstriprr#�textZ_stderr_bufferr-�hasattrr)rr!Zcapture�argsr)�stdout�stderr�k�vZe2Zk2Zv2rrr�_add_result3s4

z RegressionTestResult._add_resultcCs|jr|jj|�d��dS)Nr)rrr&)r�cZwordrrrZ__writeSszRegressionTestResult.__writecCslt|t�r0|jdkr|j}q8|j�d|j��}nt|�}tj||d�}tj|||�}|dj|�dj|�d�S)N�builtins�.�)�type�messager=)�
isinstancer>�
__module__�__name__r�	traceback�format_exception�join)r Zerr_typeZ	err_valueZerr_tb�typename�msg�tbrrrZ__makeErrorDictWs

z$RegressionTestResult.__makeErrorDictcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�error�E�ERROR)r9�$_RegressionTestResult__makeErrorDictr
�addError�_RegressionTestResult__write)rr!�err)rrrrMjszRegressionTestResult.addErrorcs4|j|d|j|�d�t�j||�|jdd�dS)NT)�output�xzexpected failure)r9rLr
�addExpectedFailurerN)rr!rO)rrrrRosz'RegressionTestResult.addExpectedFailurecs4|j|d|j|�d�t�j||�|jdd�dS)NT)Zfailure�F�FAIL)r9rLr
�
addFailurerN)rr!rO)rrrrUtszRegressionTestResult.addFailurecs2|j||d�t�j||�|jdd|���dS)N)Zskipped�Szskipped )r9r
�addSkiprN)rr!�reason)rrrrWyszRegressionTestResult.addSkipcs&|j|�t�j|�|jdd�dS)Nr<�ok)r9r
�
addSuccessrN)rr!)rrrrZ~s
zRegressionTestResult.addSuccesscs*|j|dd�t�j|�|jdd�dS)NZUNEXPECTED_SUCCESS)Zoutcome�uzunexpected success)r9r
�addUnexpectedSuccessrN)rr!)rrrr\�sz)RegressionTestResult.addUnexpectedSuccesscCs2|jr|jjd�|jd|j�|jd|j�dS)NrrKrT)rrr&�printErrorList�errors�failures)rrrr�printErrors�sz RegressionTestResult.printErrorscCs`xZ|D]R\}}|jj|j�|jj|�d|j|��d��|jj|j�|jjd|�qWdS)Nz: rz%s
)rr&�
separator1r'�
separator2)rZflavorr^r!rOrrrr]�s
z#RegressionTestResult.printErrorListcCsH|j}|jdt|j��|jdtt|j���|jdtt|j���|S)NZtestsr^r_)rrrZtestsRun�lenr^r_)rr)rrr�get_xml_element�s
z$RegressionTestResult.get_xml_element)F)rBrA�__qualname__rarbr�classmethodr/r"r9rNrLrMrRrUrWrZr\r`r]rd�
__classcell__rr)rrrs"
 rc@seZdZddd�Zdd�ZdS)�QuietRegressionTestRunnerFcCst|dd�|_||j_dS)Nr)rr,r)rrrrrrr�sz"QuietRegressionTestRunner.__init__cCs||j�|jS)N)r,)rr!rrrr+�s
zQuietRegressionTestRunner.runN)F)rBrArerr+rrrrrh�s
rhFcCs&|rtjtjt||d�Stjt|d�S)N)Zresultclassrr
)r)�	functools�partial�unittestZTextTestRunnerrrh)r
rrrr�get_test_runner_class�srlcCst||�|�S)N)rl)rr
Zcapture_outputrrr�get_test_runner�srm�__main__c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�	TestTestscCsdS)Nr)rrrr�	test_pass�szTestTests.test_passcCstjd�dS)Ng�?)r$Zsleep)rrrr�test_pass_slow�szTestTests.test_pass_slowcCs*tdtjd�tdtjd�|jd�dS)Nr5)�filer6zfailure message)�print�sysr5r6Zfail)rrrr�	test_fail�szTestTests.test_failcCs(tdtjd�tdtjd�td��dS)Nr5)rrr6z
error message)rsrtr5r6�RuntimeError)rrrr�
test_error�szTestTests.test_errorN)rBrArerprqrurwrrrrro�sroccs|]}|dkVqdS)z-vNr)�.0�arrr�	<genexpr>�srzzOutput:zXML: r=)�end)F)F)'�__doc__ri�iortr$rCrkZxml.etree.ElementTreeZetreeZElementTreerrZTextTestResultrrhrlrmrBZTestCaseroZ	TestSuiteZsuiteZaddTestZ	makeSuite�StringIOr�sum�argvZ
runner_clsr5Zrunnerr+r,rsr0Ztostringlistrd�s�decoderrrr�<module>s4
	




PK�R�ZMhU-=-=1support/__pycache__/__init__.cpython-36.opt-1.pycnu�[���3

�\dh����@s^
dZedkred��ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZ
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl!Z"ddl#Z#ddl$m%Z%yddl&Z&ddl'Z'Wnek
�rBdZ&dZ'YnXyddl(Z)Wnek
�rjdZ)YnXyddl*Z*Wnek
�r�dZ*YnXyddl+Z+Wnek
�r�dZ+YnXyddl,Z,Wnek
�r�dZ,YnXyddl-Z-Wnek
�r
dZ-YnXyddl.Z.Wnek
�r2dZ.YnXyddl/Z/Wnek
�rZdZ/YnXddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbg\Z0Gdcd�de1�Z2Gddd
�d
e2�Z3Gded�de2�Z4Gdfd�de j5�Z6ej7�dfdhdi��Z8�dgfdk�dld�Z9dmdn�Z:dodp�Z;dqd=�Z<drd>�Z=ffdjfdsd�Z>dtd9�Z?dZ@dZAdaBdaCdZDdjZEdaFdud�ZGdvd�ZHdwd�ZIdxdy�ZJejjKdz��r.�dhd{d|�ZLd}d~�ZMdd��ZNd�d��ZOd�d��ZPnejQZMejRZNd�d��ZOd�d��ZPd�d�ZQd�d��ZRd�d�ZSd�d��ZTd�d�ZUd�d��ZVd�d#�ZW�did�d$�ZXd�d��ZYd�d%�ZZd�d&�Z[d�d'�Z\�djd�d(�Z]d�Z^d�Z_ej`ejafd�dJ�Zbe^fd�dK�Zcd�dM�Zdd�d��Zeee�Zfd�d��Zg�dmZh�dpZie jjekjld��jKd��d��Zme jje*d��Zne jje+d��Zoe jje,d��Zpe jje-d��ZqejjKd��Zrejsd��Ztetdk	�oxetdkZuejd�k�r�eu�r�d�nd�ZvndZvejwd�k�r�d�Zxnd�Zxd�jyexejz��ZxdZ{xL�dqD]BZ|yej}ej~e|��e|k�r�e�Wnek
�rYnXe|Z{P�q�Wexd�Z�ejd�k�r:ddl�Z�e�j�d�e��Z�ej��Z�dZ�ejwd�k�r�ej��jd�k�r�exd�Z�ye�j�e��Wne�k
�r�YnXe�d�e�e�f�dZ�nBejd�k�r�yd�j�e��Wn&e�k
�r�exd�j�e�dǃZ�YnXdZ�xF�drD]<Zwyewj�e��Wn&e�k
�r,ej~ex�ewZ�PYnX�q�We{�rHexd�e{Z�ndZ�ej��Z�djZ�djZ�ej7�dsd�d΄�Z�ej7�dtd�dЄ�Z�ej7�dud�d��Z�e�edӃ�r�ej7d�dN��Z�ej�j�ej�j�e���Z�ej�j�e��Z�ej�j�e�dՃZ��dvd�d�Z�d�d �Z�d�d^�Z�d�dڄZ�dddۜd�d)�Z�d�dL�Z�Gd�d߄d�e��Z��dwd�d�Z�ej7d�dU��Z�ej7d�e�djfd�d��Z�ej7d�dV��Z�Gd�d�de��Z�Gd�dW�dWej�j��Z�Gd�d�d�e��Z�Gd�d*�d*e��Z�e�e�ej�d�Z�e�e�ej�d�Z�e�e�ej�d�Z�ej7d�fd�d�d.��Z�ej7d�d��Z�d�d�Z�d�d�Z�d�d�Z�d�d��Z�ej7d�d���Z�d�d��Z�d�Z�d�Z�e�ed���	rLd�e�Z�d�Z�e��dZd�d�ZÐd�d�ZĐdxZŐdyZƐd�d�Zǐd	dX�ZȐd
d_�ZɐdzZ�d�e�Z�d�e�Z�d�e�Z�ej�Zϐdd\�Z�G�d�d
��d
�Zѐd{�dd6�ZҐdd7�Z�G�dd/�d/�ZԐd�d�ZՐd�d�Z֐ddA�Zאdd8�Zؐd|�d�d�Z�daڐddB�Zېd�d�ZܐddE�Zݐd�d�Zސd�d �Zߐd!�d"�Z�d#�d$�Z�da�da�d%�d&�Z�d'�d(�Z�d)�d*�Z�d+d0�Z�d,�d-�Z�e݃�
o�ejd�k�
o�ejs�d.�Z�e�jdk	�oe�Z�e jje�d/�Z�d}�d0d1�Z�d1�d2�Z�d3�d4�Z�djZ�d5dQ�Z�d6dR�Z�d7dS�Z�ej7�d~�d9�d:��Z�d;dO�Z�ej7�d�d<dT��Z�ej7�d=dZ��Z�ej7�d>dY��Z��d?�d@�Z�e j�e�e�dA��dB�Z��dC�dD�Z��dE�dF�Z�G�dGdP�dPej�j��Z�G�dHd[�d[e���Zd�a�dId!��Z�dJd2��Zd�a�dK�dL��Z�dMd;��Z�dN�dO��Z�dPd"��Zf�dQ��dRd?��Z	dfff�dSd@��Z
G�dTd]�d]��Z�dU�dV��Z�dW�dX��Z
ff�dY�dZ��Zgf�d[da��Zd�a�d\dG��Zej7�d]�d^���Z�d_db��ZG�d`�da��da��ZG�db�dc��dc��Zej7�dd�de���ZdS(�z7Supporting definitions for the Python regression tests.ztest.supportz.support must be imported from the test package�N�)�get_test_runner�
PIPE_MAX_SIZE�verbose�
max_memuse�
use_resources�failfast�Error�
TestFailed�
TestDidNotRun�ResourceDenied�
import_module�import_fresh_module�CleanImport�unload�forget�record_original_stdout�get_original_stdout�captured_stdout�captured_stdin�captured_stderr�TESTFN�SAVEDCWD�unlink�rmtree�temp_cwd�findfile�create_empty_file�can_symlink�fs_is_case_insensitive�is_resource_enabled�requires�requires_freebsd_version�requires_linux_version�requires_mac_ver�requires_hashdigest�check_syntax_error�TransientResource�time_out�socket_peer_reset�ioerror_peer_reset�transient_internet�BasicTestRunner�run_unittest�run_doctest�skip_unless_symlink�
requires_gzip�requires_bz2�
requires_lzma�
bigmemtest�bigaddrspacetest�cpython_only�
get_attribute�requires_IEEE_754�skip_unless_xattr�
requires_zlib�anticipate_failure�load_package_tests�detect_api_mismatch�check__all__�requires_android_level�requires_multiprocessing_queue�	is_jython�
is_android�check_impl_detail�
unix_shell�setswitchinterval�HOST�IPV6_ENABLED�find_unused_port�	bind_port�open_urlresource�bind_unix_socket�
temp_umask�
reap_children�TestHandler�threading_setup�threading_cleanup�reap_threads�
start_threads�check_warnings�check_no_resource_warning�EnvironmentVarGuard�run_with_locale�	swap_item�	swap_attr�Matcher�set_memlimit�SuppressCrashReport�sortdict�run_with_tz�PGO�missing_compiler_executable�fd_countc@seZdZdZdS)r	z*Base class for regression test exceptions.N)�__name__�
__module__�__qualname__�__doc__�rdrd�-/usr/lib64/python3.6/test/support/__init__.pyr	|sc@seZdZdZdS)r
zTest failed.N)r`rarbrcrdrdrdrer
sc@seZdZdZdS)rzTest did not run any subtests.N)r`rarbrcrdrdrdrer�sc@seZdZdZdS)rz�Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not be enabled.  It is used to distinguish between expected
    and unexpected skips.
    N)r`rarbrcrdrdrdrer�sTccs8|r.tj��tjddt�dVWdQRXndVdS)z�Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect.
    �ignorez.+ (module|package)N)�warnings�catch_warnings�filterwarnings�DeprecationWarning)rfrdrdre�_ignore_deprecated_imports�s
rkF)�required_oncCsft|��Ty
tj|�Stk
rV}z&tjjt|��r8�tj	t
|���WYdd}~XnXWdQRXdS)acImport and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed. If a module is required on a platform but optional for
    others, set required_on to an iterable of platform prefixes which will be
    compared against sys.platform.
    N)rk�	importlibr
�ImportError�sys�platform�
startswith�tuple�unittest�SkipTest�str)�name�
deprecatedrl�msgrdrdrer
�s	

cCs^|tjkrt|�tj|=x>ttj�D]0}||ks@|j|d�r&tj|||<tj|=q&WdS)zyHelper function to save and remove a module from sys.modules

    Raise ImportError if the module can't be imported.
    �.N)ro�modules�
__import__�listrq)rv�orig_modules�modnamerdrdre�_save_and_remove_module�s
rcCs>d}ytj|||<Wntk
r.d}YnXdtj|<|S)z�Helper function to save and block a module in sys.modules

    Return True if the module was in sys.modules, False otherwise.
    TFN)rorz�KeyError)rvr}Zsavedrdrdre�_save_and_block_module�s

r�cCs|r
tjSdd�S)z�Decorator to mark a test that is known to be broken in some cases

       Any use of this decorator should have a comment identifying the
       associated tracker issue.
    cSs|S)Nrd)�frdrdre�<lambda>�sz$anticipate_failure.<locals>.<lambda>)rsZexpectedFailure)Z	conditionrdrdrer:�scCsF|dkrd}tjjtjjtjjt���}|j|||d�}|j|�|S)z�Generic load_tests implementation for simple test packages.

    Most packages can implement load_tests using this function as follows:

       def load_tests(*args):
           return load_package_tests(os.path.dirname(__file__), *args)
    Nztest*)Z	start_dirZ
top_level_dir�pattern)�os�path�dirname�__file__ZdiscoverZaddTests)Zpkg_dir�loaderZstandard_testsr�Ztop_dirZ
package_testsrdrdrer;�s
cCs�t|���i}g}t||�zfyHx|D]}t||�q&Wx |D]}t||�s>|j|�q>Wtj|�}Wntk
r~d}YnXWdx|j�D]\}	}
|
tj	|	<q�Wx|D]}tj	|=q�WX|SQRXdS)a�Import and return a module, deliberately bypassing sys.modules.

    This function imports and returns a fresh copy of the named Python module
    by removing the named module from sys.modules before doing the import.
    Note that unlike reload, the original module is not affected by
    this operation.

    *fresh* is an iterable of additional module names that are also removed
    from the sys.modules cache before doing the import.

    *blocked* is an iterable of module names that are replaced with None
    in the module cache during the import to ensure that attempts to import
    them raise ImportError.

    The named module and any modules named in the *fresh* and *blocked*
    parameters are saved before starting the import and then reinserted into
    sys.modules when the fresh import is complete.

    Module and package deprecation messages are suppressed during this import
    if *deprecated* is True.

    This function will raise ImportError if the named module cannot be
    imported.
    N)
rkrr��appendrmr
rn�itemsrorz)rvZfreshZblockedrwr}Znames_to_removeZ
fresh_nameZblocked_nameZfresh_moduleZ	orig_name�moduleZname_to_removerdrdrer�s$





cCs>yt||�}Wn&tk
r4tjd||f��YnX|SdS)z?Get an attribute, raising SkipTest if AttributeError is raised.zobject %r has no attribute %rN)�getattr�AttributeErrorrsrt)�objrvZ	attributerdrdrer6s
cCs|adS)N)�_original_stdout)�stdoutrdrdrer0scCs
tptjS)N)r�ror�rdrdrdrer4scCs&ytj|=Wntk
r YnXdS)N)rorzr�)rvrdrdrer7scGsny||�Stk
rh}zDtdkrHtd|jj|f�td|j|f�tj|tj�||�Sd}~XnXdS)N�z%s: %szre-run %s%r)	�OSErrorr�print�	__class__r`r��chmod�stat�S_IRWXU)r��func�args�errrdrdre�
_force_run=sr��wincCs�||�|r|}ntjj|�\}}|p(d}d}x<|dkrjtj|�}|rJ|n||ksVdStj|�|d9}q0Wtjd|tdd�dS)Nryg����MbP?g�?r�z)tests may fail, delete still pending for �)�
stacklevel)	r�r��split�listdir�time�sleeprg�warn�RuntimeWarning)r��pathname�waitallr�rv�timeout�Lrdrdre�_waitforHs



r�cCsttj|�dS)N)r�r�r)�filenamerdrdre�_unlinkisr�cCsttj|�dS)N)r�r��rmdir)r�rdrdre�_rmdirlsr�cs,�fdd��t�|dd�tdd�|�dS)Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}Wn<tk
rn}z td||ft	j
d�d}WYdd}~XnXtj|�r�t
�|dd�t|tj|�qt|tj|�qWdS)Nz-support.rmtree(): os.lstat(%r) failed with %s)�filerT)r�)r�r�r�r��join�lstat�st_moder�r�ro�
__stderr__r��S_ISDIRr�r�r)r�rv�fullname�mode�exc)�
_rmtree_innerrdrer�ps

z_rmtree.<locals>._rmtree_innerT)r�cSst|tj|�S)N)r�r�r�)�prdrdrer�sz_rmtree.<locals>.<lambda>)r�)r�rd)r�re�_rmtreeosr�c
Cs^yddl}Wntk
r Yn:X|jt|�d�}|jjj||t|��}|rZ|d|�S|S)Nrr�)�ctypesrnZcreate_unicode_buffer�len�windll�kernel32ZGetLongPathNameW)r�r��bufferZlengthrdrdre�	_longpath�s
r�csFytj|�dStk
r"YnX�fdd���|�tj|�dS)Nc
s�x~t|tj|�D]l}tjj||�}ytj|�j}Wntk
rJd}YnXtj	|�rn�|�t|tj
|�qt|tj|�qWdS)Nr)r�r�r�r�r�r�r�r�r�r�r�r)r�rvr�r�)r�rdrer��s

z_rmtree.<locals>._rmtree_inner)�shutilrr�r�r�)r�rd)r�rer��s
cCs|S)Nrd)r�rdrdrer��scCs*yt|�Wnttfk
r$YnXdS)N)r��FileNotFoundError�NotADirectoryError)r�rdrdrer�scCs&yt|�Wntk
r YnXdS)N)r�r�)r�rdrdrer��sr�cCs&yt|�Wntk
r YnXdS)N)r�r�)r�rdrdrer�scCsBtjj|�}tjjtjj|��}tjj||d�}tj||�|S)aMove a PEP 3147/488 pyc file to its legacy pyc location.

    :param source: The file system path to the source file.  The source file
        does not need to exist, however the PEP 3147/488 pyc file must exist.
    :return: The file system path to the legacy pyc file.
    �c)	rm�util�cache_from_sourcer�r�r��abspathr��rename)�sourceZpyc_fileZup_oneZ
legacy_pycrdrdre�make_legacy_pyc�s
r�cCs\t|�xNtjD]D}tjj||d�}t|d�x dD]}ttjj||d��q8WqWdS)	z�'Forget' a module was ever imported.

    This removes the module from sys.modules and deletes any PEP 3147/488 or
    legacy .pyc files.
    z.pyr��rr�)�optimizationN)r�rr�)	rror�r�r�rrmr�r�)r~r�r��optrdrdrer�s
cs�ttd�rtjSd}tjjd�r�ddl�ddl�d}d}G�fdd�d�j�}�j	j
}|j�}|sj�j��|�}�j
j�}|j||�j|��j|��j|��}|s��j��t|j|@�s�d}n�tjdk�rVdd	lm}	m�m}
m}dd
lm}|	j|d��}
|
j�dk�rd}nFG�fd
d�d|�}|�}|
|�}|
j|�dk�sR|
j|�dk�rVd}|�s�y.ddlm}|�}|j�|j �|j!�Wn\t"k
�r�}z>t#|�}t$|�dk�r�|dd�d}dj%t&|�j'|�}WYdd}~XnX|t_(|t_tjS)N�resultr�rrcs.eZdZd�jjfd�jjfd�jjfgZdS)z*_is_gui_available.<locals>.USEROBJECTFLAGSZfInheritZ	fReserved�dwFlagsN)r`rarb�wintypesZBOOL�DWORD�_fields_rd)r�rdre�USEROBJECTFLAGS�s

r�z,gui not available (WSF_VISIBLE flag not set)�darwin)�cdll�c_int�pointer�	Structure)�find_libraryZApplicationServicesz0gui tests cannot run without OS X window managercseZdZd�fd�fgZdS)z._is_gui_available.<locals>.ProcessSerialNumberZ
highLongOfPSNZlowLongOfPSNN)r`rarbr�rd)r�rdre�ProcessSerialNumbersr�z#cannot run without OS X gui process)�Tk�2z [...]zTk unavailable due to {}: {}))�hasattr�_is_gui_availabler�rorprqr�Zctypes.wintypesr�r�Zuser32ZGetProcessWindowStationZWinErrorr�r�ZGetUserObjectInformationWZbyrefZsizeof�boolr�r�r�r�Zctypes.utilr�ZLoadLibraryZCGMainDisplayIDZGetCurrentProcessZSetFrontProcessZtkinterr�Zwithdraw�updateZdestroy�	Exceptionrur��format�typer`�reason)r�Z	UOI_FLAGSZWSF_VISIBLEr�Zdll�hZuofZneeded�resr�r�r�r�Zapp_servicesr�ZpsnZpsn_pr��root�eZ
err_stringrd)r�r�rer��sh

r�cCstdkp|tkS)z�Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    N)r)�resourcerdrdrer $scCs>t|�s |dkrd|}t|��|dkr:t�r:ttj��dS)z@Raise ResourceDenied if the specified resource is not available.Nz"Use of the %r resource not enabled�gui)r rr�r�)r�rxrdrdrer!,scs��fdd�}|S)z�Decorator raising SkipTest if the OS is `sysname` and the version is less
    than `min_version`.

    For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
    the FreeBSD version is less than 7.2.
    cs$tj�����fdd��}�|_|S)Nc
s�tj��krztj�jdd�d}yttt|jd���}Wntk
rLYn.X|�krzdjtt	���}t
jd�||f���||�S)N�-rrryz(%s version %s or higher required, not %s)rp�system�releaser�rr�map�int�
ValueErrorr�rursrt)r��kw�version_txt�version�min_version_txt)r��min_version�sysnamerdre�wrapper=sz:_requires_unix_version.<locals>.decorator.<locals>.wrapper)�	functools�wrapsr�)r�r�)r�r�)r�re�	decorator<sz)_requires_unix_version.<locals>.decoratorrd)r�r�r�rd)r�r�re�_requires_unix_version5sr�cGs
td|�S)z�Decorator raising SkipTest if the OS is FreeBSD and the FreeBSD version is
    less than `min_version`.

    For example, @requires_freebsd_version(7, 2) raises SkipTest if the FreeBSD
    version is less than 7.2.
    ZFreeBSD)r�)r�rdrdrer"PscGs
td|�S)z�Decorator raising SkipTest if the OS is Linux and the Linux version is
    less than `min_version`.

    For example, @requires_linux_version(2, 6, 32) raises SkipTest if the Linux
    version is less than 2.6.32.
    ZLinux)r�)r�rdrdrer#Yscs�fdd�}|S)z�Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    cs"tj����fdd��}�|_|S)Ncsxtjdkrntj�d}yttt|jd���}Wntk
rBYn,X|�krndjtt	���}t
jd||f���||�S)Nr�rryz&Mac OS X %s or higher required, not %s)rorpZmac_verrrr�r�r�r�r�rursrt)r�r�r�r�r�)r�r�rdrer�js
z4requires_mac_ver.<locals>.decorator.<locals>.wrapper)r�r�r�)r�r�)r�)r�rer�isz#requires_mac_ver.<locals>.decoratorrd)r�r�rd)r�rer$bscs��fdd�}|S)a�Decorator raising SkipTest if a hashing algorithm is not available

    The hashing algorithm could be missing or blocked by a strict crypto
    policy.

    If 'openssl' is True, then the decorator checks that OpenSSL provides
    the algorithm. Otherwise the check falls back to built-in
    implementations.

    ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
    ValueError: unsupported hash type md4
    cstj�����fdd��}|S)NcsXy&�rtdk	rtj��n
tj��Wn&tk
rLtjd��d���YnX�||�S)Nz
hash digest 'z' is not available.)�_hashlib�new�hashlibr�rsrt)r��kwargs)�
digestnamer��opensslrdrer��sz7requires_hashdigest.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)rr)r�rer��sz&requires_hashdigest.<locals>.decoratorrd)rrr�rd)rrrer%}s
z	127.0.0.1z::1cCs"tj||�}t|�}|j�~|S)a�
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    OSError will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.
    )�socketrH�close)�familyZsocktypeZtempsock�portrdrdrerG�s
8cCs�|jtjkr�|jtjkr�ttd�r>|jtjtj�dkr>t	d��ttd�r~y |jtjtj
�dkrft	d��Wntk
r|YnXttd�r�|jtjtj
d�|j|df�|j�d}|S)a%Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    �SO_REUSEADDRrzHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!�SO_REUSEPORTzHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!�SO_EXCLUSIVEADDRUSEr)rr�AF_INETr��SOCK_STREAMr�Z
getsockoptZ
SOL_SOCKETrr
rr�Z
setsockoptr�bindZgetsockname)�sock�hostrrdrdrerH�s


cCs:y|j|�Wn&tk
r4|j�tjd��YnXdS)zBBind a unix socket, raising SkipTest if PermissionError is raised.zcannot bind AF_UNIX socketsN)r�PermissionErrorrrsrt)rZaddrrdrdrerJs
cCsZtjrVd}z<y"tjtjtj�}|jtdf�dStk
rBYnXWd|rT|j�XdS)z+Check whether IPv6 is enabled on this host.NrTF)rZhas_ipv6ZAF_INET6r
r�HOSTv6r�r)rrdrdre�_is_ipv6_enableds

rcstj���fdd��}|S)z5Skip the test on TLS certificate validation failures.csNy�||�Wn:tk
rH}zdt|�kr6tjd���WYdd}~XnXdS)NZCERTIFICATE_VERIFY_FAILEDz.system does not contain necessary certificates)�IOErrorrursrt)r�r�r�)r�rdre�decs
z&system_must_validate_cert.<locals>.dec)r�r�)r�rrd)r�re�system_must_validate_certs	rr�i�ZdoubleZIEEEztest requires IEEE 754 doublesz
requires zlibz
requires gzipzrequires bz2z
requires lzma�java�ANDROID_API_LEVEL�win32z/system/bin/shz/bin/shz$testz@testz	{}_{}_tmp�æ�İ�Ł�φ�К�א�،�ت�ก� �€u-àòɘŁğr�ZNFD�ntr�u-共Ł♡ͣ�ztWARNING: The filename %r CAN be encoded by the filesystem encoding (%s). Unicode filename tests may not be effective��s-��surrogateescape��w����������r�ccs�d}|dkr&tj�}d}tjj|�}nBytj|�d}Wn.tk
rf|sN�tjd|t	dd�YnX|rttj
�}z
|VWd|r�|tj
�kr�t|�XdS)a�Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    FNTz+tests may fail, unable to create temp dir: �)r�)�tempfile�mkdtempr�r��realpath�mkdirr�rgr�r��getpidr)r��quietZdir_created�pidrdrdre�temp_dir�s&


r2ccsftj�}ytj|�Wn.tk
rD|s,�tjd|tdd�YnXztj�VWdtj|�XdS)agReturn a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    z)tests may fail, unable to change CWD to: r*)r�N)r��getcwd�chdirr�rgr�r�)r�r0Z	saved_dirrdrdre�
change_cwd	s

r5�tempcwdccs:t||d��$}t||d��}|VWdQRXWdQRXdS)a�
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    )r�r0)r0N)r2r5)rvr0Z	temp_pathZcwd_dirrdrdrer$s�umaskccs&tj|�}z
dVWdtj|�XdS)z8Context manager that temporarily sets the process umask.N)r�r7)r7ZoldmaskrdrdrerK8s

�datacCsbtjj|�r|S|dk	r&tjj||�}tgtj}x*|D]"}tjj||�}tjj|�r8|Sq8W|S)a[Try to find a file on sys.path or in the test directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path).

    Setting *subdir* indicates a relative path to use to find the file
    rather than looking directly in the path directories.
    N)r�r��isabsr��
TEST_HOME_DIRro�exists)r�Zsubdirr�Zdn�fnrdrdrerIs
cCs(tj|tjtjBtjB�}tj|�dS)z>Create an empty file. If the file already exists, truncate it.N)r��open�O_WRONLY�O_CREAT�O_TRUNCr)r��fdrdrdrer[scCs,t|j��}dd�|D�}dj|�}d|S)z%Like repr(dict), but in sorted order.cSsg|]}d|�qS)z%r: %rrd)�.0Zpairrdrdre�
<listcomp>cszsortdict.<locals>.<listcomp>z, z{%s})�sortedr�r�)�dictr�Z	reprpairsZ
withcommasrdrdrer[`s
cCs*ttd�}z|j�S|j�tt�XdS)z`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    �wbN)r=r�filenorr)r�rdrdre�make_bad_fdgs

rH)�lineno�offsetcCsp|jt��}t|dd�WdQRX|j}|j|j�|dk	rJ|j|j|�|j|j�|dk	rl|j|j|�dS)Nz
<test string>�exec)�assertRaises�SyntaxError�compileZ	exceptionZassertIsNotNonerI�assertEqualrJ)�testcaseZ	statementrIrJ�cmr�rdrdrer&sscsVddl}ddl}�jdd��|jj|�djd�d}tjjt	|�}���fdd�}tjj
|�r|||�}|dk	rt|St|�td�t
r�td	|t�d
�|jj�}tr�|jjd�|j|d
d�}tr�|jjd�dkr�tj|d�}zBt|d��.}	|j�}
x|
�r|	j|
�|j�}
�q�WWdQRXWd|j�X||�}|dk	�rF|Std|��dS)Nr�checkr��/rcs>t|f����}�dkr|S�|�r2|jd�|S|j�dS)Nr)r=�seekr)r<r�)r�rRr�rdre�check_valid_file�s
z*open_urlresource.<locals>.check_valid_fileZurlfetchz	fetching %s ...)r��Accept-Encoding�gzip�)r�zContent-Encoding)ZfileobjrFzinvalid resource %r���)rVrW)Zurllib.requestZurllib.parse�pop�parseZurlparser�r�r�r��
TEST_DATA_DIRr;rr!rr�rZrequestZbuild_openerrWZ
addheadersr�r=Zheaders�getZGzipFile�read�writerr
)Zurlr�r��urllibr�r<rUr��opener�out�srd)r�rRr�rerI~s<	



c@s4eZdZdZdd�Zdd�Zedd��Zdd	�Zd
S)�WarningsRecorderzyConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS)Nr)�	_warnings�_last)�selfZ
warnings_listrdrdre�__init__�szWarningsRecorder.__init__cCsDt|j�|jkr t|jd|�S|tjjkr0dStd||f��dS)Nrz%r has no attribute %rrY)r�rerfr�rg�WarningMessage�_WARNING_DETAILSr�)rg�attrrdrdre�__getattr__�s
zWarningsRecorder.__getattr__cCs|j|jd�S)N)rerf)rgrdrdrerg�szWarningsRecorder.warningscCst|j�|_dS)N)r�rerf)rgrdrdre�reset�szWarningsRecorder.resetN)	r`rarbrcrhrl�propertyrgrmrdrdrdrerd�s
rdc
cs
tjd�}|jjd�}|r"|j�tjdd�� }tjdjd�t	|�VWdQRXt
|�}g}xz|D]r\}}d}	xH|dd�D]8}|j}
tj
|t|
�tj�r�t|
j|�r�d}	|j|�q�W|	rf|rf|j||jf�qfW|r�td	|d
��|�rtd|d
��dS)z�Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    r�Z__warningregistry__T)�recordrg�alwaysNFzunhandled warning %srz)filter (%r, %s) did not catch any warning)ro�	_getframe�	f_globalsr]�clearrgrhrz�simplefilterrdr|�message�re�matchru�I�
issubclassr��remover�r`�AssertionError)�filtersr0�frame�registry�wZreraiseZmissingrx�cat�seenZwarningrdrdre�_filterwarnings�s0
r�cOs.|jd�}|s$dtff}|dkr$d}t||�S)a�Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    r0r�NT)r]�Warningr�)r|r�r0rdrdrerR�s

r�ccsHtjdd��&}tjd||d�dV|r.t�WdQRX|j|g�dS)a�Context manager to check that no warnings are emitted.

    This context manager enables a given warning within its scope
    and checks that no warnings are emitted even with that warning
    enabled.

    If force_gc is True, a garbage collection is attempted before checking
    for warnings. This may help to catch warnings emitted when objects
    are deleted, such as ResourceWarning.

    Other keyword arguments are passed to warnings.filterwarnings().
    T)rorp)ru�categoryN)rgrhri�
gc_collectrO)rPrur�Zforce_gc�warnsrdrdre�check_no_warningssr�ccsBtjdd�� }tjdtd�dVt�WdQRX|j|g�dS)a"Context manager to check that no ResourceWarning is emitted.

    Usage:

        with check_no_resource_warning(self):
            f = open(...)
            ...
            del f

    You must remove the object which may emit ResourceWarning before
    the end of the context manager.
    T)rorp)r�N)rgrhri�ResourceWarningr�rO)rPr�rdrdrerSs
c@s(eZdZdZdd�Zdd�Zdd�ZdS)	ra,Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsNtjj�|_x<|D]4}|tjkrtj|}|j|kr>tj|j=tj|=qWdS)N)rorz�copy�original_modulesr`)rgZmodule_namesZmodule_namer�rdrdrerh?s




zCleanImport.__init__cCs|S)Nrd)rgrdrdre�	__enter__LszCleanImport.__enter__cGstjj|j�dS)N)rorzr�r�)rg�
ignore_excrdrdre�__exit__OszCleanImport.__exit__N)r`rarbrcrhr�r�rdrdrdrer3s

c@sheZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�ZdS)rTz_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS)N)r��environ�_environ�_changed)rgrdrdrerhXszEnvironmentVarGuard.__init__cCs
|j|S)N)r�)rg�envvarrdrdre�__getitem__\szEnvironmentVarGuard.__getitem__cCs*||jkr|jj|�|j|<||j|<dS)N)r�r�r])rgr��valuerdrdre�__setitem___s
zEnvironmentVarGuard.__setitem__cCs2||jkr|jj|�|j|<||jkr.|j|=dS)N)r�r�r])rgr�rdrdre�__delitem__es

zEnvironmentVarGuard.__delitem__cCs
|jj�S)N)r��keys)rgrdrdrer�lszEnvironmentVarGuard.keyscCs
t|j�S)N)�iterr�)rgrdrdre�__iter__oszEnvironmentVarGuard.__iter__cCs
t|j�S)N)r�r�)rgrdrdre�__len__rszEnvironmentVarGuard.__len__cCs|||<dS)Nrd)rgr�r�rdrdre�setuszEnvironmentVarGuard.setcCs
||=dS)Nrd)rgr�rdrdre�unsetxszEnvironmentVarGuard.unsetcCs|S)Nrd)rgrdrdrer�{szEnvironmentVarGuard.__enter__cGsJx<|jj�D].\}}|dkr0||jkr:|j|=q||j|<qW|jt_dS)N)r�r�r�r�r�)rgr��k�vrdrdrer�~s

zEnvironmentVarGuard.__exit__N)r`rarbrcrhr�r�r�r�r�r�r�r�r�r�rdrdrdrerTSsc@s(eZdZdZdd�Zdd�Zdd�ZdS)	�
DirsOnSysPatha�Context manager to temporarily add directories to sys.path.

    This makes a copy of sys.path, appends any directories given
    as positional arguments, then reverts sys.path to the copied
    settings when the context ends.

    Note that *all* sys.path modifications in the body of the
    context manager, including replacement of the object,
    will be reverted at the end of the block.
    cGs(tjdd�|_tj|_tjj|�dS)N)ror��original_value�original_object�extend)rg�pathsrdrdrerh�szDirsOnSysPath.__init__cCs|S)Nrd)rgrdrdrer��szDirsOnSysPath.__enter__cGs|jt_|jtjdd�<dS)N)r�ror�r�)rgr�rdrdrer��szDirsOnSysPath.__exit__N)r`rarbrcrhr�r�rdrdrdrer��s
r�c@s*eZdZdZdd�Zdd�Zd	dd�ZdS)
r'z�Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS)N)r��attrs)rgr�r�rdrdrerh�szTransientResource.__init__cCs|S)Nrd)rgrdrdrer��szTransientResource.__enter__NcCsT|dk	rPt|j|�rPx:|jj�D]$\}}t||�s4Pt||�|kr Pq Wtd��dS)z�If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any).Nz%an optional resource is not available)ryr�r�r�r�r�r)rgZtype_r��	tracebackrkZ
attr_valuerdrdrer��s
zTransientResource.__exit__)NNN)r`rarbrcrhr�r�rdrdrdrer'�s)�errnog>@)r��errnosc	#spd!d"d#d$d%d&g}d(d*d,d.d/g}td|��|�g��sRdd�|D��dd�|D�����fdd�}tj�}z�y|dk	r�tj|�dVWn�tjk
�r�}z&tr�tjj	�j
dd��|�WYdd}~Xn�tk
�rZ}zpx^|j
}t|�d k�rt
|dt��r|d}n*t|�dk�r8t
|d t��r8|d }nP�q�W||��WYdd}~XnXWdtj|�XdS)0z�Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.�ECONNREFUSED�o�
ECONNRESET�h�EHOSTUNREACH�q�ENETUNREACH�e�	ETIMEDOUT�n�
EADDRNOTAVAIL�c�	EAI_AGAINr*�EAI_FAILr��
EAI_NONAMEr��
EAI_NODATA��
WSANO_DATA�*zResource %r is not availablecSsg|]\}}tt||��qSrd)r�r�)rBrv�numrdrdrerC�sz&transient_internet.<locals>.<listcomp>cSsg|]\}}tt||��qSrd)r�r)rBrvr�rdrdrerC�scs�t|dd�}t|tj�s�t|tj�r,|�ks�t|tjj�rTd|jkoNdkns�t|tjj	�r�d|j
ks�d|j
ks�d|j
ks�|�kr�ts�tj
j�jdd��|�dS)	Nr�i�iW�ConnectionRefusedError�TimeoutError�EOFErrorr�
)r��
isinstancerr�Zgaierrorr`�errorZ	HTTPError�codeZURLErrorr�rro�stderrr_r�)r��n)�captured_errnos�denied�
gai_errnosrdre�filter_error�s


z(transient_internet.<locals>.filter_errorNrr�r)r�r�)r�r�)r�r�)r�r�)r�r�)r�r����)r�r����)r�r����)r�r����)r�r�)r�r�)rrZgetdefaulttimeoutZsetdefaulttimeout�nntplibZNNTPTemporaryErrorrror�r_r�r�r�r�)	Z
resource_namer�r�Zdefault_errnosZdefault_gai_errnosr�Zold_timeoutr��ard)r�r�r�rer+�sP



c
csFddl}tt|�}tt||j��ztt|�VWdtt||�XdS)z�Return a context manager used by captured_stdout/stdin/stderr
    that temporarily replaces the sys stream *stream_name* with a StringIO.rN)�ior�ro�setattr�StringIO)Zstream_namer�Zorig_stdoutrdrdre�captured_outputs
r�cCstd�S)z�Capture the output of sys.stdout:

       with captured_stdout() as stdout:
           print("hello")
       self.assertEqual(stdout.getvalue(), "hello\n")
    r�)r�rdrdrdrerscCstd�S)z�Capture the output of sys.stderr:

       with captured_stderr() as stderr:
           print("hello", file=sys.stderr)
       self.assertEqual(stderr.getvalue(), "hello\n")
    r�)r�rdrdrdrer%scCstd�S)a	Capture the input to sys.stdin:

       with captured_stdin() as stdin:
           stdin.write('hello\n')
           stdin.seek(0)
           # call test code that consumes from sys.stdin
           captured = input()
       self.assertEqual(captured, "hello")
    �stdin)r�rdrdrdrer.s
cCs*tj�trtjd�tj�tj�dS)a�Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    g�������?N)�gcZcollectr@r�r�rdrdrdrer�;s


r�c
cs.tj�}tj�z
dVWd|r(tj�XdS)N)r��	isenabled�disable�enable)Zhave_gcrdrdre�
disable_gcKs
r�cCs:tjd�pd}d}x|j�D]}|jd�r|}qW|dkS)z,Find if Python was built with optimizations.�	PY_CFLAGSr�z-O�-O0�-Og)r�r�r�)�	sysconfig�get_config_varr�rq)ZcflagsZ	final_optr�rdrdre�python_is_optimizedVs
r�ZnPZ0n�gettotalrefcountZ2PZ0Pr�cCstjt|t�S)N)�struct�calcsize�_header�_align)�fmtrdrdre�calcobjsizegsr�cCstjt|t�S)N)r�r��_vheaderr�)r�rdrdre�calcvobjsizejsr���	cCspddl}tj|�}t|�tkr(|jt@sBt|�tkrLt|�jt@rL||j7}dt|�||f}|j|||�dS)Nrz&wrong size for %s: got %d, expected %d)	�	_testcapiro�	getsizeofr��	__flags__�_TPFLAGS_HEAPTYPE�_TPFLAGS_HAVE_GCZSIZEOF_PYGC_HEADrO)�test�o�sizer�r�rxrdrdre�check_sizeofqs

r�cs��fdd�}|S)Ncs$���fdd�}�j|_�j|_|S)Ncs�y ddl}t|��}|j|�}Wn(tk
r6�YnBd}}Yn0Xx,�D]$}y|j||�PWqPYqPXqPWz
�||�S|r�|r�|j||�XdS)Nr)�localer��	setlocaler�)r��kwdsr�r�Zorig_locale�loc)�catstrr��localesrdre�inner�s$



z1run_with_locale.<locals>.decorator.<locals>.inner)r`rc)r�r�)r�r�)r�rer��sz"run_with_locale.<locals>.decoratorrd)r�r�r�rd)r�r�rerU�scs�fdd�}|S)Ncs"��fdd�}�j|_�j|_|S)Ncs�y
tj}Wntk
r(tjd��YnXdtjkr@tjd}nd}�tjd<|�z
�||�S|dkrrtjd=n
|tjd<tj�XdS)Nztzset requiredZTZ)r��tzsetr�rsrtr�r�)r�r�r�Zorig_tz)r��tzrdrer��s





z-run_with_tz.<locals>.decorator.<locals>.inner)r`rc)r�r�)r�)r�rer��szrun_with_tz.<locals>.decoratorrd)r�r�rd)r�rer\�scCs�dttdtd�}tjd|tjtjB�}|dkr>td|f��tt|j	d��||j	d�j
��}|a|tkrrt}|t
dkr�td|f��|adS)Ni)r��m�g�tz(\d+(\.\d+)?) (K|M|G|T)b?$zInvalid memory limit %rrr*z$Memory limit %r too low to be useful)�_1M�_1Grvrw�
IGNORECASE�VERBOSEr�r��float�group�lower�real_max_memuse�MAX_Py_ssize_t�_2Gr)�limitZsizesr�ZmemlimitrdrdrerY�s$c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�_MemoryWatchdogz`An object which periodically watches the process' memory consumption
    and prints it out.
    cCsdjtj�d�|_d|_dS)Nz/proc/{pid}/statm)r1F)r�r�r/�procfile�started)rgrdrdrerh�sz_MemoryWatchdog.__init__cCs�yt|jd�}Wn<tk
rL}z tjdj|�t�tjj	�dSd}~XnXt
d�}tjtj
|g|tjd�|_|j�d|_dS)N�rz!/proc not available for stats: {}zmemory_watchdog.py)r�r�T)r=r
r�rgr�r�r�ror��flushr�
subprocess�Popen�
executableZDEVNULL�mem_watchdogrr)rgr�r�Zwatchdog_scriptrdrdre�start�s
z_MemoryWatchdog.startcCs|jr|jj�|jj�dS)N)rrZ	terminate�wait)rgrdrdre�stop�s
z_MemoryWatchdog.stopN)r`rarbrcrhrrrdrdrdrer	�sr	cs���fdd�}|S)atDecorator for bigmem tests.

    'size' is a requested size for the test (in arbitrary, test-interpreted
    units.) 'memuse' is the number of bytes per unit for the test, or a good
    estimate of it. For example, a test that needs two byte buffers, of 4 GiB
    each, could be decorated with @bigmemtest(size=_4G, memuse=2).

    The 'size' argument is normally passed to the decorated test method as an
    extra argument. If 'dry_run' is true, the value passed to the test method
    may be less than the requested value. If 'dry_run' is false, it means the
    test doesn't support dummy runs when -M is not specified.
    cs ���fdd����_��_�S)Nc
s��j}�j}tsd}n|}ts$�rFt||krFtjd||d��tr|tr|t�tdj||dd��t�}|j	�nd}z
�||�S|r�|j
�XdS)	Niz'not enough memory: %.1fG minimum neededir*z* ... expected peak memory use: {peak:.1f}G)Zpeaki@i@)r��memuserrsrtrr�r�r	rr)rgr�r�maxsizeZwatchdog)�dry_runr�r�rdrer�s*


z.bigmemtest.<locals>.decorator.<locals>.wrapper)r�r)r�)rrr�)r�r�rer�szbigmemtest.<locals>.decoratorrd)r�rrr�rd)rrr�rer3s
!cs�fdd�}|S)z0Decorator for tests that fill the address space.csDttkr8td
kr$tdkr$tjd��q@tjdtd��n�|�SdS)
Nr��?r�z-not enough memory: try a 32-bit build insteadz'not enough memory: %.1fG minimum neededir*ll����li@)rrrsrt)rg)r�rdrer�3sz!bigaddrspacetest.<locals>.wrapperrd)r�r�rd)r�rer41sc@seZdZdd�ZdS)r,cCstj�}||�|S)N)rsZ
TestResult)rgr�r�rdrdre�runDszBasicTestRunner.runN)r`rarbrrdrdrdrer,CscCs|S)Nrd)r�rdrdre�_idIsrcCs<|dkrt�rtjtj�St|�r(tStjdj|��SdS)Nr�zresource {0!r} is not enabled)r�rs�skipr�r rr�)r�rdrdre�requires_resourceLs
rcCs&trt|krtjd|tf�StSdS)Nz%s at Android API level %d)rA�_ANDROID_API_LEVELrsrr)�levelr�rdrdrer>TscCstdd�|�S)z9
    Decorator for tests only applicable on CPython.
    T)�cpython)�impl_detail)r�rdrdrer5[scKsVtf|�rtS|dkrLt|�\}}|r,d}nd}t|j��}|jdj|��}tj|�S)Nz*implementation detail not available on {0}z%implementation detail specific to {0}z or )	rBr�
_parse_guardsrDr�r�r�rsr)rx�guardsZ
guardnames�defaultrdrdrer!as
r!cCsTtdkr:ddl}y|j�daWntk
r8daYnXd}trF|Stj|�|�S)z8Skip decorator for tests that use multiprocessing.Queue.NrTFz6requires a functioning shared semaphore implementation)�_have_mp_queue�multiprocessingZQueuernrsr)r�r&rxrdrdrer?os
cCs*|sddidfSt|j��d}||fS)Nr TFr)r|�values)r#Zis_truerdrdrer"~sr"cKs t|�\}}|jtj�j�|�S)a5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    )r"r]rpZpython_implementationr)r#r$rdrdrerB�scs,ttd�s�Stj���fdd��}|SdS)zEDecorator to temporarily turn off tracing for the duration of a test.�gettracecs.tj�}ztjd��||�Stj|�XdS)N)ror(�settrace)r�r�Zoriginal_trace)r�rdrer��s


zno_tracing.<locals>.wrapperN)r�ror�r�)r�r�rd)r�re�
no_tracing�s
r*cCstt|��S)aDecorator for tests which involve reference counting.

    To start, the decorator does not run the test if is not run by CPython.
    After that, any trace function is unset during the test to prevent
    unexpected refcounts caused by the trace function.

    )r*r5)r�rdrdre�
refcount_test�sr+cCsRg}xB|jD]8}t|tj�r2t||�|j|�q||�r|j|�qW||_dS)z>Recursively filter test cases in a suite based on a predicate.N)Z_testsr�rs�	TestSuite�
_filter_suiter�)�suiteZpredZnewtestsr�rdrdrer-�s
r-cCs�ttjttdk	d�}|j|�}tdk	r4tj|j��|js>t	�|j
�s�t|j�dkrl|j
rl|jdd}n6t|j
�dkr�|jr�|j
dd}nd}ts�|d7}t|��dS)z2Run tests from a unittest.TestSuite-derived class.N)�	verbosityZcapture_outputrrzmultiple errors occurredz!; run in verbose mode for details)rror�r�junit_xml_listrr�Zget_xml_elementZtestsRunrZ
wasSuccessfulr��errorsZfailuresr
)r.Zrunnerr�r�rdrdre�
_run_suite�s"
r2cCstdkrdSt|j��SdS)NT)�_match_test_func�id)r�rdrdre�
match_test�sr5cCsd|kotjd|�S)Nryz[?*\[\]])rv�search)r�rdrdre�_is_full_match_test�sr7csr|tkrdS|sd}f}nHttt|��r4t|�j}n.djttj|��}t	j
|�j��fdd�}|}t|�a|a
dS)N�|cs$�|�rdStt�|jd���SdS)NTry)�anyr�r�)Ztest_id)�regex_matchrdre�match_test_regex�sz)set_match_tests.<locals>.match_test_regex)�_match_test_patterns�allr�r7r��__contains__r��fnmatch�	translatervrNrwrrr3)Zpatternsr�Zregexr;rd)r:re�set_match_tests�srAcGs�tjtjf}tj�}xh|D]`}t|t�rT|tjkrJ|jtjtj|��qzt	d��qt||�rj|j|�q|jtj
|��qWt|t�t
|�dS)z1Run tests from unittest.TestCase-derived classes.z)str arguments must be keys in sys.modulesN)rsr,ZTestCaser�rurorzZaddTestZ
findTestCasesr�Z	makeSuiter-r5r2)�classesZvalid_typesr.�clsrdrdrer-s





cCsdS)z,Just used to check if docstrings are enabledNrdrdrdrdre�_check_docstrings(srD�WITH_DOC_STRINGSztest requires docstringscCs`ddl}|dkrt}nd}|j|||d�\}}|rBtd||f��trXtd|j|f�||fS)aRun doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    rN)r�optionflagsz%d of %d doctests failedz,doctest (%s) ... %d tests with zero failures)�doctestrZtestmodr
r�r`)r�r/rFrGr�r�rdrdrer.9scCstjj�fS)N)rorzr�rdrdrdre�
modules_setupTsrHcCs:dd�tjj�D�}tjj�tjj|�tjj|�dS)NcSs"g|]\}}|jd�r||f�qS)z
encodings.)rq)rBr�r�rdrdrerC[sz#modules_cleanup.<locals>.<listcomp>)rorzr�rsr�)Z
oldmodulesZ	encodingsrdrdre�modules_cleanupWs
rIcCs"trtj�tjj�fSdffSdS)Nr)�_thread�_count�	threading�	_danglingr�rdrdrdrerNzscGsJtsdSd}x8t|�D],}tj�tjf}||kr2Ptjd�t�qWdS)N�dg{�G�z�?)rJ�rangerKrLrMr�r�r�)Zoriginal_valuesZ
_MAX_COUNT�countr'rdrdrerO�s
cs"ts�Stj���fdd��}|S)z�Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cst�}z�|�St|�XdS)N)rNrO)r��key)r�rdrer��szreap_threads.<locals>.decorator)rJr�r�)r�r�rd)r�rerP�s�N@ccs�tj�}z
dVWdtj�}||}xjtj�}||kr8Ptj�|kr|tj�|}d||�d|d�d|�d|�d�	}t|��tjd�t�q&WXdS)	aH
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use _thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the _thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the _thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    Nz!wait_threads() failed to cleanup z threads after z.1fz seconds (count: z
, old count: �)g{�G�z�?)rJrKr�Z	monotonicr{r�r�)r�Z	old_countZ
start_timeZdeadlinerPZdtrxrdrdre�wait_threads_exit�s
$
rTc
CsZttd�rVd}xFy2tj|tj�\}}|dkr.Ptd|tjd�WqPYqXqWdS)z�Use this function at the end of test_main() whenever sub-processes
    are started.  This will help ensure that no extra children (zombies)
    stick around to hog resources and create problems when looking
    for refleaks.
    �waitpidrrz2Warning -- reap_children() reaped child process %s)r�NrY)r�r�rU�WNOHANGr�ror�)Zany_processr1ZstatusrdrdrerL�s
ccs*t|�}g}zZy$x|D]}|j�|j|�qWWn*trVtdt|�t|�f��YnXdVWdz�|rt|�tj�}}xltdd�D]^}|d7}x$|D]}|jt	|tj�d��q�Wdd�|D�}|s�Ptr�tdt|�|f�q�WWdd	d�|D�}|�r"t
jtj
�td
t|���XXdS)Nz/Can't start %d threads, only %d threads startedrr�<g{�G�z�?cSsg|]}|j�r|�qSrd)�isAlive)rBr�rdrdrerC�sz!start_threads.<locals>.<listcomp>z7Unable to join %d threads during a period of %d minutescSsg|]}|j�r|�qSrd)rX)rBr�rdrdrerC�szUnable to join %d threads)r|rr�rr�r�r�rOr��max�faulthandlerZdump_tracebackror�r{)ZthreadsZunlockrr�ZendtimeZ	starttimer�rdrdrerQ�s>


c
csnt||�r<t||�}t|||�z
|VWdt|||�Xn.t|||�z
dVWdt||�rht||�XdS)a�Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        This will set obj.attr to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `attr` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N)r�r�r��delattr)r�rk�new_val�real_valrdrdrerW�s




ccsX||kr0||}|||<z
|VWd|||<Xn$|||<z
dVWd||krR||=XdS)a�Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    Nrd)r��itemr\r]rdrdrerV	s

cCstjdd|�j�}|S)z�Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs, \d+ blocks\]\r?\n?�)rv�sub�strip)r�rdrdre�strip_python_stderr8	srbZ	getcountsz-types are immortal if COUNT_ALLOCS is definedcCstj�S)znReturn a list of command-line arguments reproducing the current
    settings in sys.flags and sys.warnoptions.)rZ_args_from_interpreter_flagsrdrdrdre�args_from_interpreter_flagsE	srccCstj�S)zgReturn a list of command-line arguments reproducing the current
    optimization settings in sys.flags.)rZ"_optim_args_from_interpreter_flagsrdrdrdre�!optim_args_from_interpreter_flagsJ	srdc@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
rMcCstjjj|d�||_dS)Nr)�logging�handlers�BufferingHandlerrh�matcher)rgrhrdrdrerhT	szTestHandler.__init__cCsdS)NFrd)rgrdrdre�shouldFlush]	szTestHandler.shouldFlushcCs|j|�|jj|j�dS)N)r�r�r��__dict__)rgrordrdre�emit`	s
zTestHandler.emitcKs.d}x$|jD]}|jj|f|�rd}PqW|S)zW
        Look for a saved dict whose keys/values match the supplied arguments.
        FT)r�rh�matches)rgr�r��drdrdrerld	szTestHandler.matchesN)r`rarbrhrirkrlrdrdrdrerMS	s	c@s eZdZdZdd�Zdd�ZdS)	rXrxrucKs<d}x2|D]*}||}|j|�}|j|||�s
d}Pq
W|S)a.
        Try to match a single dict with the supplied arguments.

        Keys whose values are strings and which are in self._partial_matches
        will be checked for partial (i.e. substring) matches. You can extend
        this scheme to (for example) do regular expression matching, etc.
        TF)r]�match_value)rgrmr�r�r�r��dvrdrdrerls	s

zMatcher.matchescCsHt|�t|�krd}n.t|�tk	s,||jkr6||k}n|j|�dk}|S)zT
        Try to match a single stored value (dv) with a supplied value (v).
        Fr)r�ru�_partial_matches�find)rgr�ror�r�rdrdrern�	s
zMatcher.match_valueN)rxru)r`rarbrprlrnrdrdrdrerXo	sc
CsZtdk	rtStd}ytjt|�d}Wntttfk
rFd}YnXtj|�|a|S)NrTF)�_can_symlinkrr��symlinkr��NotImplementedErrorr�rz)Zsymlink_path�canrdrdrer�	s

cCs t�}d}|r|Stj|�|�S)z8Skip decorator for tests that require functional symlinkz*Requires functional symlink implementation)rrsr)r��okrxrdrdrer/�	scCs�tdk	rtSttd�sd}n�tj�}tj|d�\}}z�ttd���}y`tj|dd�tj|dd�tj|j	�dd�t
j�}tj
d	|�}|dkp�t|jd
��dk}Wntk
r�d}YnXWdQRXWdtt�t|�t|�X|a|S)N�setxattrF)�dirrFs	user.testr_strusted.foos42z
2.6.(\d{1,2})r�')�
_can_xattrr�r�r+r,Zmkstempr=rrwrGrpr�rvrwr�rr�rr�)ruZtmp_dirZtmp_fpZtmp_name�fpZkernel_versionr�rdrdre�	can_xattr�	s,

r|cCs t�}d}|r|Stj|�|�S)zDSkip decorator for tests that require functional extended attributesz(no non-broken extended attribute support)r|rsr)r�rvrxrdrdrer8�	scCs$tpt}d}|r|Stj|�|�S)z;Skip decorator for tests not run in (non-extended) PGO taskz#Not run for (non-extended) PGO task)r]�PGO_EXTENDEDrsr)r�rvrxrdrdre�skip_if_pgo_task�	s
r~cCs^tj|d��H}|j}|j�}||kr,|j�}ytjj||�Stk
rNdSXWdQRXdS)zKDetects if the file system for the specified directory is case-insensitive.)rxFN)	r+ZNamedTemporaryFilerv�upperrr�r��samefiler�)Z	directory�base�	base_pathZ	case_pathrdrdrer�	s)rfcCs>tt|��tt|��}|r(|t|�8}tdd�|D��}|S)aReturns the set of items in ref_api not in other_api, except for a
    defined list of items to be ignored in this check.

    By default this skips private attributes beginning with '_' but
    includes all magic methods, i.e. those starting and ending in '__'.
    css(|] }|jd�s|jd�r|VqdS)�_�__N)rq�endswith)rBr�rdrdre�	<genexpr>�	sz&detect_api_mismatch.<locals>.<genexpr>)r�rx)Zref_apiZ	other_apirfZ
missing_itemsrdrdrer<�	s
cCs�|dkr|jf}nt|t�r"|f}t|�}xbt|�D]V}|jd�s4||krLq4t||�}t|dd�|ks�t|d�r4t|tj	�r4|j
|�q4W|j|j|�dS)aAssert that the __all__ variable of 'module' contains all public names.

    The module's public names (its API) are detected automatically based on
    whether they match the public name convention and were defined in
    'module'.

    The 'name_of_module' argument can specify (as a string or tuple thereof)
    what module(s) an API could be defined in in order to be detected as a
    public API. One case for this is when 'module' imports part of its public
    API from other modules, possibly a C backend (like 'csv' and its '_csv').

    The 'extra' argument can be a set of names that wouldn't otherwise be
    automatically detected as "public", like objects without a proper
    '__module__' attribute. If provided, it will be added to the
    automatically detected ones.

    The 'blacklist' argument can be a set of names that must not be treated
    as part of the public API even though their names indicate otherwise.

    Usage:
        import bar
        import foo
        import unittest
        from test import support

        class MiscTestCase(unittest.TestCase):
            def test__all__(self):
                support.check__all__(self, foo)

        class OtherTestCase(unittest.TestCase):
            def test__all__(self):
                extra = {'BAR_CONST', 'FOO_CONST'}
                blacklist = {'baz'}  # Undocumented name.
                # bar imports part of its API from _bar.
                support.check__all__(self, bar, ('bar', '_bar'),
                                     extra=extra, blacklist=blacklist)

    Nr�ra)
r`r�rur�rxrqr�r��types�
ModuleType�addZassertCountEqual�__all__)Z	test_caser�Zname_of_moduleZextraZ	blacklistZexpectedrvr�rdrdrer=�	s)


c@s(eZdZdZdZdZdd�Zdd�ZdS)rZz�Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    Nc
Csrtjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
rlYnLXi|_
x�|j|j|jgD].}|j
||j�}|j||j�}||f|j
|<q�Wn�tdk	�r
y*tjtj�|_tjtjd|jdf�Wnttfk
�rYnXtjdk�rnddd	d
g}tj|tjtjd�}|�|j�d}	WdQRX|	j�dk�rntd
ddd�|S)z�On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        r�rNr�rr�z/usr/bin/defaultsr^zcom.apple.CrashReporterZ
DialogType)r�r�s	developerz:this test triggers the Crash Reporter, that is intentionalr�T)�endr
) rorprqr�r�r��_k32�SetErrorMode�	old_value�msvcrt�CrtSetReportModer�rn�	old_modes�CRT_WARN�	CRT_ERROR�
CRT_ASSERTZCRTDBG_MODE_FILE�CrtSetReportFileZCRTDBG_FILE_STDERRr�Z	getrlimit�RLIMIT_CORE�	setrlimitr�r�rr�PIPEZcommunicaterar�)
rgr�ZSEM_NOGPFAULTERRORBOXr��report_type�old_mode�old_file�cmd�procr�rdrdrer�2
sN




zSuppressCrashReport.__enter__cGs�|jdkrdStjjd�rl|jj|j�|jr�ddl}xj|jj�D]$\}\}}|j	||�|j
||�qBWn6tdk	r�ytjtj
|j�Wnttfk
r�YnXdS)zARestore Windows ErrorMode or core file behavior to initial value.Nr�r)r�rorprqr�r�r�r�r�r�r�r�r�r�r�r�)rgr�r�r�r�r�rdrdrer�s
s
zSuppressCrashReport.__exit__)r`rarbrcr�r�r�r�rdrdrdrerZ)
s
Acsrt���d�y�j��Wn$ttfk
r@t��d��YnXd�����fdd�}|j|�t��|�dS)z�Override 'object_to_patch'.'attr_name' with 'new_value'.

    Also, add a cleanup procedure to 'test_instance' to restore
    'object_to_patch' value for 'attr_name'.
    The 'attr_name' should be a valid attribute for 'object_to_patch'.

    FNTcs �rt����n
t���dS)N)r�r[rd)�
attr_is_local�	attr_name�object_to_patchr�rdre�cleanup�
szpatch.<locals>.cleanup)r�rjr�r�Z
addCleanupr�)Z
test_instancer�r�Z	new_valuer�rd)r�r�r�r�re�patch�
s


r�cCsFyddl}Wntk
r YnX|j�r4tjd��ddl}|j|�S)zi
    Run code in a subinterpreter. Raise unittest.SkipTest if the tracemalloc
    module is enabled.
    rNzUrun_in_subinterp() cannot be used if tracemalloc module is tracing memory allocations)�tracemallocrnZ
is_tracingrsrtr��run_in_subinterp)r�r�r�rdrdrer��
s
r�csHG��fdd�d|�}d�|||���|jtt��t�|j��dS)NcseZdZ��fdd�ZdS)z%check_free_after_iterating.<locals>.Acs*d�yt��Wntk
r$YnXdS)NT)�next�
StopIteration)rg)�done�itrdre�__del__�
s
z-check_free_after_iterating.<locals>.A.__del__N)r`rarbr�rd)r�r�rdre�A�
sr�F)rLr�r�r�Z
assertTrue)r�r�rCr�r�rd)r�r�re�check_free_after_iterating�
s	r�cCs|ddlm}m}m}|j�}|j|�xP|jD]F}|r@||kr@q.t||�}|rPn
|dkrZq.|j|d�dkr.|dSq.WdS)a<Check if the compiler components used to build the interpreter exist.

    Check for the existence of the compiler executables whose names are listed
    in 'cmd_names' or all the compiler executables when 'cmd_names' is empty
    and return the first missing executable or None when none is found
    missing.

    r)�	ccompilerr��spawnN)	Z	distutilsr�r�r�Znew_compilerZcustomize_compilerZexecutablesr�Zfind_executable)Z	cmd_namesr�r�r�Zcompilerrvr�rdrdrer^�
s	

cCs@d}tr6||kr6tdkr.tjddg�j�dkatr6|}tj|�S)Ng�h㈵��>Zgetpropzro.kernel.qemu�1)rA�_is_android_emulatorrZcheck_outputrarorD)ZintervalZminimum_intervalrdrdrerD�
sc
cs>tjj�}tj�}ztj�dVWd|r8tj|dd�XdS)NT)r�Zall_threads)ror�rGrZ�
is_enabledr�r�)rAr�rdrdre�disable_faulthandler�
s

r�c	/Cs�tjjd�r8ytjd�}t|�dStk
r6YnXd}ttd�rjytjd�}Wnt	k
rhYnXd}tjd	kr�yd
dl
}|jWntt
fk
r�Yn0Xi}x(|j|j|jfD]}|j|d
�||<q�Wzpd
}xft|�D]Z}ytj|�}Wn4t	k
�r(}z|jtjk�r�WYdd}~Xq�Xtj|�|d7}q�WWd|dk	�rzx*|j|j|jfD]}|j|||��q`WX|S)z/Count the number of open file descriptors.
    �linux�freebsdz
/proc/self/fdr��sysconf�SC_OPEN_MAXNrr)r�r�)rorprqr�r�r�r�r�r�r�r�r�r�rnr�r�r�rO�dupr�ZEBADFr)	�namesZMAXFDr�r�r�rPrAZfd2r�rdrdrer_	sP





c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�SaveSignalsz�
    Save an restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    cCsjddl}||_ttd|j��|_x>dD]6}yt||�}Wntk
rNw&YnX|jj|�q&Wi|_dS)Nrr�SIGKILL�SIGSTOP)r�r�)	�signalr|rO�NSIG�signalsr�r�rzrf)rgr�Zsigname�signumrdrdrerhMs
zSaveSignals.__init__cCs4x.|jD]$}|jj|�}|dkr"q||j|<qWdS)N)r�r��	getsignalrf)rgr��handlerrdrdre�saveZs
zSaveSignals.savecCs*x$|jj�D]\}}|jj||�qWdS)N)rfr�r�)rgr�r�rdrdre�restorefszSaveSignals.restoreN)r`rarbrcrhr�r�rdrdrdrer�Ds
r�c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�FakePathz.Simple implementing of the path protocol.
    cCs
||_dS)N)r�)rgr�rdrdrerhnszFakePath.__init__cCsd|j�d�S)Nz
<FakePath �>)r�)rgrdrdre�__repr__qszFakePath.__repr__cCs6t|jt�s$t|jt�r,t|jt�r,|j�n|jSdS)N)r�r��
BaseExceptionr�ry)rgrdrdre�
__fspath__ts
zFakePath.__fspath__N)r`rarbrcrhr�r�rdrdrdrer�ksr�ccs.tj�}ztj|�dVWdtj|�XdS)z>Temporarily change the integer string conversion length limit.N)ro�get_int_max_str_digits�set_int_max_str_digits)Z
max_digitsZcurrentrdrdre�adjust_int_max_str_digits|s


r�)T)F)F)N)Nii@i@i@ii)rrrrrrrrr r!r")r&r$r'r(r))NF)F)r6F)N)Fi@ii)T)N)Nr)rR)N(rcr`rn�collections.abc�collections�
contextlibZdatetimer�rZr?r�r�r�rm�importlib.utilr�Zlogging.handlersrer�r�rprvr�rr�r�rror�r+r�r�rsZurllib.errorr`rgZ
testresultrrJrLZmultiprocessing.processr&�zlibrW�bz2Zlzmar�r�r�r�r	r
rrtr�contextmanagerrkr
rr�r:r;rr6rrrrr0rr�rrrr�rqr�r�r�r�r�rr�rr�rr�r r!r�r"r#r$r%rErr	r
rGrHrJrrFrrZ
SOCK_MAX_SIZEZ
skipUnlessr�
__getformat__r7r9r0r1r2r@r�rrArCrvrr�r/ZFS_NONASCII�	character�fsdecode�fsencode�UnicodeErrorZTESTFN_UNICODEZunicodedata�	normalize�getfilesystemencodingZTESTFN_ENCODINGZTESTFN_UNENCODABLEZgetwindowsversion�encode�UnicodeEncodeErrorr��decode�UnicodeDecodeErrorZTESTFN_UNDECODABLEZTESTFN_NONASCIIr3rr]r}r2r5rr�rKr�r�r�r�ZTEST_SUPPORT_DIRr:r�r\rrr[rHr&rI�objectrdr�rRr�r�rSr�abc�MutableMappingrTr�r'r�r�r(r�r)r*r+r�rrrr�r�r�r�r�r�r�r�r�r�r�rUr\r�r�rZ_4GrrrYr	r3r4r,rrr>r5r!r%r?r"rBr*r+r-r2r3r<r5r7rAr-rDZMISSING_C_DOCSTRINGSZHAVE_DOCSTRINGSZrequires_docstringsr.rHrIZenvironment_alteredrNrOrPrTrLrQrWrVrbZskipIfZrequires_type_collectingrcrdrfrgrMrXrrrr/rzr|r8r~rr<r=rZr�r�r�r^r�rDr�r_r�r�r�rdrdrdre�<module>s�











2	
!

J			>%	


%2' 5M		



$
#
0







(




"
#
	"
:_";'PK�R�Z �~��support/script_helper.pynu�[���# Common utility functions used by various script execution tests
#  e.g. test_cmd_line, test_cmd_line_script and test_runpy

import sys
import os
import re
import os.path
import tempfile
import subprocess
import py_compile
import contextlib
import shutil
try:
    import zipfile
except ImportError:
    # If Python is build without Unicode support, importing _io will
    # fail, which, in turn, means that zipfile cannot be imported
    # Most of this module can then still be used.
    pass

from test.support import strip_python_stderr

# Executing the interpreter in a subprocess
def _assert_python(expected_success, *args, **env_vars):
    cmd_line = [sys.executable]
    if not env_vars:
        cmd_line.append('-E')
    cmd_line.extend(args)
    # Need to preserve the original environment, for in-place testing of
    # shared library builds.
    env = os.environ.copy()
    env.update(env_vars)
    p = subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                         env=env)
    try:
        out, err = p.communicate()
    finally:
        subprocess._cleanup()
        p.stdout.close()
        p.stderr.close()
    rc = p.returncode
    err =  strip_python_stderr(err)
    if (rc and expected_success) or (not rc and not expected_success):
        raise AssertionError(
            "Process return code is %d, "
            "stderr follows:\n%s" % (rc, err.decode('ascii', 'ignore')))
    return rc, out, err

def assert_python_ok(*args, **env_vars):
    """
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` is ok and return a (return code, stdout, stderr) tuple.
    """
    return _assert_python(True, *args, **env_vars)

def assert_python_failure(*args, **env_vars):
    """
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` fails and return a (return code, stdout, stderr) tuple.
    """
    return _assert_python(False, *args, **env_vars)

def python_exit_code(*args):
    cmd_line = [sys.executable, '-E']
    cmd_line.extend(args)
    with open(os.devnull, 'w') as devnull:
        return subprocess.call(cmd_line, stdout=devnull,
                                stderr=subprocess.STDOUT)

def spawn_python(*args, **kwargs):
    cmd_line = [sys.executable, '-E']
    cmd_line.extend(args)
    return subprocess.Popen(cmd_line, stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                            **kwargs)

def kill_python(p):
    p.stdin.close()
    data = p.stdout.read()
    p.stdout.close()
    # try to cleanup the child so we don't appear to leak when running
    # with regrtest -R.
    p.wait()
    subprocess._cleanup()
    return data

def run_python(*args, **kwargs):
    if __debug__:
        p = spawn_python(*args, **kwargs)
    else:
        p = spawn_python('-O', *args, **kwargs)
    stdout_data = kill_python(p)
    return p.wait(), stdout_data

# Script creation utilities
@contextlib.contextmanager
def temp_dir():
    dirname = tempfile.mkdtemp()
    dirname = os.path.realpath(dirname)
    try:
        yield dirname
    finally:
        shutil.rmtree(dirname)

def make_script(script_dir, script_basename, source):
    script_filename = script_basename+os.extsep+'py'
    script_name = os.path.join(script_dir, script_filename)
    script_file = open(script_name, 'w')
    script_file.write(source)
    script_file.close()
    return script_name

def compile_script(script_name):
    py_compile.compile(script_name, doraise=True)
    if __debug__:
        compiled_name = script_name + 'c'
    else:
        compiled_name = script_name + 'o'
    return compiled_name

def make_zip_script(zip_dir, zip_basename, script_name, name_in_zip=None):
    zip_filename = zip_basename+os.extsep+'zip'
    zip_name = os.path.join(zip_dir, zip_filename)
    zip_file = zipfile.ZipFile(zip_name, 'w')
    if name_in_zip is None:
        name_in_zip = os.path.basename(script_name)
    zip_file.write(script_name, name_in_zip)
    zip_file.close()
    #if test.test_support.verbose:
    #    zip_file = zipfile.ZipFile(zip_name, 'r')
    #    print 'Contents of %r:' % zip_name
    #    zip_file.printdir()
    #    zip_file.close()
    return zip_name, os.path.join(zip_name, name_in_zip)

def make_pkg(pkg_dir, init_source=''):
    os.mkdir(pkg_dir)
    make_script(pkg_dir, '__init__', init_source)

def make_zip_pkg(zip_dir, zip_basename, pkg_name, script_basename,
                 source, depth=1, compiled=False):
    unlink = []
    init_name = make_script(zip_dir, '__init__', '')
    unlink.append(init_name)
    init_basename = os.path.basename(init_name)
    script_name = make_script(zip_dir, script_basename, source)
    unlink.append(script_name)
    if compiled:
        init_name = compile_script(init_name)
        script_name = compile_script(script_name)
        unlink.extend((init_name, script_name))
    pkg_names = [os.sep.join([pkg_name]*i) for i in range(1, depth+1)]
    script_name_in_zip = os.path.join(pkg_names[-1], os.path.basename(script_name))
    zip_filename = zip_basename+os.extsep+'zip'
    zip_name = os.path.join(zip_dir, zip_filename)
    zip_file = zipfile.ZipFile(zip_name, 'w')
    for name in pkg_names:
        init_name_in_zip = os.path.join(name, init_basename)
        zip_file.write(init_name, init_name_in_zip)
    zip_file.write(script_name, script_name_in_zip)
    zip_file.close()
    for name in unlink:
        os.unlink(name)
    #if test.test_support.verbose:
    #    zip_file = zipfile.ZipFile(zip_name, 'r')
    #    print 'Contents of %r:' % zip_name
    #    zip_file.printdir()
    #    zip_file.close()
    return zip_name, os.path.join(zip_name, script_name_in_zip)
PK�R�Z����

support/testresult.pynu�[���'''Test runner and result class for the regression test suite.

'''

import functools
import io
import sys
import time
import traceback
import unittest

import xml.etree.ElementTree as ET

from datetime import datetime

class RegressionTestResult(unittest.TextTestResult):
    separator1 = '=' * 70 + '\n'
    separator2 = '-' * 70 + '\n'

    def __init__(self, stream, descriptions, verbosity):
        super().__init__(stream=stream, descriptions=descriptions, verbosity=0)
        self.buffer = True
        self.__suite = ET.Element('testsuite')
        self.__suite.set('start', datetime.utcnow().isoformat(' '))

        self.__e = None
        self.__start_time = None
        self.__results = []
        self.__verbose = bool(verbosity)

    @classmethod
    def __getId(cls, test):
        try:
            test_id = test.id
        except AttributeError:
            return str(test)
        try:
            return test_id()
        except TypeError:
            return str(test_id)
        return repr(test)

    def startTest(self, test):
        super().startTest(test)
        self.__e = e = ET.SubElement(self.__suite, 'testcase')
        self.__start_time = time.perf_counter()
        if self.__verbose:
            self.stream.write(f'{self.getDescription(test)} ... ')
            self.stream.flush()

    def _add_result(self, test, capture=False, **args):
        e = self.__e
        self.__e = None
        if e is None:
            return
        e.set('name', args.pop('name', self.__getId(test)))
        e.set('status', args.pop('status', 'run'))
        e.set('result', args.pop('result', 'completed'))
        if self.__start_time:
            e.set('time', f'{time.perf_counter() - self.__start_time:0.6f}')

        if capture:
            if self._stdout_buffer is not None:
                stdout = self._stdout_buffer.getvalue().rstrip()
                ET.SubElement(e, 'system-out').text = stdout
            if self._stderr_buffer is not None:
                stderr = self._stderr_buffer.getvalue().rstrip()
                ET.SubElement(e, 'system-err').text = stderr

        for k, v in args.items():
            if not k or not v:
                continue
            e2 = ET.SubElement(e, k)
            if hasattr(v, 'items'):
                for k2, v2 in v.items():
                    if k2:
                        e2.set(k2, str(v2))
                    else:
                        e2.text = str(v2)
            else:
                e2.text = str(v)

    def __write(self, c, word):
        if self.__verbose:
            self.stream.write(f'{word}\n')

    @classmethod
    def __makeErrorDict(cls, err_type, err_value, err_tb):
        if isinstance(err_type, type):
            if err_type.__module__ == 'builtins':
                typename = err_type.__name__
            else:
                typename = f'{err_type.__module__}.{err_type.__name__}'
        else:
            typename = repr(err_type)

        msg = traceback.format_exception(err_type, err_value, None)
        tb = traceback.format_exception(err_type, err_value, err_tb)

        return {
            'type': typename,
            'message': ''.join(msg),
            '': ''.join(tb),
        }

    def addError(self, test, err):
        self._add_result(test, True, error=self.__makeErrorDict(*err))
        super().addError(test, err)
        self.__write('E', 'ERROR')

    def addExpectedFailure(self, test, err):
        self._add_result(test, True, output=self.__makeErrorDict(*err))
        super().addExpectedFailure(test, err)
        self.__write('x', 'expected failure')

    def addFailure(self, test, err):
        self._add_result(test, True, failure=self.__makeErrorDict(*err))
        super().addFailure(test, err)
        self.__write('F', 'FAIL')

    def addSkip(self, test, reason):
        self._add_result(test, skipped=reason)
        super().addSkip(test, reason)
        self.__write('S', f'skipped {reason!r}')

    def addSuccess(self, test):
        self._add_result(test)
        super().addSuccess(test)
        self.__write('.', 'ok')

    def addUnexpectedSuccess(self, test):
        self._add_result(test, outcome='UNEXPECTED_SUCCESS')
        super().addUnexpectedSuccess(test)
        self.__write('u', 'unexpected success')

    def printErrors(self):
        if self.__verbose:
            self.stream.write('\n')
        self.printErrorList('ERROR', self.errors)
        self.printErrorList('FAIL', self.failures)

    def printErrorList(self, flavor, errors):
        for test, err in errors:
            self.stream.write(self.separator1)
            self.stream.write(f'{flavor}: {self.getDescription(test)}\n')
            self.stream.write(self.separator2)
            self.stream.write('%s\n' % err)

    def get_xml_element(self):
        e = self.__suite
        e.set('tests', str(self.testsRun))
        e.set('errors', str(len(self.errors)))
        e.set('failures', str(len(self.failures)))
        return e

class QuietRegressionTestRunner:
    def __init__(self, stream, buffer=False):
        self.result = RegressionTestResult(stream, None, 0)
        self.result.buffer = buffer

    def run(self, test):
        test(self.result)
        return self.result

def get_test_runner_class(verbosity, buffer=False):
    if verbosity:
        return functools.partial(unittest.TextTestRunner,
                                 resultclass=RegressionTestResult,
                                 buffer=buffer,
                                 verbosity=verbosity)
    return functools.partial(QuietRegressionTestRunner, buffer=buffer)

def get_test_runner(stream, verbosity, capture_output=False):
    return get_test_runner_class(verbosity, capture_output)(stream)

if __name__ == '__main__':
    class TestTests(unittest.TestCase):
        def test_pass(self):
            pass

        def test_pass_slow(self):
            time.sleep(1.0)

        def test_fail(self):
            print('stdout', file=sys.stdout)
            print('stderr', file=sys.stderr)
            self.fail('failure message')

        def test_error(self):
            print('stdout', file=sys.stdout)
            print('stderr', file=sys.stderr)
            raise RuntimeError('error message')

    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestTests))
    stream = io.StringIO()
    runner_cls = get_test_runner_class(sum(a == '-v' for a in sys.argv))
    runner = runner_cls(sys.stdout)
    result = runner.run(suite)
    print('Output:', stream.getvalue())
    print('XML: ', end='')
    for s in ET.tostringlist(result.get_xml_element()):
        print(s.decode(), end='')
    print()
PK�R�ZJ�[�test_support.pyonu�[����
zfc@s,ddlZddlZejejd<dS(i����Nstest.test_support(tsysttest.supportttesttsupporttmodules(((s)/usr/lib64/python2.7/test/test_support.pyt<module>sPK�R�ZӨq�OOtest_support.pynu�[���import sys
import test.support
sys.modules['test.test_support'] = test.support
PK�R�Z�A?�||__init__.pyonu�[����
zfc@sdS(N((((s%/usr/lib64/python2.7/test/__init__.pyt<module>tPK�R�Z�GKF��script_helper.pycnu�[����
zfc@sddlTdS(i����(t*N(ttest.support.script_helper(((s*/usr/lib64/python2.7/test/script_helper.pyt<module>tPK�R�Zg� 2))script_helper.pynu�[���from test.support.script_helper import *
PK�R�Z��O�aasupport/__init__.pyonu�[����
{fc=@s�
dZedkr!ed��nddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddlZWnek
r:dZnXddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d4d<d=d>d?d@g=ZdAZdefdB��YZdefdC��YZdefdD��YZdejfdE��YZ ej!e"dF��Z#e$dG�Z%dH�Z&dI�Z'd�d�e$dJ�Z(dK�Z)dLZ*dZ+dMa,dMa-e$Z.da/dN�Z0dO�Z1dP�Z2dQ�Z3e
jj4dR�r+e$dS�Z5dT�Z6dU�Z7dV�Z8nej9Z6ej:Z7dW�Z8dX�Z9dY�Z:dZ�Z;d[�Z<d\�Z=d]�Z>dd^�Z?d_�Z@d`ZAdaZBejCejDdb�ZEeAdc�ZFdd�ZGeG�ZHde�ZIdfZJdg�ZKd�ZLd�ZMe
jj4dk�ZNyeOe"ZPWneQk
r-e$ZPnXejRePdl�ZSdm�ZTdZUePrx�eVdn�eVdo�eVdp�eVdq�eVdr�eVds�eVdt�eVdu�eVdv�eVdw�eVdx�fD]XZWy7eWjXe
jY��jZe
jY��eWkr�e[�nWne[k
rq�XeWZUPq�Wnej\dkkr6dyZ]n�ej\dzkrNd{Z]n�d|Z]ePr�e^d}eO�rrd~Z_neOd~d�Z_e
jY�Z`eae
d��s�e
jb�d�d�kr�dZcq�edd��ZcyecjXd��Wneek
r�q�Xd�ecGHnd�jfe]ejg��Z]d�Zheji�Zjej!de$d���Zkej!e$d���Zlej!d�e$d���Zmejnjoejnjpeq��Zrejnjoer�Zsejnjtesd��Zudd��Zvd��Zwd��Zxd}ddd��Zydd��Zzd�e{fd���YZ|e$d��Z}ej!d���Z~ej!d���Zd&e{fd���YZ�d'ej�fd���YZ�d�e{fd���YZ�d*e{fd���YZ�ej!dAd�d���Z�ej!d���Z�d��Z�d��Z�d��Z�d��Z�d�Z�eae
d��r�d�e�Z�ne�d�Z�d��Z�d��Z�d�Z�d�Z�d��Z�d��Z�d��Z�d�Z�die�Z�d�e�Z�dhe�Z�e
j�Z�d��Z�d�e�d��Z�d�e�e"d��Z�d��Z�d0d�d���YZ�d��Z�d��Z�d��Z�dd��Z�d��Z�d��Z�d��Z�d��Z�da�da�d��Z�d��Z�d��Z�d��Z�e�d�e$�pW	e
jd�kpW	ej�d��Z�ejRe�d��Z�dd��Z�e$Z�d��Z�d��Z�d��Z�ej!d�d���Z�d��Z�ej!dd���Z�ej!d���Z�ej!d���Z�d��Z�ej�eae
d��d��Z�d��Z�d��Z�d�d��Z�ej!d���Z�d��Z�d@d�d���YZ�d��Z�d��Z�d�d�d���YZ�dS(�s7Supporting definitions for the Python regression tests.stest.supports3test.support must be imported from the test packagei����NtErrort
TestFailedt
TestDidNotRuntResourceDeniedt
import_moduletverboset
use_resourcest
max_memusetrecord_original_stdouttget_original_stdouttunloadtunlinktrmtreetforgettis_resource_enabledtrequirestrequires_mac_vertfind_unused_portt	bind_porttfcmpthave_unicodet	is_jythontTESTFNtHOSTtFUZZtSAVEDCWDttemp_cwdtfindfiletsortdicttcheck_syntax_errortopen_urlresourcetcheck_warningstcheck_py3k_warningstCleanImporttEnvironmentVarGuardtcaptured_outputtcaptured_stdouttTransientResourcettransient_internettrun_with_localetset_memlimitt
bigmemtesttbigaddrspacetesttBasicTestRunnertrun_unittesttrun_doctesttthreading_setuptthreading_cleanuptreap_threadst
start_threadstcpython_onlytcheck_impl_detailt
get_attributet
py3k_bytestimport_fresh_modulet
reap_childrentstrip_python_stderrtIPV6_ENABLEDtrun_with_tztSuppressCrashReportg>@cBseZdZRS(s*Base class for regression test exceptions.(t__name__t
__module__t__doc__(((s-/usr/lib64/python2.7/test/support/__init__.pyR4scBseZdZRS(sTest failed.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR7scBseZdZRS(sTest did not run any subtests.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR:scBseZdZRS(s�Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not been enabled.  It is used to distinguish between expected
    and unexpected skips.
    (R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR=sccs=|r4tj��tjddt�dVWdQXndVdS(s�Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect.tignores.+ (module|package)N(twarningstcatch_warningstfilterwarningstDeprecationWarning(R?((s-/usr/lib64/python2.7/test/support/__init__.pyt_ignore_deprecated_importsEs
c	CsSt|��Aytj|�SWn(tk
rH}tjt|���nXWdQXdS(s�Import and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed.N(RDt	importlibRtImportErrortunittesttSkipTesttstr(tnamet
deprecatedtmsg((s-/usr/lib64/python2.7/test/support/__init__.pyRTs

cCs�|tjkr&t|�tj|=nxTttj�D]C}||ks[|j|d�r6tj|||<tj|=q6q6WdS(swHelper function to save and remove a module from sys.modules

       Raise ImportError if the module can't be imported.t.N(tsystmodulest
__import__tlistt
startswith(RJtorig_modulestmodname((s-/usr/lib64/python2.7/test/support/__init__.pyt_save_and_remove_moduleas

cCsFt}ytj|||<Wntk
r4t}nXdtj|<|S(s�Helper function to save and block a module in sys.modules

       Return True if the module was in sys.modules, False otherwise.N(tTrueRNROtKeyErrortFalsetNone(RJRStsaved((s-/usr/lib64/python2.7/test/support/__init__.pyt_save_and_block_modulens


cCs�t|���i}g}t||�zyax|D]}t||�q3Wx-|D]%}t||�sQ|j|�qQqQWtj|�}Wntk
r�d}nXWdx'|j�D]\}	}
|
t	j
|	<q�Wx|D]}t	j
|=q�WX|SWdQXdS(sImports and returns a module, deliberately bypassing the sys.modules cache
    and importing a fresh copy of the module. Once the import is complete,
    the sys.modules cache is restored to its original state.

    Modules named in fresh are also imported anew if needed by the import.
    If one of these modules can't be imported, None is returned.

    Importing of modules named in blocked is prevented while the fresh import
    takes place.

    If deprecated is True, any module or package deprecation messages
    will be suppressed.N(RDRUR[tappendRERRFRYtitemsRNRO(RJtfreshtblockedRKRStnames_to_removet
fresh_nametblocked_nametfresh_modulet	orig_nametmoduletname_to_remove((s-/usr/lib64/python2.7/test/support/__init__.pyR6{s&





cCs�yt||�}Wn�tk
r�t|tj�rKd|j|f}n�t|tj�rsd|j|f}nit|tj�r�d|jj|f}n>t|t	�r�d|j|f}ndt	|�j|f}t
j|��nX|SdS(s?Get an attribute, raising SkipTest if AttributeError is raised.smodule %r has no attribute %rsclass %s has no attribute %rs%s instance has no attribute %rs"type object %r has no attribute %rs%r object has no attribute %rN(tgetattrtAttributeErrort
isinstancettypest
ModuleTypeR<t	ClassTypetInstanceTypet	__class__ttypeRGRH(tobjRJt	attributeRL((s-/usr/lib64/python2.7/test/support/__init__.pyR4�s
iicCs
|adS(N(t_original_stdout(tstdout((s-/usr/lib64/python2.7/test/support/__init__.pyR�scCs
tptjS(N(RrRNRs(((s-/usr/lib64/python2.7/test/support/__init__.pyR	�scCs&ytj|=Wntk
r!nXdS(N(RNRORW(RJ((s-/usr/lib64/python2.7/test/support/__init__.pyR
�s
cGsxy||�SWnctk
rs}tdkrVd|jj|fGHd|j|fGHntj|tj�||�SXdS(Nis%s: %ssre-run %s%r(tEnvironmentErrorRRnR<tostchmodtstattS_IRWXU(tpathtfunctargsterr((s-/usr/lib64/python2.7/test/support/__init__.pyt
_force_run�stwincCs�||�|r|}n$tjj|�\}}|p:d}d}xR|dkr�tj|�}|rm|n	||ks}dStj|�|d9}qFWtjd|tdd�dS(NRMg����MbP?g�?is)tests may fail, delete still pending for t
stackleveli(	RuRytsplittlistdirttimetsleepR@twarntRuntimeWarning(RztpathnametwaitalltdirnameRJttimeouttL((s-/usr/lib64/python2.7/test/support/__init__.pyt_waitfor�s
	

cCsttj|�dS(N(R�RuR(tfilename((s-/usr/lib64/python2.7/test/support/__init__.pyt_unlink�scCsttj|�dS(N(R�Rutrmdir(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt_rmdir�scs6�fd��t�|dt�td�|�dS(Ncs�x�t|tj|�D]i}tjj||�}tjj|�rlt�|dt�t|tj|�qt|tj	|�qWdS(NR�(
R}RuR�RytjointisdirR�RVR�R(RyRJtfullname(t
_rmtree_inner(s-/usr/lib64/python2.7/test/support/__init__.pyR�sR�cSst|tj|�S(N(R}RuR�(tp((s-/usr/lib64/python2.7/test/support/__init__.pyt<lambda>	t(R�RV(Ry((R�s-/usr/lib64/python2.7/test/support/__init__.pyt_rmtree�scsSytj|�dSWntk
r(nX�fd���|�tj|�dS(Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}Wntk
r`d}nXtj	|�r��|�t|tj
|�qt|tj|�qWdS(Ni(R}RuR�RyR�tlstattst_modeRtRwtS_ISDIRR�R(RyRJR�tmode(R�(s-/usr/lib64/python2.7/test/support/__init__.pyR�s


(tshutilRRtRuR�(Ry((R�s-/usr/lib64/python2.7/test/support/__init__.pyR�s


cCsIyt|�Wn4tk
rD}|jtjtjfkrE�qEnXdS(N(R�tOSErrorterrnotENOENTtENOTDIR(R�texc((s-/usr/lib64/python2.7/test/support/__init__.pyR$s
cCs@yt|�Wn+tk
r;}|jtjkr<�q<nXdS(N(R�R�R�R�(R�terror((s-/usr/lib64/python2.7/test/support/__init__.pyR�+s
cCsIyt|�Wn4tk
rD}|jtjtjfkrE�qEnXdS(N(R�R�R�R�tESRCH(Ryte((s-/usr/lib64/python2.7/test/support/__init__.pyR3s
cCsjt|�xYtjD]N}ttjj||tjd��ttjj||tjd��qWdS(sm"Forget" a module was ever imported by removing it from sys.modules and
    deleting any .pyc and .pyo files.tpyctpyoN(R
RNRyRRuR�textsep(RTR�((s-/usr/lib64/python2.7/test/support/__init__.pyR
;s
$cs�ttd�rtjSd}tjjd�r ddl�ddl�d}d}d�j	f�fd��Y}�j
j}|j�}|s��j
��n|�}�jj�}|j||�j|��j|��j|��}|s�j
��nt|j|@�s�d}q�n�tjdkr�dd	lm}	m�m}
m	}dd
lm}|	j|d��}
|
j�dkr�d
}q�d|f�fd��Y}|�}|
|�}|
j|�dks�|
j|�dkr�d}q�n|s�y;ddlm}|�}|j �|j!�|j"�Wq�t#k
r�}t$|�}t%|�dkrz|d d}ndj&t'|�j(|�}q�Xn|t_)|t_tjS(NtresultR~i����itUSEROBJECTFLAGScs;eZd�jjfd�jjfd�jjfgZRS(tfInheritt	fReservedtdwFlags(R<R=twintypestBOOLtDWORDt_fields_((tctypes(s-/usr/lib64/python2.7/test/support/__init__.pyR�Rss,gui not available (WSF_VISIBLE flag not set)tdarwin(tcdlltc_inttpointert	Structure(tfind_librarytApplicationServicesis0gui tests cannot run without OS X window managertProcessSerialNumbercs eZd�fd�fgZRS(t
highLongOfPSNtlowLongOfPSN(R<R=R�((R�(s-/usr/lib64/python2.7/test/support/__init__.pyR�ts	s#cannot run without OS X gui process(tTki2s [...]sTk unavailable due to {}: {}(*thasattrt_is_gui_availableR�RYRNtplatformRRR�tctypes.wintypesR�twindlltuser32tGetProcessWindowStationtWinErrorR�R�tGetUserObjectInformationWtbyreftsizeoftboolR�R�R�R�tctypes.utilR�tLoadLibrarytCGMainDisplayIDtGetCurrentProcesstSetFrontProcesstTkinterR�twithdrawtupdatetdestroyt	ExceptionRItlentformatRoR<treason(R�t	UOI_FLAGStWSF_VISIBLER�tdllthtuoftneededtresR�R�R�R�tapp_servicesR�tpsntpsn_pR�trootR�t
err_string((R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR�Gsh		"			

	
cCstdkp|tkS(s�Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    N(RRY(tresource((s-/usr/lib64/python2.7/test/support/__init__.pyR�scCs`t|�s4|dkr%d|}nt|��n|dkr\t�r\ttj��ndS(s@Raise ResourceDenied if the specified resource is not available.s$Use of the `%s' resource not enabledtguiN(RRYRR�R�(R�RL((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
cs�fd�}|S(s�Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    cs.tj����fd��}�|_|S(Ncs�tjdkr�tj�d}y"ttt|jd���}Wntk
rTq�X|�kr�djtt	���}t
jd||f��q�n�||�S(NR�iRMs&Mac OS X %s or higher required, not %s(RNR�tmac_verttupletmaptintR�t
ValueErrorR�RIRGRH(R{tkwtversion_txttversiontmin_version_txt(Rztmin_version(s-/usr/lib64/python2.7/test/support/__init__.pytwrapper�s"
(t	functoolstwrapsR�(RzR�(R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyt	decorator�s!	((R�R�((R�s-/usr/lib64/python2.7/test/support/__init__.pyR�ss	127.0.0.1s::1cCs/tj||�}t|�}|j�~|S(s�
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    socket.error will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.(tsocketRtclose(tfamilytsocktypettempsocktport((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
6
cCs|jtjkr�|jtjkr�ttd�rc|jtjtj�dkrct	d��qcnttd�r�y1|jtjtj
�dkr�t	d��nWq�tk
r�q�Xnttd�r�|jtjtj
d�q�n|j|df�|j�d}|S(s%Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    tSO_REUSEADDRisHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!tSO_REUSEPORTsHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!tSO_EXCLUSIVEADDRUSEi(R�R�tAF_INETRotSOCK_STREAMR�t
getsockoptt
SOL_SOCKETR�RR�Rtt
setsockoptR�tbindtgetsockname(tsockthostR�((s-/usr/lib64/python2.7/test/support/__init__.pyRs$
cCs{tjrwd}zNy3tjtjtj�}|jtdf�tSWntjk
r[nXWd|rs|j	�nXnt
S(s+Check whether IPv6 is enabled on this host.iN(R�thas_ipv6RYtAF_INET6R�RtHOSTv6RVR�R�RX(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_ipv6_enabled$s	cs"tj���fd��}|S(s5Skip the test on TLS certificate validation failures.csRy�||�Wn:tk
rM}dt|�krGtjd��n�nXdS(NtCERTIFICATE_VERIFY_FAILEDs.system does not contain necessary certificates(tIOErrorRIRGRH(R{tkwargsR�(tf(s-/usr/lib64/python2.7/test/support/__init__.pytdec7s(R�R�(RR((Rs-/usr/lib64/python2.7/test/support/__init__.pytsystem_must_validate_cert5s	g���ư>cCs#t|t�st|t�rcy8t|�t|�t}t||�|krUdSWqqXn�t|�t|�krt|ttf�rxPttt	|�t	|���D]-}t
||||�}|dkr�|Sq�Wt	|�t	|�kt	|�t	|�kS||k||kS(Ni(RitfloattabsRRoR�RQtrangetminR�R(txtytfuzztitoutcome((s-/usr/lib64/python2.7/test/support/__init__.pyRDs-(,iiitjavasno unicode supportcCs
t|d�S(Nsunicode-escape(tunicode(ts((s-/usr/lib64/python2.7/test/support/__init__.pytumsi�i0iAi�ii�ii*ii�i� s$testtriscosttestfiles@testR�s@test-��slatin-1tgetwindowsversioniis'u"@test-\u5171\u6709\u3055\u308c\u308b"tLatin1sgWARNING: The filename %r CAN be encoded by the filesystem.  Unicode filename tests may not be effectives	{}_{}_tmpshttp://www.pythontest.netccsQt}|dkrEddl}|j�}t}tjj|�}n�tr�t	|t
�r�tjjr�y|jt
j�pd�}Wq�tk
r�|s�tjd��q�q�Xnytj|�t}Wn7tk
r|s��ntjd|tdd�nX|rtj�}nz	|VWd|rL|tj�krLt|�nXdS(s�Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    i����Ntasciis;unable to encode the cwd name with the filesystem encoding.s+tests may fail, unable to create temp dir: Ri(RXRYttempfiletmkdtempRVRuRytrealpathRRiRtsupports_unicode_filenamestencodeRNtgetfilesystemencodingtUnicodeEncodeErrorRGRHtmkdirR�R@R�R�tgetpidR(Rytquiettdir_createdR tpid((s-/usr/lib64/python2.7/test/support/__init__.pyttemp_dir�s6





	ccs{tj�}ytj|�Wn7tk
rV|s9�ntjd|tdd�nXztj�VWdtj|�XdS(sgReturn a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    s)tests may fail, unable to change CWD to: RiN(RutgetcwdtchdirR�R@R�R�(RyR)t	saved_dir((s-/usr/lib64/python2.7/test/support/__init__.pyt
change_cwds


ttempcwdc	csBtd|d|��'}t|d|��}|VWdQXWdQXdS(s�
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    RyR)N(R,R0(RJR)t	temp_pathtcwd_dir((s-/usr/lib64/python2.7/test/support/__init__.pyR&stdatacCs�tjj|�r|S|dk	r:tjj||�}ntgtj}x9|D]1}tjj||�}tjj|�rQ|SqQW|S(s�Try to find a file on sys.path and the working directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path).N(RuRytisabsRYR�t
TEST_HOME_DIRRNtexists(tfiletsubdirRytdntfn((s-/usr/lib64/python2.7/test/support/__init__.pyRAs
cCsJ|j�}|j�g|D]}d|^q}dj|�}d|S(s%Like repr(dict), but in sorted order.s%r: %rs, s{%s}(R]tsortR�(tdictR]tpairt	reprpairst
withcommas((s-/usr/lib64/python2.7/test/support/__init__.pyROs

cCs9ttd�}z|j�SWd|j�tt�XdS(s`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    twbN(topenRtfilenoR�R(R8((s-/usr/lib64/python2.7/test/support/__init__.pytmake_bad_fdWs

cCs||jt|��}t|dd�WdQX|j}|dk	rV|j|j|�n|dk	rx|j|j|�ndS(Ns
<test string>texec(tassertRaisesRegexptSyntaxErrortcompilet	exceptionRYtassertEqualtlinenotoffset(ttestcaset	statementterrtextRKRLtcmR|((s-/usr/lib64/python2.7/test/support/__init__.pyRcs	c
sSddl}ddl}|j|�djd�d}tjjt|�}�fd�}tjj|�r�||�}|dk	r�|St	|�nt
d�t�d|IJ|j|dd�}zNt
|d	��9}|j�}	x#|	r
|j|	�|j�}	q�WWdQXWd|j�X||�}|dk	r?|Std
|��dS(Ni����it/csGt|�}�dkr|S�|�r9|jd�|S|j�dS(Ni(RBRYtseekR�(R;R(tcheck(s-/usr/lib64/python2.7/test/support/__init__.pytcheck_valid_filess
turlfetchs	fetching %s ...R�iRAsinvalid resource "%s"(turlparseturllib2R�RuRyR�t
TEST_DATA_DIRR7RYRRR	turlopenRBtreadtwriteR�R(
turlRSRVRWR�R;RTRtoutR((RSs-/usr/lib64/python2.7/test/support/__init__.pyRls. 	

	
tWarningsRecordercBs8eZdZd�Zd�Zed��Zd�ZRS(syConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS(Ni(t	_warningst_last(tselft
warnings_list((s-/usr/lib64/python2.7/test/support/__init__.pyt__init__�s	cCs\t|j�|jkr,t|jd|�S|tjjkrBdStd||f��dS(Ni����s%r has no attribute %r(	R�R_R`RgR@tWarningMessaget_WARNING_DETAILSRYRh(Ratattr((s-/usr/lib64/python2.7/test/support/__init__.pyt__getattr__�s
cCs|j|jS(N(R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR@�scCst|j�|_dS(N(R�R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pytreset�s(R<R=R>RcRgtpropertyR@Rh(((s-/usr/lib64/python2.7/test/support/__init__.pyR^�s
		c
csptjd�}|jjd�}|r4|j�ntjdt��&}tjdj	d�t
|�VWdQXg|D]}|j^qu}g}x�|D]�\}}	t}
x[|D]R}t
|�}tj||tj�r�t|j|	�r�t}
|j|�q�q�W|
r�|r�|j||	jf�q�q�W|rOtd|d��n|rltd	|d��ndS(
s�Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    it__warningregistry__trecordR@talwaysNsunhandled warning %ris)filter (%r, %s) did not catch any warning(RNt	_getframet	f_globalstgettclearR@RARVROtsimplefilterR^tmessageRXRItretmatchtIt
issubclassRntremoveR\R<tAssertionError(
tfiltersR)tframetregistrytwtwarningtreraisetmissingRLtcattseenR�Rr((s-/usr/lib64/python2.7/test/support/__init__.pyt_filterwarnings�s0
cOsI|jd�}|s<dtff}|dkr<t}q<nt||�S(s�Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    R)R�N(RotWarningRYRVR�(RyR
R)((s-/usr/lib64/python2.7/test/support/__init__.pyR�scOs@tjr$|s*dtff}q*nd}t||jd��S(sjContext manager to silence py3k warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default False)

    Without argument, it defaults to:
        check_py3k_warnings(("", DeprecationWarning), quiet=False)
    R�R)((RNtpy3kwarningRCR�Ro(RyR
((s-/usr/lib64/python2.7/test/support/__init__.pyR �s
	cBs)eZdZd�Zd�Zd�ZRS(s,Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsotjj�|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS(N(RNROtcopytoriginal_modulesR<(Ratmodule_namestmodule_nameRe((s-/usr/lib64/python2.7/test/support/__init__.pyRcs

cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyt	__enter__scGstjj|j�dS(N(RNROR�R�(Rat
ignore_exc((s-/usr/lib64/python2.7/test/support/__init__.pyt__exit__s(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR!s
	
	cBs_eZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d	�ZRS(
s_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS(N(Rutenviront_environt_changed(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRc(scCs|j|S(N(R�(Ratenvvar((s-/usr/lib64/python2.7/test/support/__init__.pyt__getitem__,scCs<||jkr+|jj|�|j|<n||j|<dS(N(R�R�Ro(RaR�tvalue((s-/usr/lib64/python2.7/test/support/__init__.pyt__setitem__/scCsK||jkr+|jj|�|j|<n||jkrG|j|=ndS(N(R�R�Ro(RaR�((s-/usr/lib64/python2.7/test/support/__init__.pyt__delitem__5scCs
|jj�S(N(R�tkeys(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�<scCs|||<dS(N((RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytset?scCs||=dS(N((RaR�((s-/usr/lib64/python2.7/test/support/__init__.pytunsetBscCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�EscGshxU|jj�D]D\}}|dkrG||jkrT|j|=qTq||j|<qW|jt_dS(N(R�R]RYR�RuR�(RaR�tktv((s-/usr/lib64/python2.7/test/support/__init__.pyR�Hs(R<R=R>RcR�R�R�R�R�R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR"#s								t
DirsOnSysPathcBs)eZdZd�Zd�Zd�ZRS(s�Context manager to temporarily add directories to sys.path.

    This makes a copy of sys.path, appends any directories given
    as positional arguments, then reverts sys.path to the copied
    settings when the context ends.

    Note that *all* sys.path modifications in the body of the
    context manager, including replacement of the object,
    will be reverted at the end of the block.
    cGs-tj|_tj|_tjj|�dS(N(RNRytoriginal_valuetoriginal_objecttextend(Ratpaths((s-/usr/lib64/python2.7/test/support/__init__.pyRc^s
cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�cscGs|jt_|jtj(dS(N(R�RNRyR�(RaR�((s-/usr/lib64/python2.7/test/support/__init__.pyR�fs(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR�Rs
		cBs2eZdZd�Zd�Zdddd�ZRS(s�Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS(N(R�tattrs(RaR�R
((s-/usr/lib64/python2.7/test/support/__init__.pyRcps	cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�tscCs}|dk	ryt|j|�ryxX|jj�D]8\}}t||�sMPnt||�|kr.Pq.q.Wtd��ndS(s�If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any).s%an optional resource is not availableN(RYRvR�R�t	iteritemsR�RgR(Rattype_R�t	tracebackRft
attr_value((s-/usr/lib64/python2.7/test/support/__init__.pyR�wsN(R<R=R>RcR�RYR�(((s-/usr/lib64/python2.7/test/support/__init__.pyR%ks		c#s�dddd d!d"g}d#d$d%d&d'g}td|��|�g��s�g|D]\}}tt||�^qV�g|D]\}}tt||�^q��n���fd�}tj�}z�y%|dk	r�tj|�ndVWn�tk
r�}	xxtr}|	j	}
t
|
�dkrGt|
dt�rG|
d}	qt
|
�dkryt|
dt�ry|
d}	qPqW||	��nXWdtj|�XdS((s�Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.tECONNREFUSEDiot
ECONNRESETihtEHOSTUNREACHiqtENETUNREACHiet	ETIMEDOUTint
EADDRNOTAVAILict	EAI_AGAINi����tEAI_FAILi����t
EAI_NONAMEi����t
EAI_NODATAi����t
WSANO_DATAi�*sResource '%s' is not availablecst|dd�}t|tj�sNt|tj�rB|�ksN|�kr{tsrtjj	�j
dd�n��ndS(NR�is
(RgRYRiR�R�tgaierrorRRNtstderrR[R{(R|tn(tcaptured_errnostdeniedt
gai_errnos(s-/usr/lib64/python2.7/test/support/__init__.pytfilter_error�sNiii(R�io(R�ih(R�iq(R�ie(R�in(R�ic(R�i����(R�i����(R�i����(R�i����(R�i�*(RRgR�R�tgetdefaulttimeoutRYtsetdefaulttimeoutR	RVR{R�Ri(t
resource_nameR�terrnostdefault_errnostdefault_gai_errnosRJtnumR�told_timeoutR|ta((R�R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR&�sJ		(+				%
%

ccs[ddl}tt|�}tt||j��ztt|�VWdtt||�XdS(s�Return a context manager used by captured_stdout and captured_stdin
    that temporarily replaces the sys stream *stream_name* with a StringIO.i����N(tStringIORgRNtsetattr(tstream_nameR�torig_stdout((s-/usr/lib64/python2.7/test/support/__init__.pyR#�scCs
td�S(s�Capture the output of sys.stdout:

       with captured_stdout() as s:
           print "hello"
       self.assertEqual(s.getvalue(), "hello")
    Rs(R#(((s-/usr/lib64/python2.7/test/support/__init__.pyR$�scCs
td�S(NR�(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stderr�scCs
td�S(Ntstdin(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stdin�scCs8tj�tr tjd�ntj�tj�dS(s�Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    g�������?N(tgctcollectRR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyt
gc_collect�s



t2PtgettotalrefcounttPcCstjt|d�S(Nt0P(tstructtcalcsizet_header(tfmt((s-/usr/lib64/python2.7/test/support/__init__.pytcalcobjsize�scCstjt|d�S(NR�(R�R�t_vheader(R�((s-/usr/lib64/python2.7/test/support/__init__.pytcalcvobjsize�sii	cCs�ddl}tj|�}t|�tkr:|jt@s_t|�tkrot|�jt@ro||j7}ndt|�||f}|j|||�dS(Ni����s&wrong size for %s: got %d, expected %d(	t	_testcapiRNt	getsizeofRot	__flags__t_TPFLAGS_HEAPTYPEt_TPFLAGS_HAVE_GCtSIZEOF_PYGC_HEADRJ(ttesttotsizeR�R�RL((s-/usr/lib64/python2.7/test/support/__init__.pytcheck_sizeofs%cs��fd�}|S(Ncs1���fd�}�j|_�j|_|S(Ncs�y.ddl}t|��}|j|�}Wn$tk
rD�nAd}}n1Xx-�D]%}y|j||�PWq\q\Xq\Wz�||�SWd|r�|r�|j||�nXdS(Ni����(tlocaleRgt	setlocaleRhRY(R{tkwdsR�tcategorytorig_localetloc(tcatstrRztlocales(s-/usr/lib64/python2.7/test/support/__init__.pytinners$

(t	func_nameR>(RzR�(R�R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR�s((R�R�R�((R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR'scs�fd�}|S(Ncs.��fd�}�j|_�j|_|S(Ncs�y
tj}Wn tk
r/tjd��nXdtjkrOtjd}nd}�tjd<|�z�||�SWd|dkr�tjd=n
|tjd<tj�XdS(Nstzset requiredtTZ(R�ttzsetRhRGRHRuR�RY(R{R�R�torig_tz(Rzttz(s-/usr/lib64/python2.7/test/support/__init__.pyR�;s




(R<R>(RzR�(R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR�:s((R�R�((R�s-/usr/lib64/python2.7/test/support/__init__.pyR:9scCs�idd6td6td6dtd6}tjd|tjtjB�}|dkrgtd|f��ntt	|j
d��||j
d	�j��}|a|t
kr�t
}n|tdkr�td
|f��n|adS(NiR�tmtgtts(\d+(\.\d+)?) (K|M|G|T)b?$sInvalid memory limit %riis$Memory limit %r too low to be useful(t_1Mt_1GRsRtt
IGNORECASEtVERBOSERYR�R�Rtgrouptlowertreal_max_memusetMAX_Py_ssize_tt_2GR(tlimittsizesR�tmemlimit((s-/usr/lib64/python2.7/test/support/__init__.pyR(bs 2	ics���fd�}|S(sQDecorator for bigmem tests.

    'minsize' is the minimum useful size for the test (in arbitrary,
    test-interpreted units.) 'memuse' is the number of 'bytes per size' for
    the test, or a good estimate of it. 'overhead' specifies fixed overhead,
    independent of the testsize, and defaults to 5Mb.

    The decorator tries to guess a good value for 'size' and passes it to
    the decorated test function. If minsize * memuse is more than the
    allowed memory use (as defined by max_memuse), the test is skipped.
    Otherwise, minsize is adjusted upward to use up to max_memuse.
    cs7����fd�}�|_�|_�|_|S(Ncs�ts.d}|j|��dtk�n^tt���}|�krutrqtjjd�jf�ndSt	|dt��}�||�S(Niis)Skipping %s because of memory constraint
i2(
RtassertFalseR�R�RRNR�R[R<tmax(Ratmaxsize(Rtmemusetminsizetoverhead(s-/usr/lib64/python2.7/test/support/__init__.pyR��s"(R�R�R�(RR�(R�R�R�(Rs-/usr/lib64/python2.7/test/support/__init__.pyR��s
			((R�R�R�R�((R�R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR)ws
cs����fd�}|S(Ncs7����fd�}�|_�|_�|_|S(Ncsftsd}n�}ts"�rYt|�krYtrUtjjd�jf�ndS�||�S(Nis)Skipping %s because of memory constraint
(R�RRNR�R[R<(RaR�(tdry_runRR�R�(s-/usr/lib64/python2.7/test/support/__init__.pyR��s	
(R�R�R�(RR�(RR�R�R�(Rs-/usr/lib64/python2.7/test/support/__init__.pyR��s
			((R�R�R�RR�((RR�R�R�s-/usr/lib64/python2.7/test/support/__init__.pytprecisionbigmemtest�scs�fd�}|S(s0Decorator for tests that fill the address space.cs@ttkr2tr<tjjd�jf�q<n
�|�SdS(Ns)Skipping %s because of memory constraint
(RR�RRNR�R[R<(Ra(R(s-/usr/lib64/python2.7/test/support/__init__.pyR��s
((RR�((Rs-/usr/lib64/python2.7/test/support/__init__.pyR*�scBseZd�ZRS(cCstj�}||�|S(N(RGt
TestResult(RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytrun�s
(R<R=R(((s-/usr/lib64/python2.7/test/support/__init__.pyR+�scCs|S(N((Rp((s-/usr/lib64/python2.7/test/support/__init__.pyt_id�scCsP|dkr&t�r&tjtj�St|�r6tStjdj|��SdS(NR�sresource {0!r} is not enabled(R�RGtskipR�RRR�(R�((s-/usr/lib64/python2.7/test/support/__init__.pytrequires_resource�s
cCstdt�|�S(s9
    Decorator for tests only applicable on CPython.
    tcpython(timpl_detailRV(R�((s-/usr/lib64/python2.7/test/support/__init__.pyR2�scKs}t|�rtS|dkrpt|�\}}|r=d}nd}t|j��}|jdj|��}ntj	|�S(Ns*implementation detail not available on {0}s%implementation detail specific to {0}s or (
R3RRYt
_parse_guardstsortedR�R�R�RGR(RLtguardst
guardnamestdefault((s-/usr/lib64/python2.7/test/support/__init__.pyR�s	cCs2|sitd6tfS|j�d}||fS(NRi(RVRXtvalues(Rtis_true((s-/usr/lib64/python2.7/test/support/__init__.pyR	�scKs.t|�\}}|jtj�j�|�S(s5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    (R	RoR�tpython_implementationR�(RR
((s-/usr/lib64/python2.7/test/support/__init__.pyR3�scCsrg}x\|jD]Q}t|tj�rEt||�|j|�q||�r|j|�qqW||_dS(s>Recursively filter test cases in a suite based on a predicate.N(t_testsRiRGt	TestSuitet
_filter_suiteR\(tsuitetpredtnewtestsR�((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
cCs�tr'tjtjdddt�}n	t�}|j|�}|jr\|j	r\t
�n|j�s�t|j
�dkr�|jr�|j
dd}nLt|j�dkr�|j
r�|jdd}nd}ts�|d7}nt|��ndS(	s2Run tests from a unittest.TestSuite-derived class.t	verbosityitfailfastiismultiple errors occurreds!; run in verbose mode for detailsN(RRGtTextTestRunnerRNRsRR+RttestsRuntskippedRt
wasSuccessfulR�terrorstfailuresR(RtrunnerR�R|((s-/usr/lib64/python2.7/test/support/__init__.pyt
_run_suites 		
cCs$tdkrtSt|j��SdS(N(t_match_test_funcRYRVtid(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt
match_test#scCsd|kotjd|�S(NRMs[?*\[\]](Rstsearch(tpattern((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_full_match_test+scs�|tkrdS|s%d}d}nittt|��rLt|�j}nBdjttj	|��}t
j|�j��fd�}|}t
|�a|adS(Nt|cs0�|�rtStt�|jd���SdS(NRM(RVtanyR�R�(ttest_id(tregex_match(s-/usr/lib64/python2.7/test/support/__init__.pytmatch_test_regexJs((t_match_test_patternsRYtallR�R&R�t__contains__R�tfnmatcht	translateRsRHRtR�R!(tpatternsRztregexR+((R*s-/usr/lib64/python2.7/test/support/__init__.pytset_match_tests5s	cGs�tjtjf}tj�}x�|D]�}t|t�rx|tjkri|jtjtj|��q�t	d��q%t||�r�|j|�q%|jtj
|��q%Wt|t�t
|�dS(s1Run tests from unittest.TestCase-derived classes.s)str arguments must be keys in sys.modulesN(RGRtTestCaseRiRIRNROtaddTestt
findTestCasesR�t	makeSuiteRR#R (tclassestvalid_typesRtcls((s-/usr/lib64/python2.7/test/support/__init__.pyR,]s
 
Rtwin32tWITH_DOC_STRINGSstest requires docstringscCs�ddl}|dkr!t}nd}tj}t�t_z>|j|d|�\}}|rytd||f��nWd|t_Xtr�d|j|fGHn||fS(s
Run doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    test.support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    i����NRs%d of %d doctests faileds,doctest (%s) ... %d tests with zero failures(	tdoctestRYRRNRsR	ttestmodRR<(ReRR=tsave_stdoutRR�((s-/usr/lib64/python2.7/test/support/__init__.pyR-|s		
cCstrtj�fSdSdS(Ni(i(tthreadt_count(((s-/usr/lib64/python2.7/test/support/__init__.pyR.�s
cCsTts
dSd}x=t|�D]/}tj�}||kr?Pntjd�qWdS(Ni
g�������?(R@RRAR�R�(t
nb_threadst
_MAX_COUNTtcountR�((s-/usr/lib64/python2.7/test/support/__init__.pyR/�scs,ts
�Stj���fd��}|S(s�Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cs)t�}z�|�SWdt|�XdS(N(R.R/(R{tkey(Rz(s-/usr/lib64/python2.7/test/support/__init__.pyR��s	(R@R�R�(RzR�((Rzs-/usr/lib64/python2.7/test/support/__init__.pyR0�sgN@ccs�tj�}z	dVWdtj�}||}x�tr�tj�}||krSPntj�|kr�tj�|}d|||||f}t|��ntjd�t�q1WXdS(sE
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    NsYwait_threads() failed to cleanup %s threads after %.1f seconds (count: %s, old count: %s)g{�G�z�?(R@RAR�RVRxR�R�(R�t	old_countt
start_timetdeadlineRDtdtRL((s-/usr/lib64/python2.7/test/support/__init__.pytwait_threads_exit�s 	
	
cCscttd�r_d}xGtr[y/tj|tj�\}}|dkrLPnWqPqXqWndS(s�Use this function at the end of test_main() whenever sub-processes
    are started.  This will help ensure that no extra children (zombies)
    stick around to hog resources and create problems when looking
    for refleaks.
    twaitpidi����iN(R�RuRVRKtWNOHANG(tany_processR+tstatus((s-/usr/lib64/python2.7/test/support/__init__.pyR7�s		c	cs�t|�}g}zfy,x%|D]}|j�|j|�qWWn.trkdt|�t|�fGHn�nXdVWd|r�|�ntj�}}x�tdd�D]�}|d7}x.|D]&}|jt|tj�d��q�Wg|D]}|j	�r�|^q�}|sPntr�dt|�|fGHq�q�WXg|D]}|j	�rE|^qE}|r�t
dt|���ndS(Ns/Can't start %d threads, only %d threads startediii<g{�G�z�?s7Unable to join %d threads during a period of %d minutessUnable to join %d threads(RQtstartR\RR�R�RR�R�tisAliveRx(tthreadstunlocktstartedR�tendtimet	starttimeR�((s-/usr/lib64/python2.7/test/support/__init__.pyR1s:

	


$%%ccs�t||�rNt||�}t|||�z	|VWdt|||�Xn<t|||�z	dVWdt||�r�t||�nXdS(s�Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        This will set obj.attr to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `attr` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N(R�RgR�tdelattr(RpRftnew_valtreal_val((s-/usr/lib64/python2.7/test/support/__init__.pyt	swap_attr)s		ccsk||kr:||}|||<z	|VWd|||<Xn-|||<z	dVWd||krf||=nXdS(s�Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N((RptitemRWRX((s-/usr/lib64/python2.7/test/support/__init__.pyt	swap_itemHs

	
	cCs\y|j�SWnGtk
rWydjd�|D��SWqXtk
rSt|�SXnXdS(sZEmulate the py3k bytes() constructor.

    NOTE: This is only a best effort function.
    R�css|]}t|�VqdS(N(tchr(t.0R((s-/usr/lib64/python2.7/test/support/__init__.pys	<genexpr>rsN(ttobytesRhR�t	TypeErrortbytes(tb((s-/usr/lib64/python2.7/test/support/__init__.pyR5gs

t	getcountss-types are immortal if COUNT_ALLOCS is definedcCsddl}|j�S(sZReturn a list of command-line arguments reproducing the current
    settings in sys.flags.i����N(t
subprocesst_args_from_interpreter_flags(Rc((s-/usr/lib64/python2.7/test/support/__init__.pytargs_from_interpreter_flagsyscCstjdd|�j�}|S(s�Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs\]\r?\n?$R�(Rstsubtstrip(R�((s-/usr/lib64/python2.7/test/support/__init__.pyR8scsid|f��fd��Y}tg�|||���|jtt��t�|j�d�dS(NtAcseZ��fd�ZRS(cs0t�d<yt��Wntk
r+nXdS(Ni(RVtnextt
StopIteration(Ra(tdonetit(s-/usr/lib64/python2.7/test/support/__init__.pyt__del__�s


(R<R=Rm((RkRl(s-/usr/lib64/python2.7/test/support/__init__.pyRh�si(RXtassertRaisesRjRiR�t
assertTrue(R�titerR:R{Rh((RkRls-/usr/lib64/python2.7/test/support/__init__.pytcheck_free_after_iterating�s	ccs:tj�}tj�z	dVWd|r5tj�nXdS(N(R�t	isenabledtdisabletenable(thave_gc((s-/usr/lib64/python2.7/test/support/__init__.pyt
disable_gc�s
	cCsTtjd�pd}d}x,|j�D]}|jd�r(|}q(q(W|dkS(s,Find if Python was built with optimizations.t	PY_CFLAGSR�s-Os-O0s-Og(R�s-O0s-Og(t	sysconfigtget_config_varR�RR(tcflagst	final_opttopt((s-/usr/lib64/python2.7/test/support/__init__.pytpython_is_optimized�s
cBs,eZdZdZdZd�Zd�ZRS(s�Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    cCstjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
r�qXi|_
x|j|j|jgD]C}|j
||j�}|j||j�}||f|j
|<q�Wnyddl}Wntk
r%d}nX|dk	r�y9|j|j�|_|j|jd|jdf�Wq�ttfk
r�q�Xntjdkrddl}dd	d
dg}	|j|	d|jd
|j�}
|
j�d}|j�dkrtj j!d�tj j"�qn|S(s�On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        R~i����NiiiR�s/usr/bin/defaultsRZscom.apple.CrashReportert
DialogTypeRsR�t	developers:this test triggers the Crash Reporter, that is intentional(#RNR�RRR�R�tkernel32t_k32tSetErrorModet	old_valueR�tCrtSetReportModeRhRFt	old_modestCRT_WARNt	CRT_ERRORt
CRT_ASSERTtCRTDBG_MODE_FILEtCrtSetReportFiletCRTDBG_FILE_STDERRR�RYt	getrlimittRLIMIT_COREt	setrlimitR�R�RctPopentPIPEtcommunicateRgRsR[tflush(RaR�tSEM_NOGPFAULTERRORBOXR�treport_typetold_modetold_fileR�RctcmdtprocRs((s-/usr/lib64/python2.7/test/support/__init__.pyR��sV				

	cGs�|jdkrdStjjd�r�|jj|j�|jr�ddl}xF|jj	�D]2\}\}}|j
||�|j||�q]Wq�n@ddl}y|j
|j|j�Wnttfk
r�nXdS(sARestore Windows ErrorMode or core file behavior to initial value.NR~i����(R�RYRNR�RRR�R�R�R�R]R�R�R�R�R�R�R�(RaR�R�R�R�R�R�((s-/usr/lib64/python2.7/test/support/__init__.pyR�s	"N(R<R=R>RYR�R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR;�s
	GcCs*ddl}t��|j�WdQXdS(s�Deliberate crash of Python.

    Python can be killed by a segmentation fault (SIGSEGV), a bus error
    (SIGBUS), or a different error depending on the platform.

    Use SuppressCrashReport() to prevent a crash report from popping up.
    i����N(R�R;t
_read_null(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt
_crash_pythons	
c
Cs�tjjd�rdy!tjd�}t|�dSWqdtk
r`}|jtjkra�qaqdXnd}t	td�r�ytj
d�}Wq�tk
r�q�Xnd
}tjdkr+yd	d
l}|j
Wnttfk
r�q+Xi}x9|j|j|jfD]}|j
|d�||<qWnzyd}xlt|�D]^}ytj|�}Wn+tk
r�}	|	jtjkr��q�qAXtj|�|d7}qAWWd
|d
k	r�x7|j|j|jfD]}|j
|||�q�WnX|S(
s/Count the number of open file descriptors.
    tlinuxtfreebsds
/proc/self/fdiitsysconftSC_OPEN_MAXR;i����Ni(R�R�(RNR�RRRuR�R�R�R�R�R�R�RYtmsvcrtR�RhRFR�R�R�RtduptEBADFR�(
tnamesR�tMAXFDR�R�R�RDtfdtfd2R�((s-/usr/lib64/python2.7/test/support/__init__.pytfd_count#sR

	

	tSaveSignalscBs)eZdZd�Zd�Zd�ZRS(s�
    Save an restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    cCs�ddl}||_ttd|j��|_xHdD]@}yt||�}Wntk
rfq7nX|jj|�q7Wi|_dS(Ni����itSIGKILLtSIGSTOP(R�R�(	tsignalRQRtNSIGtsignalsRgRhRwthandlers(RaR�tsignametsignum((s-/usr/lib64/python2.7/test/support/__init__.pyRchs	

cCsIxB|jD]7}|jj|�}|dkr4q
n||j|<q
WdS(N(R�R�t	getsignalRYR�(RaR�thandler((s-/usr/lib64/python2.7/test/support/__init__.pytsaveus
cCs7x0|jj�D]\}}|jj||�qWdS(N(R�R]R�(RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytrestore�s(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR�_s	
	((ii@i@i@ii(i@ii(((((�R>R<RFt
contextlibR�R/R�R�R�RwRNRuR�R�R@RGREtUserDictRsR�R�RxRjR@RYt__all__t
SHORT_TIMEOUTR�RRRRHRtcontextmanagerRVRDRXRRUR[R6R4RRRR�RRrRR	R
R}RRR�R�R�R�RR�RR
R�RRRRRR�R�RRRR9R
RRt
PIPE_MAX_SIZEt
SOCK_MAX_SIZERRRt	NameErrort
skipUnlesstrequires_unicodeRtFS_NONASCIItunichrt	characterR$R%tdecodetUnicodeErrorRJRRitTESTFN_UNICODEtTESTFN_ENCODINGR�RtTESTFN_UNENCODABLEtevalR&R�R(t
TEST_HTTP_URLR-RR,R0RRyR�tabspatht__file__tTEST_SUPPORT_DIRR6R�RXRRRDRRtobjectR^R�RR R!t	DictMixinR"R�R%R&R#R$R�R�R�R�R�R�R�R�R�R�R'R:R�R�R�t_4GR�R�R(R)RR*R+RRR2RR	R3RR R!R,R#R&R3R,RytHAVE_DOCSTRINGStrequires_docstringsR-tenvironment_alteredR.R/R0RJR7R1RYR[R5tskipIftrequires_type_collectingReR8RqRvR}R;R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyt<module>s�

								
	
	
&					
!										J			<$			
	


												

				
	.			*' /D					

				$	"


		'				
	
					
	(			&
			#	 					
e		<PK�R�Z� �support/script_helper.pycnu�[����
{fc@s.ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl	Z	Wne
k
r�nXddlmZd�Z
d�Zd�Zd�Zd�Zd�Zd	�Zejd
��Zd�Zd�Zdd
�Zdd�Zded�ZdS(i����N(tstrip_python_stderrc	
Ostjg}|s"|jd�n|j|�tjj�}|j|�tj	|dtj
dtj
dtj
d|�}z|j�\}}Wdtj�|j
j�|jj�X|j}t|�}|r�|s�|r
|r
td||jdd�f��n|||fS(	Ns-Etstdintstdouttstderrtenvs-Process return code is %d, stderr follows:
%stasciitignore(tsyst
executabletappendtextendtostenvirontcopytupdatet
subprocesstPopentPIPEtcommunicatet_cleanupRtcloseRt
returncodeRtAssertionErrortdecode(	texpected_successtargstenv_varstcmd_lineRtptoutterrtrc((s2/usr/lib64/python2.7/test/support/script_helper.pyt_assert_pythons*

	

	cOstt||�S(s�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` is ok and return a (return code, stdout, stderr) tuple.
    (R tTrue(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_ok2scOstt||�S(s�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` fails and return a (return code, stdout, stderr) tuple.
    (R tFalse(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_failure9sc
GsWtjdg}|j|�ttjd��#}tj|d|dtj�SWdQXdS(Ns-EtwRR(	RRR
topenRtdevnullRtcalltSTDOUT(RRR'((s2/usr/lib64/python2.7/test/support/script_helper.pytpython_exit_code@s

c	OsGtjdg}|j|�tj|dtjdtjdtj|�S(Ns-ERRR(RRR
RRRR)(RtkwargsR((s2/usr/lib64/python2.7/test/support/script_helper.pytspawn_pythonGs

cCsA|jj�|jj�}|jj�|j�tj�|S(N(RRRtreadtwaitRR(Rtdata((s2/usr/lib64/python2.7/test/support/script_helper.pytkill_pythonNs



cOs+t||�}t|�}|j�|fS(N(R,R0R.(RR+Rtstdout_data((s2/usr/lib64/python2.7/test/support/script_helper.pyt
run_pythonXsccs<tj�}tjj|�}z	|VWdtj|�XdS(N(ttempfiletmkdtempRtpathtrealpathtshutiltrmtree(tdirname((s2/usr/lib64/python2.7/test/support/script_helper.pyttemp_diras
	cCsP|tjd}tjj||�}t|d�}|j|�|j�|S(NtpyR%(RtextsepR5tjoinR&twriteR(t
script_dirtscript_basenametsourcetscript_filenametscript_nametscript_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_scriptjs

cCs!tj|dt�|d}|S(Ntdoraisetc(t
py_compiletcompileR!(RCt
compiled_name((s2/usr/lib64/python2.7/test/support/script_helper.pytcompile_scriptrs
cCs�|tjd}tjj||�}tj|d�}|dkrYtjj|�}n|j||�|j	�|tjj||�fS(NtzipR%(
RR<R5R=tzipfiletZipFiletNonetbasenameR>R(tzip_dirtzip_basenameRCtname_in_ziptzip_filenametzip_nametzip_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_scriptzs
tcCs!tj|�t|d|�dS(Nt__init__(RtmkdirRE(tpkg_dirtinit_source((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_pkg�s
icCs�g}t|dd�}|j|�tjj|�}	t|||�}
|j|
�|r�t|�}t|
�}
|j||
f�ngtd|d�D]}tjj	|g|�^q�}tjj	|dtjj|
��}
|tj
d}tjj	||�}tj|d�}x3|D]+}tjj	||	�}|j
||�q'W|j
|
|
�|j�x|D]}tj|�qwW|tjj	||
�fS(NRYRXii����RLR%(RER	RR5RPRKR
trangetsepR=R<RMRNR>Rtunlink(RQRRtpkg_nameR@RAtdepthtcompiledR`t	init_namet
init_basenameRCtit	pkg_namestscript_name_in_zipRTRURVtnametinit_name_in_zip((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_pkg�s.

9%


(RRtretos.pathR3RRHt
contextlibR7RMtImportErrorttest.supportRR R"R$R*R,R0R2tcontextmanagerR:RERKRORWR]R#Rk(((s2/usr/lib64/python2.7/test/support/script_helper.pyt<module>s4
						
					PK�R�Z�&�=��support/__init__.pycnu�[����
{fc=@s�
dZedkr!ed��nddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddlZWnek
r:dZnXddddd	d
ddd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d4d<d=d>d?d@g=ZdAZdefdB��YZdefdC��YZdefdD��YZdejfdE��YZ ej!e"dF��Z#e$dG�Z%dH�Z&dI�Z'd�d�e$dJ�Z(dK�Z)dLZ*dZ+dMa,dMa-e$Z.da/dN�Z0dO�Z1dP�Z2dQ�Z3e
jj4dR�r+e$dS�Z5dT�Z6dU�Z7dV�Z8nej9Z6ej:Z7dW�Z8dX�Z9dY�Z:dZ�Z;d[�Z<d\�Z=d]�Z>dd^�Z?d_�Z@d`ZAdaZBejCejDdb�ZEeAdc�ZFdd�ZGeG�ZHde�ZIdfZJdg�ZKd�ZLd�ZMe
jj4dk�ZNyeOe"ZPWneQk
r-e$ZPnXejRePdl�ZSdm�ZTdZUePrx�eVdn�eVdo�eVdp�eVdq�eVdr�eVds�eVdt�eVdu�eVdv�eVdw�eVdx�fD]XZWy7eWjXe
jY��jZe
jY��eWkr�e[�nWne[k
rq�XeWZUPq�Wnej\dkkr6dyZ]n�ej\dzkrNd{Z]n�d|Z]ePr�e^d}eO�rrd~Z_neOd~d�Z_e
jY�Z`eae
d��s�e
jb�d�d�kr�dZcq�edd��ZcyecjXd��Wneek
r�q�Xd�ecGHnd�jfe]ejg��Z]d�Zheji�Zjej!de$d���Zkej!e$d���Zlej!d�e$d���Zmejnjoejnjpeq��Zrejnjoer�Zsejnjtesd��Zudd��Zvd��Zwd��Zxd}ddd��Zydd��Zzd�e{fd���YZ|e$d��Z}ej!d���Z~ej!d���Zd&e{fd���YZ�d'ej�fd���YZ�d�e{fd���YZ�d*e{fd���YZ�ej!dAd�d���Z�ej!d���Z�d��Z�d��Z�d��Z�d��Z�d�Z�eae
d��r�d�e�Z�ne�d�Z�d��Z�d��Z�d�Z�d�Z�d��Z�d��Z�d��Z�d�Z�die�Z�d�e�Z�dhe�Z�e
j�Z�d��Z�d�e�d��Z�d�e�e"d��Z�d��Z�d0d�d���YZ�d��Z�d��Z�d��Z�dd��Z�d��Z�d��Z�d��Z�d��Z�da�da�d��Z�d��Z�d��Z�d��Z�e�d�e$�pW	e
jd�kpW	ej�d��Z�ejRe�d��Z�dd��Z�e$Z�d��Z�d��Z�d��Z�ej!d�d���Z�d��Z�ej!dd���Z�ej!d���Z�ej!d���Z�d��Z�ej�eae
d��d��Z�d��Z�d��Z�d�d��Z�ej!d���Z�d��Z�d@d�d���YZ�d��Z�d��Z�d�d�d���YZ�dS(�s7Supporting definitions for the Python regression tests.stest.supports3test.support must be imported from the test packagei����NtErrort
TestFailedt
TestDidNotRuntResourceDeniedt
import_moduletverboset
use_resourcest
max_memusetrecord_original_stdouttget_original_stdouttunloadtunlinktrmtreetforgettis_resource_enabledtrequirestrequires_mac_vertfind_unused_portt	bind_porttfcmpthave_unicodet	is_jythontTESTFNtHOSTtFUZZtSAVEDCWDttemp_cwdtfindfiletsortdicttcheck_syntax_errortopen_urlresourcetcheck_warningstcheck_py3k_warningstCleanImporttEnvironmentVarGuardtcaptured_outputtcaptured_stdouttTransientResourcettransient_internettrun_with_localetset_memlimitt
bigmemtesttbigaddrspacetesttBasicTestRunnertrun_unittesttrun_doctesttthreading_setuptthreading_cleanuptreap_threadst
start_threadstcpython_onlytcheck_impl_detailt
get_attributet
py3k_bytestimport_fresh_modulet
reap_childrentstrip_python_stderrtIPV6_ENABLEDtrun_with_tztSuppressCrashReportg>@cBseZdZRS(s*Base class for regression test exceptions.(t__name__t
__module__t__doc__(((s-/usr/lib64/python2.7/test/support/__init__.pyR4scBseZdZRS(sTest failed.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR7scBseZdZRS(sTest did not run any subtests.(R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR:scBseZdZRS(s�Test skipped because it requested a disallowed resource.

    This is raised when a test calls requires() for a resource that
    has not been enabled.  It is used to distinguish between expected
    and unexpected skips.
    (R<R=R>(((s-/usr/lib64/python2.7/test/support/__init__.pyR=sccs=|r4tj��tjddt�dVWdQXndVdS(s�Context manager to suppress package and module deprecation
    warnings when importing them.

    If ignore is False, this context manager has no effect.tignores.+ (module|package)N(twarningstcatch_warningstfilterwarningstDeprecationWarning(R?((s-/usr/lib64/python2.7/test/support/__init__.pyt_ignore_deprecated_importsEs
c	CsSt|��Aytj|�SWn(tk
rH}tjt|���nXWdQXdS(s�Import and return the module to be tested, raising SkipTest if
    it is not available.

    If deprecated is True, any module or package deprecation messages
    will be suppressed.N(RDt	importlibRtImportErrortunittesttSkipTesttstr(tnamet
deprecatedtmsg((s-/usr/lib64/python2.7/test/support/__init__.pyRTs

cCs�|tjkr&t|�tj|=nxTttj�D]C}||ks[|j|d�r6tj|||<tj|=q6q6WdS(swHelper function to save and remove a module from sys.modules

       Raise ImportError if the module can't be imported.t.N(tsystmodulest
__import__tlistt
startswith(RJtorig_modulestmodname((s-/usr/lib64/python2.7/test/support/__init__.pyt_save_and_remove_moduleas

cCsFt}ytj|||<Wntk
r4t}nXdtj|<|S(s�Helper function to save and block a module in sys.modules

       Return True if the module was in sys.modules, False otherwise.N(tTrueRNROtKeyErrortFalsetNone(RJRStsaved((s-/usr/lib64/python2.7/test/support/__init__.pyt_save_and_block_modulens


cCs�t|���i}g}t||�zyax|D]}t||�q3Wx-|D]%}t||�sQ|j|�qQqQWtj|�}Wntk
r�d}nXWdx'|j�D]\}	}
|
t	j
|	<q�Wx|D]}t	j
|=q�WX|SWdQXdS(sImports and returns a module, deliberately bypassing the sys.modules cache
    and importing a fresh copy of the module. Once the import is complete,
    the sys.modules cache is restored to its original state.

    Modules named in fresh are also imported anew if needed by the import.
    If one of these modules can't be imported, None is returned.

    Importing of modules named in blocked is prevented while the fresh import
    takes place.

    If deprecated is True, any module or package deprecation messages
    will be suppressed.N(RDRUR[tappendRERRFRYtitemsRNRO(RJtfreshtblockedRKRStnames_to_removet
fresh_nametblocked_nametfresh_modulet	orig_nametmoduletname_to_remove((s-/usr/lib64/python2.7/test/support/__init__.pyR6{s&





cCs�yt||�}Wn�tk
r�t|tj�rKd|j|f}n�t|tj�rsd|j|f}nit|tj�r�d|jj|f}n>t|t	�r�d|j|f}ndt	|�j|f}t
j|��nX|SdS(s?Get an attribute, raising SkipTest if AttributeError is raised.smodule %r has no attribute %rsclass %s has no attribute %rs%s instance has no attribute %rs"type object %r has no attribute %rs%r object has no attribute %rN(tgetattrtAttributeErrort
isinstancettypest
ModuleTypeR<t	ClassTypetInstanceTypet	__class__ttypeRGRH(tobjRJt	attributeRL((s-/usr/lib64/python2.7/test/support/__init__.pyR4�s
iicCs
|adS(N(t_original_stdout(tstdout((s-/usr/lib64/python2.7/test/support/__init__.pyR�scCs
tptjS(N(RrRNRs(((s-/usr/lib64/python2.7/test/support/__init__.pyR	�scCs&ytj|=Wntk
r!nXdS(N(RNRORW(RJ((s-/usr/lib64/python2.7/test/support/__init__.pyR
�s
cGsxy||�SWnctk
rs}tdkrVd|jj|fGHd|j|fGHntj|tj�||�SXdS(Nis%s: %ssre-run %s%r(tEnvironmentErrorRRnR<tostchmodtstattS_IRWXU(tpathtfunctargsterr((s-/usr/lib64/python2.7/test/support/__init__.pyt
_force_run�stwincCs�||�|r|}n$tjj|�\}}|p:d}d}xR|dkr�tj|�}|rm|n	||ks}dStj|�|d9}qFWtjd|tdd�dS(NRMg����MbP?g�?is)tests may fail, delete still pending for t
stackleveli(	RuRytsplittlistdirttimetsleepR@twarntRuntimeWarning(RztpathnametwaitalltdirnameRJttimeouttL((s-/usr/lib64/python2.7/test/support/__init__.pyt_waitfor�s
	

cCsttj|�dS(N(R�RuR(tfilename((s-/usr/lib64/python2.7/test/support/__init__.pyt_unlink�scCsttj|�dS(N(R�Rutrmdir(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt_rmdir�scs6�fd��t�|dt�td�|�dS(Ncs�x�t|tj|�D]i}tjj||�}tjj|�rlt�|dt�t|tj|�qt|tj	|�qWdS(NR�(
R}RuR�RytjointisdirR�RVR�R(RyRJtfullname(t
_rmtree_inner(s-/usr/lib64/python2.7/test/support/__init__.pyR�sR�cSst|tj|�S(N(R}RuR�(tp((s-/usr/lib64/python2.7/test/support/__init__.pyt<lambda>	t(R�RV(Ry((R�s-/usr/lib64/python2.7/test/support/__init__.pyt_rmtree�scsSytj|�dSWntk
r(nX�fd���|�tj|�dS(Ncs�x�t|tj|�D]�}tjj||�}ytj|�j}Wntk
r`d}nXtj	|�r��|�t|tj
|�qt|tj|�qWdS(Ni(R}RuR�RyR�tlstattst_modeRtRwtS_ISDIRR�R(RyRJR�tmode(R�(s-/usr/lib64/python2.7/test/support/__init__.pyR�s


(tshutilRRtRuR�(Ry((R�s-/usr/lib64/python2.7/test/support/__init__.pyR�s


cCsIyt|�Wn4tk
rD}|jtjtjfkrE�qEnXdS(N(R�tOSErrorterrnotENOENTtENOTDIR(R�texc((s-/usr/lib64/python2.7/test/support/__init__.pyR$s
cCs@yt|�Wn+tk
r;}|jtjkr<�q<nXdS(N(R�R�R�R�(R�terror((s-/usr/lib64/python2.7/test/support/__init__.pyR�+s
cCsIyt|�Wn4tk
rD}|jtjtjfkrE�qEnXdS(N(R�R�R�R�tESRCH(Ryte((s-/usr/lib64/python2.7/test/support/__init__.pyR3s
cCsjt|�xYtjD]N}ttjj||tjd��ttjj||tjd��qWdS(sm"Forget" a module was ever imported by removing it from sys.modules and
    deleting any .pyc and .pyo files.tpyctpyoN(R
RNRyRRuR�textsep(RTR�((s-/usr/lib64/python2.7/test/support/__init__.pyR
;s
$cs�ttd�rtjSd}tjjd�r ddl�ddl�d}d}d�j	f�fd��Y}�j
j}|j�}|s��j
��n|�}�jj�}|j||�j|��j|��j|��}|s�j
��nt|j|@�s�d}q�n�tjdkr�dd	lm}	m�m}
m	}dd
lm}|	j|d��}
|
j�dkr�d
}q�d|f�fd��Y}|�}|
|�}|
j|�dks�|
j|�dkr�d}q�n|s�y;ddlm}|�}|j �|j!�|j"�Wq�t#k
r�}t$|�}t%|�dkrz|d d}ndj&t'|�j(|�}q�Xn|t_)|t_tjS(NtresultR~i����itUSEROBJECTFLAGScs;eZd�jjfd�jjfd�jjfgZRS(tfInheritt	fReservedtdwFlags(R<R=twintypestBOOLtDWORDt_fields_((tctypes(s-/usr/lib64/python2.7/test/support/__init__.pyR�Rss,gui not available (WSF_VISIBLE flag not set)tdarwin(tcdlltc_inttpointert	Structure(tfind_librarytApplicationServicesis0gui tests cannot run without OS X window managertProcessSerialNumbercs eZd�fd�fgZRS(t
highLongOfPSNtlowLongOfPSN(R<R=R�((R�(s-/usr/lib64/python2.7/test/support/__init__.pyR�ts	s#cannot run without OS X gui process(tTki2s [...]sTk unavailable due to {}: {}(*thasattrt_is_gui_availableR�RYRNtplatformRRR�tctypes.wintypesR�twindlltuser32tGetProcessWindowStationtWinErrorR�R�tGetUserObjectInformationWtbyreftsizeoftboolR�R�R�R�tctypes.utilR�tLoadLibrarytCGMainDisplayIDtGetCurrentProcesstSetFrontProcesstTkinterR�twithdrawtupdatetdestroyt	ExceptionRItlentformatRoR<treason(R�t	UOI_FLAGStWSF_VISIBLER�tdllthtuoftneededtresR�R�R�R�tapp_servicesR�tpsntpsn_pR�trootR�t
err_string((R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR�Gsh		"			

	
cCstdkp|tkS(s�Test whether a resource is enabled.

    Known resources are set by regrtest.py.  If not running under regrtest.py,
    all resources are assumed enabled unless use_resources has been set.
    N(RRY(tresource((s-/usr/lib64/python2.7/test/support/__init__.pyR�scCs`t|�s4|dkr%d|}nt|��n|dkr\t�r\ttj��ndS(s@Raise ResourceDenied if the specified resource is not available.s$Use of the `%s' resource not enabledtguiN(RRYRR�R�(R�RL((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
cs�fd�}|S(s�Decorator raising SkipTest if the OS is Mac OS X and the OS X
    version if less than min_version.

    For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
    is lesser than 10.5.
    cs.tj����fd��}�|_|S(Ncs�tjdkr�tj�d}y"ttt|jd���}Wntk
rTq�X|�kr�djtt	���}t
jd||f��q�n�||�S(NR�iRMs&Mac OS X %s or higher required, not %s(RNR�tmac_verttupletmaptintR�t
ValueErrorR�RIRGRH(R{tkwtversion_txttversiontmin_version_txt(Rztmin_version(s-/usr/lib64/python2.7/test/support/__init__.pytwrapper�s"
(t	functoolstwrapsR�(RzR�(R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyt	decorator�s!	((R�R�((R�s-/usr/lib64/python2.7/test/support/__init__.pyR�ss	127.0.0.1s::1cCs/tj||�}t|�}|j�~|S(s�
Returns an unused port that should be suitable for binding.  This is
    achieved by creating a temporary socket with the same family and type as
    the 'sock' parameter (default is AF_INET, SOCK_STREAM), and binding it to
    the specified host address (defaults to 0.0.0.0) with the port set to 0,
    eliciting an unused ephemeral port from the OS.  The temporary socket is
    then closed and deleted, and the ephemeral port is returned.

    Either this method or bind_port() should be used for any tests where a
    server socket needs to be bound to a particular port for the duration of
    the test.  Which one to use depends on whether the calling code is creating
    a python socket, or if an unused port needs to be provided in a constructor
    or passed to an external program (i.e. the -accept argument to openssl's
    s_server mode).  Always prefer bind_port() over find_unused_port() where
    possible.  Hard coded ports should *NEVER* be used.  As soon as a server
    socket is bound to a hard coded port, the ability to run multiple instances
    of the test simultaneously on the same host is compromised, which makes the
    test a ticking time bomb in a buildbot environment. On Unix buildbots, this
    may simply manifest as a failed test, which can be recovered from without
    intervention in most cases, but on Windows, the entire python process can
    completely and utterly wedge, requiring someone to log in to the buildbot
    and manually kill the affected process.

    (This is easy to reproduce on Windows, unfortunately, and can be traced to
    the SO_REUSEADDR socket option having different semantics on Windows versus
    Unix/Linux.  On Unix, you can't have two AF_INET SOCK_STREAM sockets bind,
    listen and then accept connections on identical host/ports.  An EADDRINUSE
    socket.error will be raised at some point (depending on the platform and
    the order bind and listen were called on each socket).

    However, on Windows, if SO_REUSEADDR is set on the sockets, no EADDRINUSE
    will ever be raised when attempting to bind two identical host/ports. When
    accept() is called on each socket, the second caller's process will steal
    the port from the first caller, leaving them both in an awkwardly wedged
    state where they'll no longer respond to any signals or graceful kills, and
    must be forcibly killed via OpenProcess()/TerminateProcess().

    The solution on Windows is to use the SO_EXCLUSIVEADDRUSE socket option
    instead of SO_REUSEADDR, which effectively affords the same semantics as
    SO_REUSEADDR on Unix.  Given the propensity of Unix developers in the Open
    Source world compared to Windows ones, this is a common mistake.  A quick
    look over OpenSSL's 0.9.8g source shows that they use SO_REUSEADDR when
    openssl.exe is called with the 's_server' option, for example. See
    http://bugs.python.org/issue2550 for more info.  The following site also
    has a very thorough description about the implications of both REUSEADDR
    and EXCLUSIVEADDRUSE on Windows:
    http://msdn2.microsoft.com/en-us/library/ms740621(VS.85).aspx)

    XXX: although this approach is a vast improvement on previous attempts to
    elicit unused ports, it rests heavily on the assumption that the ephemeral
    port returned to us by the OS won't immediately be dished back out to some
    other process when we close and delete our temporary socket but before our
    calling code has a chance to bind the returned port.  We can deal with this
    issue if/when we come across it.(tsocketRtclose(tfamilytsocktypettempsocktport((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
6
cCs|jtjkr�|jtjkr�ttd�rc|jtjtj�dkrct	d��qcnttd�r�y1|jtjtj
�dkr�t	d��nWq�tk
r�q�Xnttd�r�|jtjtj
d�q�n|j|df�|j�d}|S(s%Bind the socket to a free port and return the port number.  Relies on
    ephemeral ports in order to ensure we are using an unbound port.  This is
    important as many tests may be running simultaneously, especially in a
    buildbot environment.  This method raises an exception if the sock.family
    is AF_INET and sock.type is SOCK_STREAM, *and* the socket has SO_REUSEADDR
    or SO_REUSEPORT set on it.  Tests should *never* set these socket options
    for TCP/IP sockets.  The only case for setting these options is testing
    multicasting via multiple UDP sockets.

    Additionally, if the SO_EXCLUSIVEADDRUSE socket option is available (i.e.
    on Windows), it will be set on the socket.  This will prevent anyone else
    from bind()'ing to our host/port for the duration of the test.
    tSO_REUSEADDRisHtests should never set the SO_REUSEADDR socket option on TCP/IP sockets!tSO_REUSEPORTsHtests should never set the SO_REUSEPORT socket option on TCP/IP sockets!tSO_EXCLUSIVEADDRUSEi(R�R�tAF_INETRotSOCK_STREAMR�t
getsockoptt
SOL_SOCKETR�RR�Rtt
setsockoptR�tbindtgetsockname(tsockthostR�((s-/usr/lib64/python2.7/test/support/__init__.pyRs$
cCs{tjrwd}zNy3tjtjtj�}|jtdf�tSWntjk
r[nXWd|rs|j	�nXnt
S(s+Check whether IPv6 is enabled on this host.iN(R�thas_ipv6RYtAF_INET6R�RtHOSTv6RVR�R�RX(R((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_ipv6_enabled$s	cs"tj���fd��}|S(s5Skip the test on TLS certificate validation failures.csRy�||�Wn:tk
rM}dt|�krGtjd��n�nXdS(NtCERTIFICATE_VERIFY_FAILEDs.system does not contain necessary certificates(tIOErrorRIRGRH(R{tkwargsR�(tf(s-/usr/lib64/python2.7/test/support/__init__.pytdec7s(R�R�(RR((Rs-/usr/lib64/python2.7/test/support/__init__.pytsystem_must_validate_cert5s	g���ư>cCs#t|t�st|t�rcy8t|�t|�t}t||�|krUdSWqqXn�t|�t|�krt|ttf�rxPttt	|�t	|���D]-}t
||||�}|dkr�|Sq�Wt	|�t	|�kt	|�t	|�kS||k||kS(Ni(RitfloattabsRRoR�RQtrangetminR�R(txtytfuzztitoutcome((s-/usr/lib64/python2.7/test/support/__init__.pyRDs-(,iiitjavasno unicode supportcCs
t|d�S(Nsunicode-escape(tunicode(ts((s-/usr/lib64/python2.7/test/support/__init__.pytumsi�i0iAi�ii�ii*ii�i� s$testtriscosttestfiles@testR�s@test-��slatin-1tgetwindowsversioniis'u"@test-\u5171\u6709\u3055\u308c\u308b"tLatin1sgWARNING: The filename %r CAN be encoded by the filesystem.  Unicode filename tests may not be effectives	{}_{}_tmpshttp://www.pythontest.netccsQt}|dkrEddl}|j�}t}tjj|�}n�tr�t	|t
�r�tjjr�y|jt
j�pd�}Wq�tk
r�|s�tjd��q�q�Xnytj|�t}Wn7tk
r|s��ntjd|tdd�nX|rtj�}nz	|VWd|rL|tj�krLt|�nXdS(s�Return a context manager that creates a temporary directory.

    Arguments:

      path: the directory to create temporarily.  If omitted or None,
        defaults to creating a temporary directory using tempfile.mkdtemp.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, if the path is specified and cannot be
        created, only a warning is issued.

    i����Ntasciis;unable to encode the cwd name with the filesystem encoding.s+tests may fail, unable to create temp dir: Ri(RXRYttempfiletmkdtempRVRuRytrealpathRRiRtsupports_unicode_filenamestencodeRNtgetfilesystemencodingtUnicodeEncodeErrorRGRHtmkdirR�R@R�R�tgetpidR(Rytquiettdir_createdR tpid((s-/usr/lib64/python2.7/test/support/__init__.pyttemp_dir�s6





	ccs{tj�}ytj|�Wn7tk
rV|s9�ntjd|tdd�nXztj�VWdtj|�XdS(sgReturn a context manager that changes the current working directory.

    Arguments:

      path: the directory to use as the temporary current working directory.

      quiet: if False (the default), the context manager raises an exception
        on error.  Otherwise, it issues only a warning and keeps the current
        working directory the same.

    s)tests may fail, unable to change CWD to: RiN(RutgetcwdtchdirR�R@R�R�(RyR)t	saved_dir((s-/usr/lib64/python2.7/test/support/__init__.pyt
change_cwds


ttempcwdc	csBtd|d|��'}t|d|��}|VWdQXWdQXdS(s�
    Context manager that temporarily creates and changes the CWD.

    The function temporarily changes the current working directory
    after creating a temporary directory in the current directory with
    name *name*.  If *name* is None, the temporary directory is
    created using tempfile.mkdtemp.

    If *quiet* is False (default) and it is not possible to
    create or change the CWD, an error is raised.  If *quiet* is True,
    only a warning is raised and the original CWD is used.

    RyR)N(R,R0(RJR)t	temp_pathtcwd_dir((s-/usr/lib64/python2.7/test/support/__init__.pyR&stdatacCs�tjj|�r|S|dk	r:tjj||�}ntgtj}x9|D]1}tjj||�}tjj|�rQ|SqQW|S(s�Try to find a file on sys.path and the working directory.  If it is not
    found the argument passed to the function is returned (this does not
    necessarily signal failure; could still be the legitimate path).N(RuRytisabsRYR�t
TEST_HOME_DIRRNtexists(tfiletsubdirRytdntfn((s-/usr/lib64/python2.7/test/support/__init__.pyRAs
cCsJ|j�}|j�g|D]}d|^q}dj|�}d|S(s%Like repr(dict), but in sorted order.s%r: %rs, s{%s}(R]tsortR�(tdictR]tpairt	reprpairst
withcommas((s-/usr/lib64/python2.7/test/support/__init__.pyROs

cCs9ttd�}z|j�SWd|j�tt�XdS(s`
    Create an invalid file descriptor by opening and closing a file and return
    its fd.
    twbN(topenRtfilenoR�R(R8((s-/usr/lib64/python2.7/test/support/__init__.pytmake_bad_fdWs

cCs||jt|��}t|dd�WdQX|j}|dk	rV|j|j|�n|dk	rx|j|j|�ndS(Ns
<test string>texec(tassertRaisesRegexptSyntaxErrortcompilet	exceptionRYtassertEqualtlinenotoffset(ttestcaset	statementterrtextRKRLtcmR|((s-/usr/lib64/python2.7/test/support/__init__.pyRcs	c
sSddl}ddl}|j|�djd�d}tjjt|�}�fd�}tjj|�r�||�}|dk	r�|St	|�nt
d�t�d|IJ|j|dd�}zNt
|d	��9}|j�}	x#|	r
|j|	�|j�}	q�WWdQXWd|j�X||�}|dk	r?|Std
|��dS(Ni����it/csGt|�}�dkr|S�|�r9|jd�|S|j�dS(Ni(RBRYtseekR�(R;R(tcheck(s-/usr/lib64/python2.7/test/support/__init__.pytcheck_valid_filess
turlfetchs	fetching %s ...R�iRAsinvalid resource "%s"(turlparseturllib2R�RuRyR�t
TEST_DATA_DIRR7RYRRR	turlopenRBtreadtwriteR�R(
turlRSRVRWR�R;RTRtoutR((RSs-/usr/lib64/python2.7/test/support/__init__.pyRls. 	

	
tWarningsRecordercBs8eZdZd�Zd�Zed��Zd�ZRS(syConvenience wrapper for the warnings list returned on
       entry to the warnings.catch_warnings() context manager.
    cCs||_d|_dS(Ni(t	_warningst_last(tselft
warnings_list((s-/usr/lib64/python2.7/test/support/__init__.pyt__init__�s	cCs\t|j�|jkr,t|jd|�S|tjjkrBdStd||f��dS(Ni����s%r has no attribute %r(	R�R_R`RgR@tWarningMessaget_WARNING_DETAILSRYRh(Ratattr((s-/usr/lib64/python2.7/test/support/__init__.pyt__getattr__�s
cCs|j|jS(N(R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR@�scCst|j�|_dS(N(R�R_R`(Ra((s-/usr/lib64/python2.7/test/support/__init__.pytreset�s(R<R=R>RcRgtpropertyR@Rh(((s-/usr/lib64/python2.7/test/support/__init__.pyR^�s
		c
csptjd�}|jjd�}|r4|j�ntjdt��&}tjdj	d�t
|�VWdQXg|D]}|j^qu}g}x�|D]�\}}	t}
x[|D]R}t
|�}tj||tj�r�t|j|	�r�t}
|j|�q�q�W|
r�|r�|j||	jf�q�q�W|rOtd|d��n|rltd	|d��ndS(
s�Catch the warnings, then check if all the expected
    warnings have been raised and re-raise unexpected warnings.
    If 'quiet' is True, only re-raise the unexpected warnings.
    it__warningregistry__trecordR@talwaysNsunhandled warning %ris)filter (%r, %s) did not catch any warning(RNt	_getframet	f_globalstgettclearR@RARVROtsimplefilterR^tmessageRXRItretmatchtIt
issubclassRntremoveR\R<tAssertionError(
tfiltersR)tframetregistrytwtwarningtreraisetmissingRLtcattseenR�Rr((s-/usr/lib64/python2.7/test/support/__init__.pyt_filterwarnings�s0
cOsI|jd�}|s<dtff}|dkr<t}q<nt||�S(s�Context manager to silence warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default True without argument,
         default False if some filters are defined)

    Without argument, it defaults to:
        check_warnings(("", Warning), quiet=True)
    R)R�N(RotWarningRYRVR�(RyR
R)((s-/usr/lib64/python2.7/test/support/__init__.pyR�scOs@tjr$|s*dtff}q*nd}t||jd��S(sjContext manager to silence py3k warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default False)

    Without argument, it defaults to:
        check_py3k_warnings(("", DeprecationWarning), quiet=False)
    R�R)((RNtpy3kwarningRCR�Ro(RyR
((s-/usr/lib64/python2.7/test/support/__init__.pyR �s
	cBs)eZdZd�Zd�Zd�ZRS(s,Context manager to force import to return a new module reference.

    This is useful for testing module-level behaviours, such as
    the emission of a DeprecationWarning on import.

    Use like this:

        with CleanImport("foo"):
            importlib.import_module("foo") # new reference
    cGsotjj�|_xV|D]N}|tjkrtj|}|j|krZtj|j=ntj|=qqWdS(N(RNROtcopytoriginal_modulesR<(Ratmodule_namestmodule_nameRe((s-/usr/lib64/python2.7/test/support/__init__.pyRcs

cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyt	__enter__scGstjj|j�dS(N(RNROR�R�(Rat
ignore_exc((s-/usr/lib64/python2.7/test/support/__init__.pyt__exit__s(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR!s
	
	cBs_eZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d	�ZRS(
s_Class to help protect the environment variable properly.  Can be used as
    a context manager.cCstj|_i|_dS(N(Rutenviront_environt_changed(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyRc(scCs|j|S(N(R�(Ratenvvar((s-/usr/lib64/python2.7/test/support/__init__.pyt__getitem__,scCs<||jkr+|jj|�|j|<n||j|<dS(N(R�R�Ro(RaR�tvalue((s-/usr/lib64/python2.7/test/support/__init__.pyt__setitem__/scCsK||jkr+|jj|�|j|<n||jkrG|j|=ndS(N(R�R�Ro(RaR�((s-/usr/lib64/python2.7/test/support/__init__.pyt__delitem__5scCs
|jj�S(N(R�tkeys(Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�<scCs|||<dS(N((RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytset?scCs||=dS(N((RaR�((s-/usr/lib64/python2.7/test/support/__init__.pytunsetBscCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�EscGshxU|jj�D]D\}}|dkrG||jkrT|j|=qTq||j|<qW|jt_dS(N(R�R]RYR�RuR�(RaR�tktv((s-/usr/lib64/python2.7/test/support/__init__.pyR�Hs(R<R=R>RcR�R�R�R�R�R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR"#s								t
DirsOnSysPathcBs)eZdZd�Zd�Zd�ZRS(s�Context manager to temporarily add directories to sys.path.

    This makes a copy of sys.path, appends any directories given
    as positional arguments, then reverts sys.path to the copied
    settings when the context ends.

    Note that *all* sys.path modifications in the body of the
    context manager, including replacement of the object,
    will be reverted at the end of the block.
    cGs-tj|_tj|_tjj|�dS(N(RNRytoriginal_valuetoriginal_objecttextend(Ratpaths((s-/usr/lib64/python2.7/test/support/__init__.pyRc^s
cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�cscGs|jt_|jtj(dS(N(R�RNRyR�(RaR�((s-/usr/lib64/python2.7/test/support/__init__.pyR�fs(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR�Rs
		cBs2eZdZd�Zd�Zdddd�ZRS(s�Raise ResourceDenied if an exception is raised while the context manager
    is in effect that matches the specified exception and attributes.cKs||_||_dS(N(R�tattrs(RaR�R
((s-/usr/lib64/python2.7/test/support/__init__.pyRcps	cCs|S(N((Ra((s-/usr/lib64/python2.7/test/support/__init__.pyR�tscCs}|dk	ryt|j|�ryxX|jj�D]8\}}t||�sMPnt||�|kr.Pq.q.Wtd��ndS(s�If type_ is a subclass of self.exc and value has attributes matching
        self.attrs, raise ResourceDenied.  Otherwise let the exception
        propagate (if any).s%an optional resource is not availableN(RYRvR�R�t	iteritemsR�RgR(Rattype_R�t	tracebackRft
attr_value((s-/usr/lib64/python2.7/test/support/__init__.pyR�wsN(R<R=R>RcR�RYR�(((s-/usr/lib64/python2.7/test/support/__init__.pyR%ks		c#s�dddd d!d"g}d#d$d%d&d'g}td|��|�g��s�g|D]\}}tt||�^qV�g|D]\}}tt||�^q��n���fd�}tj�}z�y%|dk	r�tj|�ndVWn�tk
r�}	xxtr}|	j	}
t
|
�dkrGt|
dt�rG|
d}	qt
|
�dkryt|
dt�ry|
d}	qPqW||	��nXWdtj|�XdS((s�Return a context manager that raises ResourceDenied when various issues
    with the Internet connection manifest themselves as exceptions.tECONNREFUSEDiot
ECONNRESETihtEHOSTUNREACHiqtENETUNREACHiet	ETIMEDOUTint
EADDRNOTAVAILict	EAI_AGAINi����tEAI_FAILi����t
EAI_NONAMEi����t
EAI_NODATAi����t
WSANO_DATAi�*sResource '%s' is not availablecst|dd�}t|tj�sNt|tj�rB|�ksN|�kr{tsrtjj	�j
dd�n��ndS(NR�is
(RgRYRiR�R�tgaierrorRRNtstderrR[R{(R|tn(tcaptured_errnostdeniedt
gai_errnos(s-/usr/lib64/python2.7/test/support/__init__.pytfilter_error�sNiii(R�io(R�ih(R�iq(R�ie(R�in(R�ic(R�i����(R�i����(R�i����(R�i����(R�i�*(RRgR�R�tgetdefaulttimeoutRYtsetdefaulttimeoutR	RVR{R�Ri(t
resource_nameR�terrnostdefault_errnostdefault_gai_errnosRJtnumR�told_timeoutR|ta((R�R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR&�sJ		(+				%
%

ccs[ddl}tt|�}tt||j��ztt|�VWdtt||�XdS(s�Return a context manager used by captured_stdout and captured_stdin
    that temporarily replaces the sys stream *stream_name* with a StringIO.i����N(tStringIORgRNtsetattr(tstream_nameR�torig_stdout((s-/usr/lib64/python2.7/test/support/__init__.pyR#�scCs
td�S(s�Capture the output of sys.stdout:

       with captured_stdout() as s:
           print "hello"
       self.assertEqual(s.getvalue(), "hello")
    Rs(R#(((s-/usr/lib64/python2.7/test/support/__init__.pyR$�scCs
td�S(NR�(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stderr�scCs
td�S(Ntstdin(R#(((s-/usr/lib64/python2.7/test/support/__init__.pytcaptured_stdin�scCs8tj�tr tjd�ntj�tj�dS(s�Force as many objects as possible to be collected.

    In non-CPython implementations of Python, this is needed because timely
    deallocation is not guaranteed by the garbage collector.  (Even in CPython
    this can be the case in case of reference cycles.)  This means that __del__
    methods may be called later than expected and weakrefs may remain alive for
    longer than expected.  This function tries its best to force all garbage
    objects to disappear.
    g�������?N(tgctcollectRR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyt
gc_collect�s



t2PtgettotalrefcounttPcCstjt|d�S(Nt0P(tstructtcalcsizet_header(tfmt((s-/usr/lib64/python2.7/test/support/__init__.pytcalcobjsize�scCstjt|d�S(NR�(R�R�t_vheader(R�((s-/usr/lib64/python2.7/test/support/__init__.pytcalcvobjsize�sii	cCs�ddl}tj|�}t|�tkr:|jt@s_t|�tkrot|�jt@ro||j7}ndt|�||f}|j|||�dS(Ni����s&wrong size for %s: got %d, expected %d(	t	_testcapiRNt	getsizeofRot	__flags__t_TPFLAGS_HEAPTYPEt_TPFLAGS_HAVE_GCtSIZEOF_PYGC_HEADRJ(ttesttotsizeR�R�RL((s-/usr/lib64/python2.7/test/support/__init__.pytcheck_sizeofs%cs��fd�}|S(Ncs1���fd�}�j|_�j|_|S(Ncs�y.ddl}t|��}|j|�}Wn$tk
rD�nAd}}n1Xx-�D]%}y|j||�PWq\q\Xq\Wz�||�SWd|r�|r�|j||�nXdS(Ni����(tlocaleRgt	setlocaleRhRY(R{tkwdsR�tcategorytorig_localetloc(tcatstrRztlocales(s-/usr/lib64/python2.7/test/support/__init__.pytinners$

(t	func_nameR>(RzR�(R�R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR�s((R�R�R�((R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR'scs�fd�}|S(Ncs.��fd�}�j|_�j|_|S(Ncs�y
tj}Wn tk
r/tjd��nXdtjkrOtjd}nd}�tjd<|�z�||�SWd|dkr�tjd=n
|tjd<tj�XdS(Nstzset requiredtTZ(R�ttzsetRhRGRHRuR�RY(R{R�R�torig_tz(Rzttz(s-/usr/lib64/python2.7/test/support/__init__.pyR�;s




(R<R>(RzR�(R�(Rzs-/usr/lib64/python2.7/test/support/__init__.pyR�:s((R�R�((R�s-/usr/lib64/python2.7/test/support/__init__.pyR:9scCs�idd6td6td6dtd6}tjd|tjtjB�}|dkrgtd|f��ntt	|j
d��||j
d	�j��}|a|t
kr�t
}n|tdkr�td
|f��n|adS(NiR�tmtgtts(\d+(\.\d+)?) (K|M|G|T)b?$sInvalid memory limit %riis$Memory limit %r too low to be useful(t_1Mt_1GRsRtt
IGNORECASEtVERBOSERYR�R�Rtgrouptlowertreal_max_memusetMAX_Py_ssize_tt_2GR(tlimittsizesR�tmemlimit((s-/usr/lib64/python2.7/test/support/__init__.pyR(bs 2	ics���fd�}|S(sQDecorator for bigmem tests.

    'minsize' is the minimum useful size for the test (in arbitrary,
    test-interpreted units.) 'memuse' is the number of 'bytes per size' for
    the test, or a good estimate of it. 'overhead' specifies fixed overhead,
    independent of the testsize, and defaults to 5Mb.

    The decorator tries to guess a good value for 'size' and passes it to
    the decorated test function. If minsize * memuse is more than the
    allowed memory use (as defined by max_memuse), the test is skipped.
    Otherwise, minsize is adjusted upward to use up to max_memuse.
    cs7����fd�}�|_�|_�|_|S(Ncs�ts.d}|j|��dtk�n^tt���}|�krutrqtjjd�jf�ndSt	|dt��}�||�S(Niis)Skipping %s because of memory constraint
i2(
RtassertFalseR�R�RRNR�R[R<tmax(Ratmaxsize(Rtmemusetminsizetoverhead(s-/usr/lib64/python2.7/test/support/__init__.pyR��s"(R�R�R�(RR�(R�R�R�(Rs-/usr/lib64/python2.7/test/support/__init__.pyR��s
			((R�R�R�R�((R�R�R�s-/usr/lib64/python2.7/test/support/__init__.pyR)ws
cs����fd�}|S(Ncs7����fd�}�|_�|_�|_|S(Ncsftsd}n�}ts"�rYt|�krYtrUtjjd�jf�ndS�||�S(Nis)Skipping %s because of memory constraint
(R�RRNR�R[R<(RaR�(tdry_runRR�R�(s-/usr/lib64/python2.7/test/support/__init__.pyR��s	
(R�R�R�(RR�(RR�R�R�(Rs-/usr/lib64/python2.7/test/support/__init__.pyR��s
			((R�R�R�RR�((RR�R�R�s-/usr/lib64/python2.7/test/support/__init__.pytprecisionbigmemtest�scs�fd�}|S(s0Decorator for tests that fill the address space.cs@ttkr2tr<tjjd�jf�q<n
�|�SdS(Ns)Skipping %s because of memory constraint
(RR�RRNR�R[R<(Ra(R(s-/usr/lib64/python2.7/test/support/__init__.pyR��s
((RR�((Rs-/usr/lib64/python2.7/test/support/__init__.pyR*�scBseZd�ZRS(cCstj�}||�|S(N(RGt
TestResult(RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytrun�s
(R<R=R(((s-/usr/lib64/python2.7/test/support/__init__.pyR+�scCs|S(N((Rp((s-/usr/lib64/python2.7/test/support/__init__.pyt_id�scCsP|dkr&t�r&tjtj�St|�r6tStjdj|��SdS(NR�sresource {0!r} is not enabled(R�RGtskipR�RRR�(R�((s-/usr/lib64/python2.7/test/support/__init__.pytrequires_resource�s
cCstdt�|�S(s9
    Decorator for tests only applicable on CPython.
    tcpython(timpl_detailRV(R�((s-/usr/lib64/python2.7/test/support/__init__.pyR2�scKs}t|�rtS|dkrpt|�\}}|r=d}nd}t|j��}|jdj|��}ntj	|�S(Ns*implementation detail not available on {0}s%implementation detail specific to {0}s or (
R3RRYt
_parse_guardstsortedR�R�R�RGR(RLtguardst
guardnamestdefault((s-/usr/lib64/python2.7/test/support/__init__.pyR�s	cCsW|sitd6tfS|j�d}|j�|gt|�ksLt�||fS(NRi(RVRXtvaluesR�Rx(Rtis_true((s-/usr/lib64/python2.7/test/support/__init__.pyR	�s
%cKs.t|�\}}|jtj�j�|�S(s5This function returns True or False depending on the host platform.
       Examples:
          if check_impl_detail():               # only on CPython (default)
          if check_impl_detail(jython=True):    # only on Jython
          if check_impl_detail(cpython=False):  # everywhere except on CPython
    (R	RoR�tpython_implementationR�(RR
((s-/usr/lib64/python2.7/test/support/__init__.pyR3�scCsrg}x\|jD]Q}t|tj�rEt||�|j|�q||�r|j|�qqW||_dS(s>Recursively filter test cases in a suite based on a predicate.N(t_testsRiRGt	TestSuitet
_filter_suiteR\(tsuitetpredtnewtestsR�((s-/usr/lib64/python2.7/test/support/__init__.pyR�s
cCs�tr'tjtjdddt�}n	t�}|j|�}|jr\|j	r\t
�n|j�s�t|j
�dkr�|jr�|j
dd}nLt|j�dkr�|j
r�|jdd}nd}ts�|d7}nt|��ndS(	s2Run tests from a unittest.TestSuite-derived class.t	verbosityitfailfastiismultiple errors occurreds!; run in verbose mode for detailsN(RRGtTextTestRunnerRNRsRR+RttestsRuntskippedRt
wasSuccessfulR�terrorstfailuresR(RtrunnerR�R|((s-/usr/lib64/python2.7/test/support/__init__.pyt
_run_suites 		
cCs$tdkrtSt|j��SdS(N(t_match_test_funcRYRVtid(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt
match_test#scCsd|kotjd|�S(NRMs[?*\[\]](Rstsearch(tpattern((s-/usr/lib64/python2.7/test/support/__init__.pyt_is_full_match_test+scs�|tkrdS|s%d}d}nittt|��rLt|�j}nBdjttj	|��}t
j|�j��fd�}|}t
|�a|adS(Nt|cs0�|�rtStt�|jd���SdS(NRM(RVtanyR�R�(ttest_id(tregex_match(s-/usr/lib64/python2.7/test/support/__init__.pytmatch_test_regexJs((t_match_test_patternsRYtallR�R&R�t__contains__R�tfnmatcht	translateRsRHRtR�R!(tpatternsRztregexR+((R*s-/usr/lib64/python2.7/test/support/__init__.pytset_match_tests5s	cGs�tjtjf}tj�}x�|D]�}t|t�rx|tjkri|jtjtj|��q�t	d��q%t||�r�|j|�q%|jtj
|��q%Wt|t�t
|�dS(s1Run tests from unittest.TestCase-derived classes.s)str arguments must be keys in sys.modulesN(RGRtTestCaseRiRIRNROtaddTestt
findTestCasesR�t	makeSuiteRR#R (tclassestvalid_typesRtcls((s-/usr/lib64/python2.7/test/support/__init__.pyR,]s
 
Rtwin32tWITH_DOC_STRINGSstest requires docstringscCs�ddl}|dkr!t}nd}tj}t�t_z>|j|d|�\}}|rytd||f��nWd|t_Xtr�d|j|fGHn||fS(s
Run doctest on the given module.  Return (#failures, #tests).

    If optional argument verbosity is not specified (or is None), pass
    test.support's belief about verbosity on to doctest.  Else doctest's
    usual behavior is used (it searches sys.argv for -v).
    i����NRs%d of %d doctests faileds,doctest (%s) ... %d tests with zero failures(	tdoctestRYRRNRsR	ttestmodRR<(ReRR=tsave_stdoutRR�((s-/usr/lib64/python2.7/test/support/__init__.pyR-|s		
cCstrtj�fSdSdS(Ni(i(tthreadt_count(((s-/usr/lib64/python2.7/test/support/__init__.pyR.�s
cCsTts
dSd}x=t|�D]/}tj�}||kr?Pntjd�qWdS(Ni
g�������?(R@RRAR�R�(t
nb_threadst
_MAX_COUNTtcountR�((s-/usr/lib64/python2.7/test/support/__init__.pyR/�scs,ts
�Stj���fd��}|S(s�Use this function when threads are being used.  This will
    ensure that the threads are cleaned up even when the test fails.
    If threading is unavailable this function does nothing.
    cs)t�}z�|�SWdt|�XdS(N(R.R/(R{tkey(Rz(s-/usr/lib64/python2.7/test/support/__init__.pyR��s	(R@R�R�(RzR�((Rzs-/usr/lib64/python2.7/test/support/__init__.pyR0�sgN@ccs�tj�}z	dVWdtj�}||}x�tr�tj�}||krSPntj�|kr�tj�|}d|||||f}t|��ntjd�t�q1WXdS(sE
    bpo-31234: Context manager to wait until all threads created in the with
    statement exit.

    Use thread.count() to check if threads exited. Indirectly, wait until
    threads exit the internal t_bootstrap() C function of the thread module.

    threading_setup() and threading_cleanup() are designed to emit a warning
    if a test leaves running threads in the background. This context manager
    is designed to cleanup threads started by the thread.start_new_thread()
    which doesn't allow to wait for thread exit, whereas thread.Thread has a
    join() method.
    NsYwait_threads() failed to cleanup %s threads after %.1f seconds (count: %s, old count: %s)g{�G�z�?(R@RAR�RVRxR�R�(R�t	old_countt
start_timetdeadlineRDtdtRL((s-/usr/lib64/python2.7/test/support/__init__.pytwait_threads_exit�s 	
	
cCscttd�r_d}xGtr[y/tj|tj�\}}|dkrLPnWqPqXqWndS(s�Use this function at the end of test_main() whenever sub-processes
    are started.  This will help ensure that no extra children (zombies)
    stick around to hog resources and create problems when looking
    for refleaks.
    twaitpidi����iN(R�RuRVRKtWNOHANG(tany_processR+tstatus((s-/usr/lib64/python2.7/test/support/__init__.pyR7�s		c	cs�t|�}g}zfy,x%|D]}|j�|j|�qWWn.trkdt|�t|�fGHn�nXdVWd|r�|�ntj�}}x�tdd�D]�}|d7}x.|D]&}|jt|tj�d��q�Wg|D]}|j	�r�|^q�}|sPntr�dt|�|fGHq�q�WXg|D]}|j	�rE|^qE}|r�t
dt|���ndS(Ns/Can't start %d threads, only %d threads startediii<g{�G�z�?s7Unable to join %d threads during a period of %d minutessUnable to join %d threads(RQtstartR\RR�R�RR�R�tisAliveRx(tthreadstunlocktstartedR�tendtimet	starttimeR�((s-/usr/lib64/python2.7/test/support/__init__.pyR1s:

	


$%%ccs�t||�rNt||�}t|||�z	|VWdt|||�Xn<t|||�z	dVWdt||�r�t||�nXdS(s�Temporary swap out an attribute with a new object.

    Usage:
        with swap_attr(obj, "attr", 5):
            ...

        This will set obj.attr to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `attr` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N(R�RgR�tdelattr(RpRftnew_valtreal_val((s-/usr/lib64/python2.7/test/support/__init__.pyt	swap_attr)s		ccsk||kr:||}|||<z	|VWd|||<Xn-|||<z	dVWd||krf||=nXdS(s�Temporary swap out an item with a new object.

    Usage:
        with swap_item(obj, "item", 5):
            ...

        This will set obj["item"] to 5 for the duration of the with: block,
        restoring the old value at the end of the block. If `item` doesn't
        exist on `obj`, it will be created and then deleted at the end of the
        block.

        The old value (or None if it doesn't exist) will be assigned to the
        target of the "as" clause, if there is one.
    N((RptitemRWRX((s-/usr/lib64/python2.7/test/support/__init__.pyt	swap_itemHs

	
	cCs\y|j�SWnGtk
rWydjd�|D��SWqXtk
rSt|�SXnXdS(sZEmulate the py3k bytes() constructor.

    NOTE: This is only a best effort function.
    R�css|]}t|�VqdS(N(tchr(t.0R((s-/usr/lib64/python2.7/test/support/__init__.pys	<genexpr>rsN(ttobytesRhR�t	TypeErrortbytes(tb((s-/usr/lib64/python2.7/test/support/__init__.pyR5gs

t	getcountss-types are immortal if COUNT_ALLOCS is definedcCsddl}|j�S(sZReturn a list of command-line arguments reproducing the current
    settings in sys.flags.i����N(t
subprocesst_args_from_interpreter_flags(Rc((s-/usr/lib64/python2.7/test/support/__init__.pytargs_from_interpreter_flagsyscCstjdd|�j�}|S(s�Strip the stderr of a Python process from potential debug output
    emitted by the interpreter.

    This will typically be run on the result of the communicate() method
    of a subprocess.Popen object.
    s\[\d+ refs\]\r?\n?$R�(Rstsubtstrip(R�((s-/usr/lib64/python2.7/test/support/__init__.pyR8scsid|f��fd��Y}tg�|||���|jtt��t�|j�d�dS(NtAcseZ��fd�ZRS(cs0t�d<yt��Wntk
r+nXdS(Ni(RVtnextt
StopIteration(Ra(tdonetit(s-/usr/lib64/python2.7/test/support/__init__.pyt__del__�s


(R<R=Rm((RkRl(s-/usr/lib64/python2.7/test/support/__init__.pyRh�si(RXtassertRaisesRjRiR�t
assertTrue(R�titerR:R{Rh((RkRls-/usr/lib64/python2.7/test/support/__init__.pytcheck_free_after_iterating�s	ccs:tj�}tj�z	dVWd|r5tj�nXdS(N(R�t	isenabledtdisabletenable(thave_gc((s-/usr/lib64/python2.7/test/support/__init__.pyt
disable_gc�s
	cCsTtjd�pd}d}x,|j�D]}|jd�r(|}q(q(W|dkS(s,Find if Python was built with optimizations.t	PY_CFLAGSR�s-Os-O0s-Og(R�s-O0s-Og(t	sysconfigtget_config_varR�RR(tcflagst	final_opttopt((s-/usr/lib64/python2.7/test/support/__init__.pytpython_is_optimized�s
cBs,eZdZdZdZd�Zd�ZRS(s�Try to prevent a crash report from popping up.

    On Windows, don't display the Windows Error Reporting dialog.  On UNIX,
    disable the creation of coredump file.
    cCstjjd�r�ddl}|jj|_d}|jj|�|_|jj|j|B�yddl	}|j
Wnttfk
r�qXi|_
x|j|j|jgD]C}|j
||j�}|j||j�}||f|j
|<q�Wnyddl}Wntk
r%d}nX|dk	r�y9|j|j�|_|j|jd|jdf�Wq�ttfk
r�q�Xntjdkrddl}dd	d
dg}	|j|	d|jd
|j�}
|
j�d}|j�dkrtj j!d�tj j"�qn|S(s�On Windows, disable Windows Error Reporting dialogs using
        SetErrorMode.

        On UNIX, try to save the previous core file size limit, then set
        soft limit to 0.
        R~i����NiiiR�s/usr/bin/defaultsRZscom.apple.CrashReportert
DialogTypeRsR�t	developers:this test triggers the Crash Reporter, that is intentional(#RNR�RRR�R�tkernel32t_k32tSetErrorModet	old_valueR�tCrtSetReportModeRhRFt	old_modestCRT_WARNt	CRT_ERRORt
CRT_ASSERTtCRTDBG_MODE_FILEtCrtSetReportFiletCRTDBG_FILE_STDERRR�RYt	getrlimittRLIMIT_COREt	setrlimitR�R�RctPopentPIPEtcommunicateRgRsR[tflush(RaR�tSEM_NOGPFAULTERRORBOXR�treport_typetold_modetold_fileR�RctcmdtprocRs((s-/usr/lib64/python2.7/test/support/__init__.pyR��sV				

	cGs�|jdkrdStjjd�r�|jj|j�|jr�ddl}xF|jj	�D]2\}\}}|j
||�|j||�q]Wq�n@ddl}y|j
|j|j�Wnttfk
r�nXdS(sARestore Windows ErrorMode or core file behavior to initial value.NR~i����(R�RYRNR�RRR�R�R�R�R]R�R�R�R�R�R�R�(RaR�R�R�R�R�R�((s-/usr/lib64/python2.7/test/support/__init__.pyR�s	"N(R<R=R>RYR�R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR;�s
	GcCs*ddl}t��|j�WdQXdS(s�Deliberate crash of Python.

    Python can be killed by a segmentation fault (SIGSEGV), a bus error
    (SIGBUS), or a different error depending on the platform.

    Use SuppressCrashReport() to prevent a crash report from popping up.
    i����N(R�R;t
_read_null(R�((s-/usr/lib64/python2.7/test/support/__init__.pyt
_crash_pythons	
c
Cs�tjjd�rdy!tjd�}t|�dSWqdtk
r`}|jtjkra�qaqdXnd}t	td�r�ytj
d�}Wq�tk
r�q�Xnd
}tjdkr+yd	d
l}|j
Wnttfk
r�q+Xi}x9|j|j|jfD]}|j
|d�||<qWnzyd}xlt|�D]^}ytj|�}Wn+tk
r�}	|	jtjkr��q�qAXtj|�|d7}qAWWd
|d
k	r�x7|j|j|jfD]}|j
|||�q�WnX|S(
s/Count the number of open file descriptors.
    tlinuxtfreebsds
/proc/self/fdiitsysconftSC_OPEN_MAXR;i����Ni(R�R�(RNR�RRRuR�R�R�R�R�R�R�RYtmsvcrtR�RhRFR�R�R�RtduptEBADFR�(
tnamesR�tMAXFDR�R�R�RDtfdtfd2R�((s-/usr/lib64/python2.7/test/support/__init__.pytfd_count#sR

	

	tSaveSignalscBs)eZdZd�Zd�Zd�ZRS(s�
    Save an restore signal handlers.

    This class is only able to save/restore signal handlers registered
    by the Python signal module: see bpo-13285 for "external" signal
    handlers.
    cCs�ddl}||_ttd|j��|_xHdD]@}yt||�}Wntk
rfq7nX|jj|�q7Wi|_dS(Ni����itSIGKILLtSIGSTOP(R�R�(	tsignalRQRtNSIGtsignalsRgRhRwthandlers(RaR�tsignametsignum((s-/usr/lib64/python2.7/test/support/__init__.pyRchs	

cCsIxB|jD]7}|jj|�}|dkr4q
n||j|<q
WdS(N(R�R�t	getsignalRYR�(RaR�thandler((s-/usr/lib64/python2.7/test/support/__init__.pytsaveus
cCs7x0|jj�D]\}}|jj||�qWdS(N(R�R]R�(RaR�R�((s-/usr/lib64/python2.7/test/support/__init__.pytrestore�s(R<R=R>RcR�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyR�_s	
	((ii@i@i@ii(i@ii(((((�R>R<RFt
contextlibR�R/R�R�R�RwRNRuR�R�R@RGREtUserDictRsR�R�RxRjR@RYt__all__t
SHORT_TIMEOUTR�RRRRHRtcontextmanagerRVRDRXRRUR[R6R4RRRR�RRrRR	R
R}RRR�R�R�R�RR�RR
R�RRRRRR�R�RRRR9R
RRt
PIPE_MAX_SIZEt
SOCK_MAX_SIZERRRt	NameErrort
skipUnlesstrequires_unicodeRtFS_NONASCIItunichrt	characterR$R%tdecodetUnicodeErrorRJRRitTESTFN_UNICODEtTESTFN_ENCODINGR�RtTESTFN_UNENCODABLEtevalR&R�R(t
TEST_HTTP_URLR-RR,R0RRyR�tabspatht__file__tTEST_SUPPORT_DIRR6R�RXRRRDRRtobjectR^R�RR R!t	DictMixinR"R�R%R&R#R$R�R�R�R�R�R�R�R�R�R�R'R:R�R�R�t_4GR�R�R(R)RR*R+RRR2RR	R3RR R!R,R#R&R3R,RytHAVE_DOCSTRINGStrequires_docstringsR-tenvironment_alteredR.R/R0RJR7R1RYR[R5tskipIftrequires_type_collectingReR8RqRvR}R;R�R�R�(((s-/usr/lib64/python2.7/test/support/__init__.pyt<module>s�

								
	
	
&					
!										J			<$			
	


												

				
	.			*' /D					

				$	"


		'				
	
					
	(			&
			#	 					
e		<PK�R�Z;rq�##support/script_helper.pyonu�[����
{fc@s.ddlZddlZddlZddlZddlZddlZddlZddlZddlZyddl	Z	Wne
k
r�nXddlmZd�Z
d�Zd�Zd�Zd�Zd�Zd	�Zejd
��Zd�Zd�Zdd
�Zdd�Zded�ZdS(i����N(tstrip_python_stderrc	
Ostjg}|s"|jd�n|j|�tjj�}|j|�tj	|dtj
dtj
dtj
d|�}z|j�\}}Wdtj�|j
j�|jj�X|j}t|�}|r�|s�|r
|r
td||jdd�f��n|||fS(	Ns-Etstdintstdouttstderrtenvs-Process return code is %d, stderr follows:
%stasciitignore(tsyst
executabletappendtextendtostenvirontcopytupdatet
subprocesstPopentPIPEtcommunicatet_cleanupRtcloseRt
returncodeRtAssertionErrortdecode(	texpected_successtargstenv_varstcmd_lineRtptoutterrtrc((s2/usr/lib64/python2.7/test/support/script_helper.pyt_assert_pythons*

	

	cOstt||�S(s�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` is ok and return a (return code, stdout, stderr) tuple.
    (R tTrue(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_ok2scOstt||�S(s�
    Assert that running the interpreter with `args` and optional environment
    variables `env_vars` fails and return a (return code, stdout, stderr) tuple.
    (R tFalse(RR((s2/usr/lib64/python2.7/test/support/script_helper.pytassert_python_failure9sc
GsWtjdg}|j|�ttjd��#}tj|d|dtj�SWdQXdS(Ns-EtwRR(	RRR
topenRtdevnullRtcalltSTDOUT(RRR'((s2/usr/lib64/python2.7/test/support/script_helper.pytpython_exit_code@s

c	OsGtjdg}|j|�tj|dtjdtjdtj|�S(Ns-ERRR(RRR
RRRR)(RtkwargsR((s2/usr/lib64/python2.7/test/support/script_helper.pytspawn_pythonGs

cCsA|jj�|jj�}|jj�|j�tj�|S(N(RRRtreadtwaitRR(Rtdata((s2/usr/lib64/python2.7/test/support/script_helper.pytkill_pythonNs



cOs.td||�}t|�}|j�|fS(Ns-O(R,R0R.(RR+Rtstdout_data((s2/usr/lib64/python2.7/test/support/script_helper.pyt
run_pythonXsccs<tj�}tjj|�}z	|VWdtj|�XdS(N(ttempfiletmkdtempRtpathtrealpathtshutiltrmtree(tdirname((s2/usr/lib64/python2.7/test/support/script_helper.pyttemp_diras
	cCsP|tjd}tjj||�}t|d�}|j|�|j�|S(NtpyR%(RtextsepR5tjoinR&twriteR(t
script_dirtscript_basenametsourcetscript_filenametscript_nametscript_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_scriptjs

cCs!tj|dt�|d}|S(Ntdoraiseto(t
py_compiletcompileR!(RCt
compiled_name((s2/usr/lib64/python2.7/test/support/script_helper.pytcompile_scriptrs
cCs�|tjd}tjj||�}tj|d�}|dkrYtjj|�}n|j||�|j	�|tjj||�fS(NtzipR%(
RR<R5R=tzipfiletZipFiletNonetbasenameR>R(tzip_dirtzip_basenameRCtname_in_ziptzip_filenametzip_nametzip_file((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_scriptzs
tcCs!tj|�t|d|�dS(Nt__init__(RtmkdirRE(tpkg_dirtinit_source((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_pkg�s
icCs�g}t|dd�}|j|�tjj|�}	t|||�}
|j|
�|r�t|�}t|
�}
|j||
f�ngtd|d�D]}tjj	|g|�^q�}tjj	|dtjj|
��}
|tj
d}tjj	||�}tj|d�}x3|D]+}tjj	||	�}|j
||�q'W|j
|
|
�|j�x|D]}tj|�qwW|tjj	||
�fS(NRYRXii����RLR%(RER	RR5RPRKR
trangetsepR=R<RMRNR>Rtunlink(RQRRtpkg_nameR@RAtdepthtcompiledR`t	init_namet
init_basenameRCtit	pkg_namestscript_name_in_zipRTRURVtnametinit_name_in_zip((s2/usr/lib64/python2.7/test/support/script_helper.pytmake_zip_pkg�s.

9%


(RRtretos.pathR3RRHt
contextlibR7RMtImportErrorttest.supportRR R"R$R*R,R0R2tcontextmanagerR:RERKRORWR]R#Rk(((s2/usr/lib64/python2.7/test/support/script_helper.pyt<module>s4
						
					PK�R�ZJ�[�test_support.pycnu�[����
zfc@s,ddlZddlZejejd<dS(i����Nstest.test_support(tsysttest.supportttesttsupporttmodules(((s)/usr/lib64/python2.7/test/test_support.pyt<module>sPK�R�Z�A?�||__init__.pycnu�[����
zfc@sdS(N((((s%/usr/lib64/python2.7/test/__init__.pyt<module>tPK�R�Z�GKF��script_helper.pyonu�[����
zfc@sddlTdS(i����(t*N(ttest.support.script_helper(((s*/usr/lib64/python2.7/test/script_helper.pyt<module>tPK��Z���qtestroot/plugins.qmltypesnu�[���import QtQuick.tooling 1.2

// This file describes the plugin-supplied types contained in the library.
// It is used for QML tooling purposes only.
//
// This file was auto-generated by qmltyperegistrar.

Module {
    dependencies: ["QtQuick 2.0"]
    Component {
        file: "private/quicktest_p.h"
        name: "QTestRootObject"
        prototype: "QObject"
        exports: ["Qt.test.qtestroot/QTestRootObject 1.0"]
        isCreatable: false
        isSingleton: true
        exportMetaObjectRevisions: [0]
        Property { name: "windowShown"; type: "bool"; isReadonly: true }
        Property { name: "hasTestCase"; type: "bool" }
        Property { name: "defined"; type: "QObject"; isReadonly: true; isPointer: true }
        Method { name: "quit" }
    }
}
PK��Z�iU�33qtestroot/qmldirnu�[���module Qt.test.qtestroot
typeinfo plugins.qmltypes
PK'/�Z��Mf}g}gwidget_tests.pyonu�[����
zfc@sVddlZddlZddlZddlmZddlmZmZm	Z	m
Z
mZmZddl
ZeZZe
�dddfkr�eZneo�ee�Zd�ZeZe
�d dddfkr�eZne�Zd	efd
��YZdefd��YZd
efd��YZdefd��YZd�Zd�ZdS(i����N(tScale(tAbstractTkTestttcl_versiontrequires_tcltget_tk_patchleveltpixels_convt
tcl_obj_eqiiicCstt|��S(N(tinttround(tx((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	int_roundsitAbstractWidgetTestcBs�eZee�ZdZeZe	d��Z
d�Zdej
d�Zeedd�Zded�Zd�Zd�Zd�Zd�Zdd	�Zd
�Zd�Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Z RS(cCsEy|jSWn3tk
r@t|jjdd��|_|jSXdS(Nttktscaling(t_scalingtAttributeErrortfloattroottcall(tself((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR
"s

cCsU|jr#|jr#tdkr#|St|t�rKdjt|j|��St|�S(Niit (ii(	t
_stringifytwantobjectsRt
isinstancettupletjointmapt_strtstr(Rtvalue((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR*s
cCs*|||�rdS|j|||�dS(N(tassertEqual(Rtactualtexpectedtmsgteq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytassertEqual21scCs|||<|tkr|}n|r4||�}n|jsG|jrwt|t�rhtj|�}qwt|�}n|dkr�t	}n|j
|||d|�|j
|j|�|d|�t|t�s|j
|�}|jt|�d�|j
|d|d|�ndS(NR"ii(t	_sentinelRRRRttkintert_joinRtNoneRR#tcgetRt	configureRtlen(RtwidgettnameRR tconvR"tt((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
checkParam6s"
		c	Cs||}|dk	r(|j|�}n|jtj��}|||<WdQX|dk	ru|jt|j�|�n|r�|j|||�n
|||<|jtj��}|ji||6�WdQX|dk	r�|jt|j�|�n|r|j|||�n
|||<dS(N(	R'tformattassertRaisesR%tTclErrorRRt	exceptionR)(RR+R,Rterrmsgt	keep_origtorigtcm((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckInvalidParamLs"

cOs+x$|D]}|j||||�qWdS(N(R/(RR+R,tvaluestkwargsR((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckParamsbs
cOse|j||||�|j||ddd�|j||ddd�|j||ddd�dS(NtR4sexpected integer but got ""t10psexpected integer but got "10p"g������	@sexpected integer but got "3.2"(R;R8(RR+R,R9R:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckIntegerParamfscOs�d|kr|jd�}nt}x*|D]"}|j|||d||�q+W|j||ddd�|j||ddd�dS(NR-R<R4s)expected floating-point number but got ""tspams-expected floating-point number but got "spam"(tpopRR/R8(RR+R,R9R:R-R((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckFloatParamos
 cCs�x6tddddfD]}|j|||dd�qWx6tdddd	fD]}|j|||dd�qOW|j||d
dd�|j||d
dd�dS(NitfalsetnotoffR ittruetyestonR<R4s!expected boolean value but got ""R?s%expected boolean value but got "spam"(tFalseR/tTrueR8(RR+R,R((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckBooleanParam{scKsN|j||ddddddddd	d
|�|j||ddd
�dS(Ns#ff0000s#00ff00s#0000ffs#123456tredtgreentbluetwhitetblacktgreyR?R4sunknown color name "spam"(R;R8(RR+R,tallow_emptyR:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckColorParam�scKs^|j||dddd|�tdkrA|j||d�n|j||dd	d
�dS(NtarrowtwatchtcrossR<iitnoneR?R4sbad cursor spec "spam"(ii(R;RR/R8(RR+R,R:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckCursorParam�s
cCs;d�}|||<|j||�|j||d�dS(NcWsdS(N((targs((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcommand�sR<(t
assertTrueR;(RR+R,RY((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckCommandParam�s	
cOs�d|kr|jd�}nd}|j||||�|dkr�d|dj|d �t|�dkrtdnd|df}|j||ddd|�d	|}n|j||d
d|�dS(NR4s %s "{}": must be %s%s or %ss, i����it,R<t	ambiguoustbadR?(R@R'R;RR*R8(RR+R,R9R:R4terrmsg2((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckEnumParam�s
c

Os!d|kr|jd�}nd}|dkr<|j}nd|krZ|jd�}nt}x||D]t}t}|}	t|t�r�|	r�|	tk	r�t|�|j}t	}	q�n|j
|||d|d|	|�qgW|j||dddd|�|j||dddd|�dS(	NR-R5R t6xR4sbad screen distance "6x"R?sbad screen distance "spam"(R@R't_conv_pixelsRIR$RRRR
R
R/R8(
RR+R,R9R:R-R5RR tconv1((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckPixelsParam�s*

c	CsZ|j||dddddd�d}tdkr=d}n|j||d
d|�dS(
NtflattgroovetraisedtridgetsolidtsunkensHbad relief "spam": must be flat, groove, raised, ridge, solid, or sunkeniiR?R4(ii(R;RR'R8(RR+R,R4((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckReliefParam�s	cCs[tjd|jdd�}|j|||dt�|j||ddd�d||<dS(	NtmasterR,timage1R-R?R4simage "spam" doesn't existR<(R%t
PhotoImageRR/RR8(RR+R,timage((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckImageParam�s
cCs|j|||dt�dS(NR-(R/R(RR+R,tvar((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckVariableParam�scCs�|j|�|j|t�t|�dkrF|jd|f�nx5|D]-}t|t�sM|jd|f�PqMqMWdS(NisInvalid bounding box: %r(tassertIsNotNonetassertIsInstanceRR*tfailRR(Rtbboxtitem((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytassertIsBoundingBox�s

cCs|j�}|j�}t|t�sL|jt|�t|j���nx|D]}||qSWtjj	ridd6dd6dd6dd6d	d
6}t
|�}t
|j�}x_t||�D]J}||ko�|||ko�|||ks�d|jj
|fGHq�q�WndS(Ntborderwidthtbdt
backgroundtbgt
foregroundtfgtinvalidcommandtinvcmdtvalidatecommandtvcmds%s.OPTIONS doesn't contain "%s"(tcreatetkeysRRRtsortedR)ttestttest_supporttverbosetsettOPTIONSt	__class__t__name__(RR+R�tktaliasesR ((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_keys�s*%

N(!R�t
__module__tstaticmethodtpixels_roundRbR't_conv_pad_pixelsRHRtpropertyR
Rtobjectt__eq__R#R$R/RIR8R;R>RARJRRRWR[R`RdRkRpRrRxR�(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyRs0						
					
			
tStandardOptionsTestsc*BseZdbZd*�Zd+�Zd,�Zd-�Zd.�Zd/�Zd0�Z	d1�Z
d2�Zd3�Zd4�Z
d5�Zd6�Zd7�Zd8�Zd9�Zejejd:kd;�d<��Zd=�Zd>�Zd?�Zd@�ZdA�ZdB�ZdC�ZdD�ZdE�Z dF�Z!dG�Z"dH�Z#dI�Z$dJ�Z%dK�Z&dL�Z'dM�Z(dN�Z)dO�Z*dP�Z+dQ�Z,dR�Z-dS�Z.dT�Z/dU�Z0dV�Z1dW�Z2dX�Z3dY�Z4dZ�Z5d[�Z6d\�Z7e8d]d^�d_��Z9e8d]d^�d`��Z:da�Z;RS(ctactivebackgroundtactiveborderwidthtactiveforegroundtanchorR{tbitmapRytcompoundtcursortdisabledforegroundtexportselectiontfontR}thighlightbackgroundthighlightcolorthighlightthicknessRotinsertbackgroundtinsertborderwidtht
insertofftimetinsertontimetinsertwidthtjumptjustifytorienttpadxtpadytrelieftrepeatdelaytrepeatintervaltselectbackgroundtselectborderwidthtselectforegroundtsetgridt	takefocusttextttextvariablettroughcolort	underlinet
wraplengthtxscrollcommandtyscrollcommandcCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activebackground
sc	Cs2|j�}|j|ddddddd�dS(NR�ig�������?g333333@ii����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activeborderwidthscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activeforegroundscCs;|j�}|j|ddddddddd	d
�dS(NR�tntnetetsetstswtwtnwtcenter(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_anchorscCsB|j�}|j|d�d|jkr>|j|d�ndS(NR{R|(R�RRR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_backgroundscCs�|j�}|j|dd�|j|dd�tjjddd�}|j|dd|�d|jjjd	d
�ko�d|jj�ks�|j	|ddd
d�ndS(NR�t	questheadtgray50s
python.xbmtsubdirt
imghdrdatat@taquaRtwindowingsystemtAppKitR?R4sbitmap "spam" not defined(
R�R/R�R�tfindfileRRRtwinfo_serverR8(RR+tfilename((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_bitmap%sc	Csf|j�}|j|ddddddd�d|jkrb|j|ddddddd�ndS(	NRyig�������?g������@ii����R=Rz(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_borderwidth2s
c	Cs2|j�}|j|ddddddd�dS(NR�tbottomR�tleftRVtrightttop(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_compound9scCs |j�}|j|d�dS(NR�(R�RW(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_cursor>scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_disabledforegroundBscCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_exportselectionFscCs<|j�}|j|dd�|j|dddd�dS(NR�s3-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*R<R4sfont "" doesn't exist(R�R/R8(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_fontJs
cCsB|j�}|j|d�d|jkr>|j|d�ndS(NR}R~(R�RRR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_foregroundQscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightbackgroundWscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightcolor[scCsQ|j�}|j|dddddd�|j|ddddd	|j�dS(
NR�ig�������?g������@iR=i����R R-(R�RdR/Rb(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightthickness_s
tdarwins"crashes with Cocoa Tk (issue19733)cCs |j�}|j|d�dS(NRo(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_imagefscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertbackgroundlsc	Cs2|j�}|j|ddddddd�dS(NR�ig�������?g������@ii����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertborderwidthpscCs#|j�}|j|dd�dS(NR�id(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertofftimeuscCs#|j�}|j|dd�dS(NR�id(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertontimeyscCs,|j�}|j|ddddd�dS(NR�g�������?g������@i����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertwidth}scCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_jump�scCsH|j�}|j|dddddd�|j|dddd�dS(	NR�R�R�R�R4s6bad justification "{}": must be left, right, or centerR<s:ambiguous justification "": must be left, right, or center(R�R`R8(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_justify�s
cCsC|j�}|jt|d�|j�|j|ddd�dS(NR�t
horizontaltvertical(R�RRtdefault_orientR`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_orient�sc
Cs8|j�}|j|ddddddd|j�dS(NR�ig������@gffffff@i����t12mR-(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_padx�sc
Cs8|j�}|j|ddddddd|j�dS(NR�ig������@gffffff@i����R�R-(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_pady�scCs |j�}|j|d�dS(NR�(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_relief�scCs&|j�}|j|ddd�dS(NR�i���i�(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_repeatdelay�scCs&|j�}|j|ddd�dS(NR�i���i�(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_repeatinterval�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectbackground�scCs,|j�}|j|ddddd�dS(NR�g�������?g������@i����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectborderwidth�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectforeground�scCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_setgrid�scCs)|j�}|j|dddd�dS(Ntstatetactivetdisabledtnormal(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_state�scCs)|j�}|j|dddd�dS(NR�t0t1R<(R�R;(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_takefocus�scCs&|j�}|j|ddd�dS(NR�R<s
any string(R�R;(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_text�scCs5|j�}tj|j�}|j|d|�dS(NR�(R�R%t	StringVarRRr(RR+Rq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_textvariable�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_troughcolor�scCs)|j�}|j|dddd�dS(NR�iii
(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_underline�scCs#|j�}|j|dd�dS(NR�id(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_wraplength�scCs |j�}|j|d�dS(NR�(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_xscrollcommand�scCs |j�}|j|d�dS(NR�(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_yscrollcommand�scCs |j�}|j|d�dS(NRY(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_command�scCs |j�}|j|d�dS(Ntindicatoron(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_indicatoron�scCs |j�}|j|d�dS(Nt	offrelief(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_offrelief�scCs |j�}|j|d�dS(Nt
overrelief(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_overrelief�scCs |j�}|j|d�dS(Ntselectcolor(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectcolor�scCs |j�}|j|d�dS(Ntselectimage(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectimage�siicCs |j�}|j|d�dS(Nt
tristateimage(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_tristateimage�scCs#|j�}|j|dd�dS(Nt
tristatevaluet
unknowable(R�R/(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_tristatevalue�scCs5|j�}tj|j�}|j|d|�dS(Ntvariable(R�R%t	DoubleVarRRr(RR+Rq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_variables(*R�R�R�R�R{R�RyR�R�R�R�R�R}R�R�R�RoR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�(<R�R�tSTANDARD_OPTIONSR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�tunittesttskipIftsystplatformR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�RRRRRR	R
RRR
RRRRRRRRR(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR��s�						
																																											tIntegerSizeTestscBseZd�Zd�ZRS(cCs)|j�}|j|dddd�dS(Ntheightidi����i(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_height	scCs)|j�}|j|dddd�dS(Ntwidthi�in���i(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_width
s(R�R�R'R)(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR%s	tPixelSizeTestscBseZd�Zd�ZRS(c	Cs2|j�}|j|ddddddd�dS(NR&idg�����LY@gfffff�Y@i����it3c(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR'sc	Cs2|j�}|j|ddddddd�dS(NR(i�gfffff6y@g�����Iy@in���it5i(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR)s(R�R�R'R)(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR*s	cs�fd�}|S(Ncs�x��jD]�}d|}t�|�s
xk�D]5}t||�r0t�|t||�j�Pq0q0W|�fd�}||_t�||�q
q
W�S(Nttest_cs1|j�}||td|�jf��dS(NsOption "%s" is not tested in %s(R�tAssertionErrorR�(RtoptionR+(tcls(s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR�)s(R�thasattrtsetattrtgetattrtim_funcR�(R0R/t
methodnametsource_classR�(tsource_classes(R0s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	decorators

		((R7R8((R7s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytadd_standard_optionsscCs4tjjr0tj�}dG|jdd�GHndS(Nspatchlevel =tinfot
patchlevel(R�R�R�R%tTclR(ttcl((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytsetUpModule3s(R!R#tTkinterR%tttkRttest_ttk.supportRRRRRRttest.test_supportR�RHtnoconvtnoconv_methRR�R
R�RR�R$RR�R%R*R9R>(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt<module>s*.
				��

	PK'/�Z�T��++runtktests.pyonu�[����
zfc@s�dZddlZddlZddlZddlZddlZejjejj	e
��Zd�Zee
dd�Ze
e
dd�Zedkr�ejje��ndS(s�
Use this module to get and run all tk tests.

Tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
i����NcCs.x'tj|�D]}|dkrtSqWtS(Ns__init__.pys__init__.pycs
__init.pyo(s__init__.pys__init__.pycs
__init.pyo(tostlistdirtTruetFalse(tpathtname((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt
is_packagesc	#s-d�x tj|�D]\}}}x4t|�D]&}|ddkr2|j|�q2q2Wt|�r|r|t|�ttj�jdd�}|r�||kr�qnt�fd�|�}x[|D]P}y$t	j
d|t�� |�VWq�tjj
k
r|r�qq�Xq�WqqWdS(s�This will import and yield modules whose names start with test_
    and are inside packages found in the path starting at basepath.

    If packages is specified it should contain package names that want
    their tests collected.
    s.pyit.t/cs|jd�o|j��S(Nttest_(t
startswithtendswith(tx(tpy_ext(s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt<lambda>+ts.%sN(RtwalktlisttremoveRtlentseptreplacetfiltert	importlibt
import_modulettestttest_supporttResourceDenied(	tbasepathtguitpackagestdirpathtdirnamest	filenamestdirnametpkg_nameR((R
s./usr/lib64/python2.7/lib-tk/test/runtktests.pytget_tests_moduless&)	
ccs�g}|r|jd�n|r2|jd�nxPtd|d|�D]9}x0|D](}xt||d�D]}|VqnWqUWqHWdS(s�Yield all the tests in the modules found by get_tests_modules.

    If nogui is True, only tests that do not require a GUI will be
    returned.ttests_noguit	tests_guiRRN((tappendR$tgetattr(ttextRRtattrstmoduletattrR((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt	get_tests6s
t__main__(t__doc__RtsystunittestRttest.test_supportRRtabspathR"t__file__t
this_dir_pathRRtNoneR$R-t__name__Rtrun_unittest(((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt<module>s	PK'/�Zש�mPmPwidget_tests.pynu�[���# Common tests for test_tkinter/test_widgets.py and test_ttk/test_widgets.py

import unittest
import sys
import Tkinter as tkinter
from ttk import Scale
from test_ttk.support import (AbstractTkTest, tcl_version, requires_tcl,
                              get_tk_patchlevel, pixels_conv, tcl_obj_eq)
import test.test_support


noconv = noconv_meth = False
if get_tk_patchlevel() < (8, 5, 11):
    noconv = str
noconv_meth = noconv and staticmethod(noconv)

def int_round(x):
    return int(round(x))

pixels_round = int_round
if get_tk_patchlevel()[:3] == (8, 5, 11):
    # Issue #19085: Workaround a bug in Tk
    # http://core.tcl.tk/tk/info/3497848
    pixels_round = int


_sentinel = object()

class AbstractWidgetTest(AbstractTkTest):
    _conv_pixels = staticmethod(pixels_round)
    _conv_pad_pixels = None
    _stringify = False

    @property
    def scaling(self):
        try:
            return self._scaling
        except AttributeError:
            self._scaling = float(self.root.call('tk', 'scaling'))
            return self._scaling

    def _str(self, value):
        if not self._stringify and self.wantobjects and tcl_version >= (8, 6):
            return value
        if isinstance(value, tuple):
            return ' '.join(map(self._str, value))
        return str(value)

    def assertEqual2(self, actual, expected, msg=None, eq=object.__eq__):
        if eq(actual, expected):
            return
        self.assertEqual(actual, expected, msg)

    def checkParam(self, widget, name, value, expected=_sentinel,
                   conv=False, eq=None):
        widget[name] = value
        if expected is _sentinel:
            expected = value
        if conv:
            expected = conv(expected)
        if self._stringify or not self.wantobjects:
            if isinstance(expected, tuple):
                expected = tkinter._join(expected)
            else:
                expected = str(expected)
        if eq is None:
            eq = tcl_obj_eq
        self.assertEqual2(widget[name], expected, eq=eq)
        self.assertEqual2(widget.cget(name), expected, eq=eq)
        # XXX
        if not isinstance(widget, Scale):
            t = widget.configure(name)
            self.assertEqual(len(t), 5)
            self.assertEqual2(t[4], expected, eq=eq)

    def checkInvalidParam(self, widget, name, value, errmsg=None,
                          keep_orig=True):
        orig = widget[name]
        if errmsg is not None:
            errmsg = errmsg.format(value)
        with self.assertRaises(tkinter.TclError) as cm:
            widget[name] = value
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)
        if keep_orig:
            self.assertEqual(widget[name], orig)
        else:
            widget[name] = orig
        with self.assertRaises(tkinter.TclError) as cm:
            widget.configure({name: value})
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)
        if keep_orig:
            self.assertEqual(widget[name], orig)
        else:
            widget[name] = orig

    def checkParams(self, widget, name, *values, **kwargs):
        for value in values:
            self.checkParam(widget, name, value, **kwargs)

    def checkIntegerParam(self, widget, name, *values, **kwargs):
        self.checkParams(widget, name, *values, **kwargs)
        self.checkInvalidParam(widget, name, '',
                errmsg='expected integer but got ""')
        self.checkInvalidParam(widget, name, '10p',
                errmsg='expected integer but got "10p"')
        self.checkInvalidParam(widget, name, 3.2,
                errmsg='expected integer but got "3.2"')

    def checkFloatParam(self, widget, name, *values, **kwargs):
        if 'conv' in kwargs:
            conv = kwargs.pop('conv')
        else:
            conv = float
        for value in values:
            self.checkParam(widget, name, value, conv=conv, **kwargs)
        self.checkInvalidParam(widget, name, '',
                errmsg='expected floating-point number but got ""')
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='expected floating-point number but got "spam"')

    def checkBooleanParam(self, widget, name):
        for value in (False, 0, 'false', 'no', 'off'):
            self.checkParam(widget, name, value, expected=0)
        for value in (True, 1, 'true', 'yes', 'on'):
            self.checkParam(widget, name, value, expected=1)
        self.checkInvalidParam(widget, name, '',
                errmsg='expected boolean value but got ""')
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='expected boolean value but got "spam"')

    def checkColorParam(self, widget, name, allow_empty=None, **kwargs):
        self.checkParams(widget, name,
                         '#ff0000', '#00ff00', '#0000ff', '#123456',
                         'red', 'green', 'blue', 'white', 'black', 'grey',
                         **kwargs)
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='unknown color name "spam"')

    def checkCursorParam(self, widget, name, **kwargs):
        self.checkParams(widget, name, 'arrow', 'watch', 'cross', '',**kwargs)
        if tcl_version >= (8, 5):
            self.checkParam(widget, name, 'none')
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='bad cursor spec "spam"')

    def checkCommandParam(self, widget, name):
        def command(*args):
            pass
        widget[name] = command
        self.assertTrue(widget[name])
        self.checkParams(widget, name, '')

    def checkEnumParam(self, widget, name, *values, **kwargs):
        if 'errmsg' in kwargs:
            errmsg = kwargs.pop('errmsg')
        else:
            errmsg = None
        self.checkParams(widget, name, *values, **kwargs)
        if errmsg is None:
            errmsg2 = ' %s "{}": must be %s%s or %s' % (
                    name,
                    ', '.join(values[:-1]),
                    ',' if len(values) > 2 else '',
                    values[-1])
            self.checkInvalidParam(widget, name, '',
                                   errmsg='ambiguous' + errmsg2)
            errmsg = 'bad' + errmsg2
        self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg)

    def checkPixelsParam(self, widget, name, *values, **kwargs):
        if 'conv' in kwargs:
            conv = kwargs.pop('conv')
        else:
            conv = None
        if conv is None:
            conv = self._conv_pixels
        if 'keep_orig' in kwargs:
            keep_orig = kwargs.pop('keep_orig')
        else:
            keep_orig = True
        for value in values:
            expected = _sentinel
            conv1 = conv
            if isinstance(value, str):
                if conv1 and conv1 is not str:
                    expected = pixels_conv(value) * self.scaling
                    conv1 = int_round
            self.checkParam(widget, name, value, expected=expected,
                            conv=conv1, **kwargs)
        self.checkInvalidParam(widget, name, '6x',
                errmsg='bad screen distance "6x"', keep_orig=keep_orig)
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='bad screen distance "spam"', keep_orig=keep_orig)

    def checkReliefParam(self, widget, name):
        self.checkParams(widget, name,
                         'flat', 'groove', 'raised', 'ridge', 'solid', 'sunken')
        errmsg='bad relief "spam": must be '\
               'flat, groove, raised, ridge, solid, or sunken'
        if tcl_version < (8, 6):
            errmsg = None
        self.checkInvalidParam(widget, name, 'spam',
                errmsg=errmsg)

    def checkImageParam(self, widget, name):
        image = tkinter.PhotoImage(master=self.root, name='image1')
        self.checkParam(widget, name, image, conv=str)
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='image "spam" doesn\'t exist')
        widget[name] = ''

    def checkVariableParam(self, widget, name, var):
        self.checkParam(widget, name, var, conv=str)

    def assertIsBoundingBox(self, bbox):
        self.assertIsNotNone(bbox)
        self.assertIsInstance(bbox, tuple)
        if len(bbox) != 4:
            self.fail('Invalid bounding box: %r' % (bbox,))
        for item in bbox:
            if not isinstance(item, int):
                self.fail('Invalid bounding box: %r' % (bbox,))
                break

    def test_keys(self):
        widget = self.create()
        keys = widget.keys()
        # XXX
        if not isinstance(widget, Scale):
            self.assertEqual(sorted(keys), sorted(widget.configure()))
        for k in keys:
            widget[k]
        # Test if OPTIONS contains all keys
        if test.test_support.verbose:
            aliases = {
                'bd': 'borderwidth',
                'bg': 'background',
                'fg': 'foreground',
                'invcmd': 'invalidcommand',
                'vcmd': 'validatecommand',
            }
            keys = set(keys)
            expected = set(self.OPTIONS)
            for k in sorted(keys - expected):
                if not (k in aliases and
                        aliases[k] in keys and
                        aliases[k] in expected):
                    print('%s.OPTIONS doesn\'t contain "%s"' %
                          (self.__class__.__name__, k))


class StandardOptionsTests(object):
    STANDARD_OPTIONS = (
        'activebackground', 'activeborderwidth', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth', 'compound', 'cursor',
        'disabledforeground', 'exportselection', 'font', 'foreground',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'insertbackground', 'insertborderwidth',
        'insertofftime', 'insertontime', 'insertwidth',
        'jump', 'justify', 'orient', 'padx', 'pady', 'relief',
        'repeatdelay', 'repeatinterval',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'setgrid', 'takefocus', 'text', 'textvariable', 'troughcolor',
        'underline', 'wraplength', 'xscrollcommand', 'yscrollcommand',
    )

    def test_activebackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'activebackground')

    def test_activeborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'activeborderwidth',
                              0, 1.3, 2.9, 6, -2, '10p')

    def test_activeforeground(self):
        widget = self.create()
        self.checkColorParam(widget, 'activeforeground')

    def test_anchor(self):
        widget = self.create()
        self.checkEnumParam(widget, 'anchor',
                'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center')

    def test_background(self):
        widget = self.create()
        self.checkColorParam(widget, 'background')
        if 'bg' in self.OPTIONS:
            self.checkColorParam(widget, 'bg')

    def test_bitmap(self):
        widget = self.create()
        self.checkParam(widget, 'bitmap', 'questhead')
        self.checkParam(widget, 'bitmap', 'gray50')
        filename = test.test_support.findfile('python.xbm', subdir='imghdrdata')
        self.checkParam(widget, 'bitmap', '@' + filename)
        # Cocoa Tk widgets don't detect invalid -bitmap values
        # See https://core.tcl.tk/tk/info/31cd33dbf0
        if not ('aqua' in self.root.tk.call('tk', 'windowingsystem') and
                'AppKit' in self.root.winfo_server()):
            self.checkInvalidParam(widget, 'bitmap', 'spam',
                    errmsg='bitmap "spam" not defined')

    def test_borderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'borderwidth',
                              0, 1.3, 2.6, 6, -2, '10p')
        if 'bd' in self.OPTIONS:
            self.checkPixelsParam(widget, 'bd', 0, 1.3, 2.6, 6, -2, '10p')

    def test_compound(self):
        widget = self.create()
        self.checkEnumParam(widget, 'compound',
                'bottom', 'center', 'left', 'none', 'right', 'top')

    def test_cursor(self):
        widget = self.create()
        self.checkCursorParam(widget, 'cursor')

    def test_disabledforeground(self):
        widget = self.create()
        self.checkColorParam(widget, 'disabledforeground')

    def test_exportselection(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'exportselection')

    def test_font(self):
        widget = self.create()
        self.checkParam(widget, 'font',
                        '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*')
        self.checkInvalidParam(widget, 'font', '',
                               errmsg='font "" doesn\'t exist')

    def test_foreground(self):
        widget = self.create()
        self.checkColorParam(widget, 'foreground')
        if 'fg' in self.OPTIONS:
            self.checkColorParam(widget, 'fg')

    def test_highlightbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'highlightbackground')

    def test_highlightcolor(self):
        widget = self.create()
        self.checkColorParam(widget, 'highlightcolor')

    def test_highlightthickness(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'highlightthickness',
                              0, 1.3, 2.6, 6, '10p')
        self.checkParam(widget, 'highlightthickness', -2, expected=0,
                        conv=self._conv_pixels)

    @unittest.skipIf(sys.platform == 'darwin',
                     'crashes with Cocoa Tk (issue19733)')
    def test_image(self):
        widget = self.create()
        self.checkImageParam(widget, 'image')

    def test_insertbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'insertbackground')

    def test_insertborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'insertborderwidth',
                              0, 1.3, 2.6, 6, -2, '10p')

    def test_insertofftime(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'insertofftime', 100)

    def test_insertontime(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'insertontime', 100)

    def test_insertwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'insertwidth', 1.3, 2.6, -2, '10p')

    def test_jump(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'jump')

    def test_justify(self):
        widget = self.create()
        self.checkEnumParam(widget, 'justify', 'left', 'right', 'center',
                errmsg='bad justification "{}": must be '
                       'left, right, or center')
        self.checkInvalidParam(widget, 'justify', '',
                errmsg='ambiguous justification "": must be '
                       'left, right, or center')

    def test_orient(self):
        widget = self.create()
        self.assertEqual(str(widget['orient']), self.default_orient)
        self.checkEnumParam(widget, 'orient', 'horizontal', 'vertical')

    def test_padx(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, -2, '12m',
                              conv=self._conv_pad_pixels)

    def test_pady(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, -2, '12m',
                              conv=self._conv_pad_pixels)

    def test_relief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'relief')

    def test_repeatdelay(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'repeatdelay', -500, 500)

    def test_repeatinterval(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'repeatinterval', -500, 500)

    def test_selectbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'selectbackground')

    def test_selectborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'selectborderwidth', 1.3, 2.6, -2, '10p')

    def test_selectforeground(self):
        widget = self.create()
        self.checkColorParam(widget, 'selectforeground')

    def test_setgrid(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'setgrid')

    def test_state(self):
        widget = self.create()
        self.checkEnumParam(widget, 'state', 'active', 'disabled', 'normal')

    def test_takefocus(self):
        widget = self.create()
        self.checkParams(widget, 'takefocus', '0', '1', '')

    def test_text(self):
        widget = self.create()
        self.checkParams(widget, 'text', '', 'any string')

    def test_textvariable(self):
        widget = self.create()
        var = tkinter.StringVar(self.root)
        self.checkVariableParam(widget, 'textvariable', var)

    def test_troughcolor(self):
        widget = self.create()
        self.checkColorParam(widget, 'troughcolor')

    def test_underline(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'underline', 0, 1, 10)

    def test_wraplength(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'wraplength', 100)

    def test_xscrollcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'xscrollcommand')

    def test_yscrollcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'yscrollcommand')

    # non-standard but common options

    def test_command(self):
        widget = self.create()
        self.checkCommandParam(widget, 'command')

    def test_indicatoron(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'indicatoron')

    def test_offrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'offrelief')

    def test_overrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'overrelief')

    def test_selectcolor(self):
        widget = self.create()
        self.checkColorParam(widget, 'selectcolor')

    def test_selectimage(self):
        widget = self.create()
        self.checkImageParam(widget, 'selectimage')

    @requires_tcl(8, 5)
    def test_tristateimage(self):
        widget = self.create()
        self.checkImageParam(widget, 'tristateimage')

    @requires_tcl(8, 5)
    def test_tristatevalue(self):
        widget = self.create()
        self.checkParam(widget, 'tristatevalue', 'unknowable')

    def test_variable(self):
        widget = self.create()
        var = tkinter.DoubleVar(self.root)
        self.checkVariableParam(widget, 'variable', var)


class IntegerSizeTests(object):
    def test_height(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'height', 100, -100, 0)

    def test_width(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'width', 402, -402, 0)


class PixelSizeTests(object):
    def test_height(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '3c')

    def test_width(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i')


def add_standard_options(*source_classes):
    # This decorator adds test_xxx methods from source classes for every xxx
    # option in the OPTIONS class attribute if they are not defined explicitly.
    def decorator(cls):
        for option in cls.OPTIONS:
            methodname = 'test_' + option
            if not hasattr(cls, methodname):
                for source_class in source_classes:
                    if hasattr(source_class, methodname):
                        setattr(cls, methodname,
                                getattr(source_class, methodname).im_func)
                        break
                else:
                    def test(self, option=option):
                        widget = self.create()
                        widget[option]
                        raise AssertionError('Option "%s" is not tested in %s' %
                                             (option, cls.__name__))
                    test.__name__ = methodname
                    setattr(cls, methodname, test)
        return cls
    return decorator

def setUpModule():
    if test.test_support.verbose:
        tcl = tkinter.Tcl()
        print 'patchlevel =', tcl.call('info', 'patchlevel')
PK'/�Z���66READMEnu�[���Writing new tests
=================

Precaution
----------

    New tests should always use only one Tk window at once, like all the
    current tests do. This means that you have to destroy the current window
    before creating another one, and clean up after the test. The motivation
    behind this is that some tests may depend on having its window focused
    while it is running to work properly, and it may be hard to force focus
    on your window across platforms (right now only test_traversal at
    test_ttk.test_widgets.NotebookTest depends on this).

PK'/�Z��Mf}g}gwidget_tests.pycnu�[����
zfc@sVddlZddlZddlZddlmZddlmZmZm	Z	m
Z
mZmZddl
ZeZZe
�dddfkr�eZneo�ee�Zd�ZeZe
�d dddfkr�eZne�Zd	efd
��YZdefd��YZd
efd��YZdefd��YZd�Zd�ZdS(i����N(tScale(tAbstractTkTestttcl_versiontrequires_tcltget_tk_patchleveltpixels_convt
tcl_obj_eqiiicCstt|��S(N(tinttround(tx((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	int_roundsitAbstractWidgetTestcBs�eZee�ZdZeZe	d��Z
d�Zdej
d�Zeedd�Zded�Zd�Zd�Zd�Zd�Zdd	�Zd
�Zd�Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Z RS(cCsEy|jSWn3tk
r@t|jjdd��|_|jSXdS(Nttktscaling(t_scalingtAttributeErrortfloattroottcall(tself((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR
"s

cCsU|jr#|jr#tdkr#|St|t�rKdjt|j|��St|�S(Niit (ii(	t
_stringifytwantobjectsRt
isinstancettupletjointmapt_strtstr(Rtvalue((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR*s
cCs*|||�rdS|j|||�dS(N(tassertEqual(Rtactualtexpectedtmsgteq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytassertEqual21scCs|||<|tkr|}n|r4||�}n|jsG|jrwt|t�rhtj|�}qwt|�}n|dkr�t	}n|j
|||d|�|j
|j|�|d|�t|t�s|j
|�}|jt|�d�|j
|d|d|�ndS(NR"ii(t	_sentinelRRRRttkintert_joinRtNoneRR#tcgetRt	configureRtlen(RtwidgettnameRR tconvR"tt((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
checkParam6s"
		c	Cs||}|dk	r(|j|�}n|jtj��}|||<WdQX|dk	ru|jt|j�|�n|r�|j|||�n
|||<|jtj��}|ji||6�WdQX|dk	r�|jt|j�|�n|r|j|||�n
|||<dS(N(	R'tformattassertRaisesR%tTclErrorRRt	exceptionR)(RR+R,Rterrmsgt	keep_origtorigtcm((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckInvalidParamLs"

cOs+x$|D]}|j||||�qWdS(N(R/(RR+R,tvaluestkwargsR((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckParamsbs
cOse|j||||�|j||ddd�|j||ddd�|j||ddd�dS(NtR4sexpected integer but got ""t10psexpected integer but got "10p"g������	@sexpected integer but got "3.2"(R;R8(RR+R,R9R:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckIntegerParamfscOs�d|kr|jd�}nt}x*|D]"}|j|||d||�q+W|j||ddd�|j||ddd�dS(NR-R<R4s)expected floating-point number but got ""tspams-expected floating-point number but got "spam"(tpopRR/R8(RR+R,R9R:R-R((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckFloatParamos
 cCs�x6tddddfD]}|j|||dd�qWx6tdddd	fD]}|j|||dd�qOW|j||d
dd�|j||d
dd�dS(NitfalsetnotoffR ittruetyestonR<R4s!expected boolean value but got ""R?s%expected boolean value but got "spam"(tFalseR/tTrueR8(RR+R,R((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckBooleanParam{scKsN|j||ddddddddd	d
|�|j||ddd
�dS(Ns#ff0000s#00ff00s#0000ffs#123456tredtgreentbluetwhitetblacktgreyR?R4sunknown color name "spam"(R;R8(RR+R,tallow_emptyR:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckColorParam�scKs^|j||dddd|�tdkrA|j||d�n|j||dd	d
�dS(NtarrowtwatchtcrossR<iitnoneR?R4sbad cursor spec "spam"(ii(R;RR/R8(RR+R,R:((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckCursorParam�s
cCs;d�}|||<|j||�|j||d�dS(NcWsdS(N((targs((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcommand�sR<(t
assertTrueR;(RR+R,RY((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckCommandParam�s	
cOs�d|kr|jd�}nd}|j||||�|dkr�d|dj|d �t|�dkrtdnd|df}|j||ddd|�d	|}n|j||d
d|�dS(NR4s %s "{}": must be %s%s or %ss, i����it,R<t	ambiguoustbadR?(R@R'R;RR*R8(RR+R,R9R:R4terrmsg2((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckEnumParam�s
c

Os!d|kr|jd�}nd}|dkr<|j}nd|krZ|jd�}nt}x||D]t}t}|}	t|t�r�|	r�|	tk	r�t|�|j}t	}	q�n|j
|||d|d|	|�qgW|j||dddd|�|j||dddd|�dS(	NR-R5R t6xR4sbad screen distance "6x"R?sbad screen distance "spam"(R@R't_conv_pixelsRIR$RRRR
R
R/R8(
RR+R,R9R:R-R5RR tconv1((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckPixelsParam�s*

c	CsZ|j||dddddd�d}tdkr=d}n|j||d
d|�dS(
NtflattgroovetraisedtridgetsolidtsunkensHbad relief "spam": must be flat, groove, raised, ridge, solid, or sunkeniiR?R4(ii(R;RR'R8(RR+R,R4((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckReliefParam�s	cCs[tjd|jdd�}|j|||dt�|j||ddd�d||<dS(	NtmasterR,timage1R-R?R4simage "spam" doesn't existR<(R%t
PhotoImageRR/RR8(RR+R,timage((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckImageParam�s
cCs|j|||dt�dS(NR-(R/R(RR+R,tvar((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytcheckVariableParam�scCs�|j|�|j|t�t|�dkrF|jd|f�nx5|D]-}t|t�sM|jd|f�PqMqMWdS(NisInvalid bounding box: %r(tassertIsNotNonetassertIsInstanceRR*tfailRR(Rtbboxtitem((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytassertIsBoundingBox�s

cCs|j�}|j�}t|t�sL|jt|�t|j���nx|D]}||qSWtjj	ridd6dd6dd6dd6d	d
6}t
|�}t
|j�}x_t||�D]J}||ko�|||ko�|||ks�d|jj
|fGHq�q�WndS(Ntborderwidthtbdt
backgroundtbgt
foregroundtfgtinvalidcommandtinvcmdtvalidatecommandtvcmds%s.OPTIONS doesn't contain "%s"(tcreatetkeysRRRtsortedR)ttestttest_supporttverbosetsettOPTIONSt	__class__t__name__(RR+R�tktaliasesR ((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_keys�s*%

N(!R�t
__module__tstaticmethodtpixels_roundRbR't_conv_pad_pixelsRHRtpropertyR
Rtobjectt__eq__R#R$R/RIR8R;R>RARJRRRWR[R`RdRkRpRrRxR�(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyRs0						
					
			
tStandardOptionsTestsc*BseZdbZd*�Zd+�Zd,�Zd-�Zd.�Zd/�Zd0�Z	d1�Z
d2�Zd3�Zd4�Z
d5�Zd6�Zd7�Zd8�Zd9�Zejejd:kd;�d<��Zd=�Zd>�Zd?�Zd@�ZdA�ZdB�ZdC�ZdD�ZdE�Z dF�Z!dG�Z"dH�Z#dI�Z$dJ�Z%dK�Z&dL�Z'dM�Z(dN�Z)dO�Z*dP�Z+dQ�Z,dR�Z-dS�Z.dT�Z/dU�Z0dV�Z1dW�Z2dX�Z3dY�Z4dZ�Z5d[�Z6d\�Z7e8d]d^�d_��Z9e8d]d^�d`��Z:da�Z;RS(ctactivebackgroundtactiveborderwidthtactiveforegroundtanchorR{tbitmapRytcompoundtcursortdisabledforegroundtexportselectiontfontR}thighlightbackgroundthighlightcolorthighlightthicknessRotinsertbackgroundtinsertborderwidtht
insertofftimetinsertontimetinsertwidthtjumptjustifytorienttpadxtpadytrelieftrepeatdelaytrepeatintervaltselectbackgroundtselectborderwidthtselectforegroundtsetgridt	takefocusttextttextvariablettroughcolort	underlinet
wraplengthtxscrollcommandtyscrollcommandcCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activebackground
sc	Cs2|j�}|j|ddddddd�dS(NR�ig�������?g333333@ii����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activeborderwidthscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_activeforegroundscCs;|j�}|j|ddddddddd	d
�dS(NR�tntnetetsetstswtwtnwtcenter(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_anchorscCsB|j�}|j|d�d|jkr>|j|d�ndS(NR{R|(R�RRR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_backgroundscCs�|j�}|j|dd�|j|dd�tjjddd�}|j|dd|�d|jjjd	d
�ko�d|jj�ks�|j	|ddd
d�ndS(NR�t	questheadtgray50s
python.xbmtsubdirt
imghdrdatat@taquaRtwindowingsystemtAppKitR?R4sbitmap "spam" not defined(
R�R/R�R�tfindfileRRRtwinfo_serverR8(RR+tfilename((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_bitmap%sc	Csf|j�}|j|ddddddd�d|jkrb|j|ddddddd�ndS(	NRyig�������?g������@ii����R=Rz(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_borderwidth2s
c	Cs2|j�}|j|ddddddd�dS(NR�tbottomR�tleftRVtrightttop(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_compound9scCs |j�}|j|d�dS(NR�(R�RW(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_cursor>scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_disabledforegroundBscCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_exportselectionFscCs<|j�}|j|dd�|j|dddd�dS(NR�s3-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*R<R4sfont "" doesn't exist(R�R/R8(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_fontJs
cCsB|j�}|j|d�d|jkr>|j|d�ndS(NR}R~(R�RRR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_foregroundQscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightbackgroundWscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightcolor[scCsQ|j�}|j|dddddd�|j|ddddd	|j�dS(
NR�ig�������?g������@iR=i����R R-(R�RdR/Rb(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_highlightthickness_s
tdarwins"crashes with Cocoa Tk (issue19733)cCs |j�}|j|d�dS(NRo(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_imagefscCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertbackgroundlsc	Cs2|j�}|j|ddddddd�dS(NR�ig�������?g������@ii����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertborderwidthpscCs#|j�}|j|dd�dS(NR�id(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertofftimeuscCs#|j�}|j|dd�dS(NR�id(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertontimeyscCs,|j�}|j|ddddd�dS(NR�g�������?g������@i����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_insertwidth}scCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_jump�scCsH|j�}|j|dddddd�|j|dddd�dS(	NR�R�R�R�R4s6bad justification "{}": must be left, right, or centerR<s:ambiguous justification "": must be left, right, or center(R�R`R8(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_justify�s
cCsC|j�}|jt|d�|j�|j|ddd�dS(NR�t
horizontaltvertical(R�RRtdefault_orientR`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_orient�sc
Cs8|j�}|j|ddddddd|j�dS(NR�ig������@gffffff@i����t12mR-(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_padx�sc
Cs8|j�}|j|ddddddd|j�dS(NR�ig������@gffffff@i����R�R-(R�RdR�(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_pady�scCs |j�}|j|d�dS(NR�(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_relief�scCs&|j�}|j|ddd�dS(NR�i���i�(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_repeatdelay�scCs&|j�}|j|ddd�dS(NR�i���i�(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_repeatinterval�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectbackground�scCs,|j�}|j|ddddd�dS(NR�g�������?g������@i����R=(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectborderwidth�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectforeground�scCs |j�}|j|d�dS(NR�(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_setgrid�scCs)|j�}|j|dddd�dS(Ntstatetactivetdisabledtnormal(R�R`(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_state�scCs)|j�}|j|dddd�dS(NR�t0t1R<(R�R;(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_takefocus�scCs&|j�}|j|ddd�dS(NR�R<s
any string(R�R;(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	test_text�scCs5|j�}tj|j�}|j|d|�dS(NR�(R�R%t	StringVarRRr(RR+Rq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_textvariable�scCs |j�}|j|d�dS(NR�(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_troughcolor�scCs)|j�}|j|dddd�dS(NR�iii
(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_underline�scCs#|j�}|j|dd�dS(NR�id(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_wraplength�scCs |j�}|j|d�dS(NR�(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_xscrollcommand�scCs |j�}|j|d�dS(NR�(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_yscrollcommand�scCs |j�}|j|d�dS(NRY(R�R[(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_command�scCs |j�}|j|d�dS(Ntindicatoron(R�RJ(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_indicatoron�scCs |j�}|j|d�dS(Nt	offrelief(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_offrelief�scCs |j�}|j|d�dS(Nt
overrelief(R�Rk(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_overrelief�scCs |j�}|j|d�dS(Ntselectcolor(R�RR(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectcolor�scCs |j�}|j|d�dS(Ntselectimage(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_selectimage�siicCs |j�}|j|d�dS(Nt
tristateimage(R�Rp(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_tristateimage�scCs#|j�}|j|dd�dS(Nt
tristatevaluet
unknowable(R�R/(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_tristatevalue�scCs5|j�}tj|j�}|j|d|�dS(Ntvariable(R�R%t	DoubleVarRRr(RR+Rq((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_variables(*R�R�R�R�R{R�RyR�R�R�R�R�R}R�R�R�RoR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�(<R�R�tSTANDARD_OPTIONSR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�tunittesttskipIftsystplatformR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�RRRRRR	R
RRR
RRRRRRRRR(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR��s�						
																																											tIntegerSizeTestscBseZd�Zd�ZRS(cCs)|j�}|j|dddd�dS(Ntheightidi����i(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyttest_height	scCs)|j�}|j|dddd�dS(Ntwidthi�in���i(R�R>(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt
test_width
s(R�R�R'R)(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR%s	tPixelSizeTestscBseZd�Zd�ZRS(c	Cs2|j�}|j|ddddddd�dS(NR&idg�����LY@gfffff�Y@i����it3c(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR'sc	Cs2|j�}|j|ddddddd�dS(NR(i�gfffff6y@g�����Iy@in���it5i(R�Rd(RR+((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR)s(R�R�R'R)(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR*s	cs�fd�}|S(Ncs�x��jD]�}d|}t�|�s
xk�D]5}t||�r0t�|t||�j�Pq0q0W|�fd�}||_t�||�q
q
W�S(Nttest_cs1|j�}||td|�jf��dS(NsOption "%s" is not tested in %s(R�tAssertionErrorR�(RtoptionR+(tcls(s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyR�)s(R�thasattrtsetattrtgetattrtim_funcR�(R0R/t
methodnametsource_classR�(tsource_classes(R0s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt	decorators

		((R7R8((R7s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytadd_standard_optionsscCs4tjjr0tj�}dG|jdd�GHndS(Nspatchlevel =tinfot
patchlevel(R�R�R�R%tTclR(ttcl((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pytsetUpModule3s(R!R#tTkinterR%tttkRttest_ttk.supportRRRRRRttest.test_supportR�RHtnoconvtnoconv_methRR�R
R�RR�R$RR�R%R*R9R>(((s0/usr/lib64/python2.7/lib-tk/test/widget_tests.pyt<module>s*.
				��

	PK'/�Z�T��++runtktests.pycnu�[����
zfc@s�dZddlZddlZddlZddlZddlZejjejj	e
��Zd�Zee
dd�Ze
e
dd�Zedkr�ejje��ndS(s�
Use this module to get and run all tk tests.

Tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
i����NcCs.x'tj|�D]}|dkrtSqWtS(Ns__init__.pys__init__.pycs
__init.pyo(s__init__.pys__init__.pycs
__init.pyo(tostlistdirtTruetFalse(tpathtname((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt
is_packagesc	#s-d�x tj|�D]\}}}x4t|�D]&}|ddkr2|j|�q2q2Wt|�r|r|t|�ttj�jdd�}|r�||kr�qnt�fd�|�}x[|D]P}y$t	j
d|t�� |�VWq�tjj
k
r|r�qq�Xq�WqqWdS(s�This will import and yield modules whose names start with test_
    and are inside packages found in the path starting at basepath.

    If packages is specified it should contain package names that want
    their tests collected.
    s.pyit.t/cs|jd�o|j��S(Nttest_(t
startswithtendswith(tx(tpy_ext(s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt<lambda>+ts.%sN(RtwalktlisttremoveRtlentseptreplacetfiltert	importlibt
import_modulettestttest_supporttResourceDenied(	tbasepathtguitpackagestdirpathtdirnamest	filenamestdirnametpkg_nameR((R
s./usr/lib64/python2.7/lib-tk/test/runtktests.pytget_tests_moduless&)	
ccs�g}|r|jd�n|r2|jd�nxPtd|d|�D]9}x0|D](}xt||d�D]}|VqnWqUWqHWdS(s�Yield all the tests in the modules found by get_tests_modules.

    If nogui is True, only tests that do not require a GUI will be
    returned.ttests_noguit	tests_guiRRN((tappendR$tgetattr(ttextRRtattrstmoduletattrR((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt	get_tests6s
t__main__(t__doc__RtsystunittestRttest.test_supportRRtabspathR"t__file__t
this_dir_pathRRtNoneR$R-t__name__Rtrun_unittest(((s./usr/lib64/python2.7/lib-tk/test/runtktests.pyt<module>s	PK'/�Z�V�����test_ttk/test_widgets.pynu�[���import unittest
import Tkinter as tkinter
from Tkinter import TclError
import ttk
from test.test_support import requires, run_unittest, have_unicode, u
import sys

from test_functions import MockTclObj
from support import (AbstractTkTest, tcl_version, get_tk_patchlevel,
                     simulate_mouse_click)
from widget_tests import (add_standard_options, noconv, noconv_meth,
    AbstractWidgetTest, StandardOptionsTests,
    IntegerSizeTests, PixelSizeTests,
    setUpModule)

requires('gui')


class StandardTtkOptionsTests(StandardOptionsTests):

    def test_class(self):
        widget = self.create()
        self.assertEqual(widget['class'], '')
        errmsg='attempt to change read-only option'
        if get_tk_patchlevel() < (8, 6, 0, 'beta', 3):
            errmsg='Attempt to change read-only option'
        self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg)
        widget2 = self.create(class_='Foo')
        self.assertEqual(widget2['class'], 'Foo')

    def test_padding(self):
        widget = self.create()
        self.checkParam(widget, 'padding', 0, expected=('0',))
        self.checkParam(widget, 'padding', 5, expected=('5',))
        self.checkParam(widget, 'padding', (5, 6), expected=('5', '6'))
        self.checkParam(widget, 'padding', (5, 6, 7),
                        expected=('5', '6', '7'))
        self.checkParam(widget, 'padding', (5, 6, 7, 8),
                        expected=('5', '6', '7', '8'))
        self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p'))
        self.checkParam(widget, 'padding', (), expected='')

    def test_style(self):
        widget = self.create()
        self.assertEqual(widget['style'], '')
        errmsg = 'Layout Foo not found'
        if hasattr(self, 'default_orient'):
            errmsg = ('Layout %s.Foo not found' %
                      getattr(self, 'default_orient').title())
        self.checkInvalidParam(widget, 'style', 'Foo',
                errmsg=errmsg)
        widget2 = self.create(class_='Foo')
        self.assertEqual(widget2['class'], 'Foo')
        # XXX
        pass


class WidgetTest(AbstractTkTest, unittest.TestCase):
    """Tests methods available in every ttk widget."""

    def setUp(self):
        super(WidgetTest, self).setUp()
        self.widget = ttk.Button(self.root, width=0, text="Text")
        self.widget.pack()
        self.widget.wait_visibility()


    def test_identify(self):
        self.widget.update_idletasks()
        self.assertEqual(self.widget.identify(
            self.widget.winfo_width() // 2,
            self.widget.winfo_height() // 2
            ), "label")
        self.assertEqual(self.widget.identify(-1, -1), "")

        self.assertRaises(tkinter.TclError, self.widget.identify, None, 5)
        self.assertRaises(tkinter.TclError, self.widget.identify, 5, None)
        self.assertRaises(tkinter.TclError, self.widget.identify, 5, '')


    def test_widget_state(self):
        # XXX not sure about the portability of all these tests
        self.assertEqual(self.widget.state(), ())
        self.assertEqual(self.widget.instate(['!disabled']), True)

        # changing from !disabled to disabled
        self.assertEqual(self.widget.state(['disabled']), ('!disabled', ))
        # no state change
        self.assertEqual(self.widget.state(['disabled']), ())
        # change back to !disable but also active
        self.assertEqual(self.widget.state(['!disabled', 'active']),
            ('!active', 'disabled'))
        # no state changes, again
        self.assertEqual(self.widget.state(['!disabled', 'active']), ())
        self.assertEqual(self.widget.state(['active', '!disabled']), ())

        def test_cb(arg1, **kw):
            return arg1, kw
        self.assertEqual(self.widget.instate(['!disabled'],
            test_cb, "hi", **{"msg": "there"}),
            ('hi', {'msg': 'there'}))

        # attempt to set invalid statespec
        currstate = self.widget.state()
        self.assertRaises(tkinter.TclError, self.widget.instate,
            ['badstate'])
        self.assertRaises(tkinter.TclError, self.widget.instate,
            ['disabled', 'badstate'])
        # verify that widget didn't change its state
        self.assertEqual(currstate, self.widget.state())

        # ensuring that passing None as state doesn't modify current state
        self.widget.state(['active', '!disabled'])
        self.assertEqual(self.widget.state(), ('active', ))


class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests):
    _conv_pixels = noconv_meth


@add_standard_options(StandardTtkOptionsTests)
class FrameTest(AbstractToplevelTest, unittest.TestCase):
    OPTIONS = (
        'borderwidth', 'class', 'cursor', 'height',
        'padding', 'relief', 'style', 'takefocus',
        'width',
    )

    def create(self, **kwargs):
        return ttk.Frame(self.root, **kwargs)


@add_standard_options(StandardTtkOptionsTests)
class LabelFrameTest(AbstractToplevelTest, unittest.TestCase):
    OPTIONS = (
        'borderwidth', 'class', 'cursor', 'height',
        'labelanchor', 'labelwidget',
        'padding', 'relief', 'style', 'takefocus',
        'text', 'underline', 'width',
    )

    def create(self, **kwargs):
        return ttk.LabelFrame(self.root, **kwargs)

    def test_labelanchor(self):
        widget = self.create()
        self.checkEnumParam(widget, 'labelanchor',
                'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws',
                errmsg='Bad label anchor specification {}')
        self.checkInvalidParam(widget, 'labelanchor', 'center')

    def test_labelwidget(self):
        widget = self.create()
        label = ttk.Label(self.root, text='Mupp', name='foo')
        self.checkParam(widget, 'labelwidget', label, expected='.foo')
        label.destroy()


class AbstractLabelTest(AbstractWidgetTest):

    def checkImageParam(self, widget, name):
        image = tkinter.PhotoImage(master=self.root, name='image1')
        image2 = tkinter.PhotoImage(master=self.root, name='image2')
        self.checkParam(widget, name, image, expected=('image1',))
        self.checkParam(widget, name, 'image1', expected=('image1',))
        self.checkParam(widget, name, (image,), expected=('image1',))
        self.checkParam(widget, name, (image, 'active', image2),
                        expected=('image1', 'active', 'image2'))
        self.checkParam(widget, name, 'image1 active image2',
                        expected=('image1', 'active', 'image2'))
        self.checkInvalidParam(widget, name, 'spam',
                errmsg='image "spam" doesn\'t exist')

    def test_compound(self):
        widget = self.create()
        self.checkEnumParam(widget, 'compound',
                'none', 'text', 'image', 'center',
                'top', 'bottom', 'left', 'right')

    def test_state(self):
        widget = self.create()
        self.checkParams(widget, 'state', 'active', 'disabled', 'normal')

    def test_width(self):
        widget = self.create()
        self.checkParams(widget, 'width', 402, -402, 0)


@add_standard_options(StandardTtkOptionsTests)
class LabelTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'anchor', 'background', 'borderwidth',
        'class', 'compound', 'cursor', 'font', 'foreground',
        'image', 'justify', 'padding', 'relief', 'state', 'style',
        'takefocus', 'text', 'textvariable',
        'underline', 'width', 'wraplength',
    )
    _conv_pixels = noconv_meth

    def create(self, **kwargs):
        return ttk.Label(self.root, **kwargs)

    def test_font(self):
        widget = self.create()
        self.checkParam(widget, 'font',
                        '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*')


@add_standard_options(StandardTtkOptionsTests)
class ButtonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'class', 'command', 'compound', 'cursor', 'default',
        'image', 'padding', 'state', 'style',
        'takefocus', 'text', 'textvariable',
        'underline', 'width',
    )

    def create(self, **kwargs):
        return ttk.Button(self.root, **kwargs)

    def test_default(self):
        widget = self.create()
        self.checkEnumParam(widget, 'default', 'normal', 'active', 'disabled')

    def test_invoke(self):
        success = []
        btn = ttk.Button(self.root, command=lambda: success.append(1))
        btn.invoke()
        self.assertTrue(success)


@add_standard_options(StandardTtkOptionsTests)
class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'class', 'command', 'compound', 'cursor',
        'image',
        'offvalue', 'onvalue',
        'padding', 'state', 'style',
        'takefocus', 'text', 'textvariable',
        'underline', 'variable', 'width',
    )

    def create(self, **kwargs):
        return ttk.Checkbutton(self.root, **kwargs)

    def test_offvalue(self):
        widget = self.create()
        self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string')

    def test_onvalue(self):
        widget = self.create()
        self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string')

    def test_invoke(self):
        success = []
        def cb_test():
            success.append(1)
            return "cb test called"

        cbtn = ttk.Checkbutton(self.root, command=cb_test)
        # the variable automatically created by ttk.Checkbutton is actually
        # undefined till we invoke the Checkbutton
        self.assertEqual(cbtn.state(), ('alternate', ))
        self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar,
            cbtn['variable'])

        res = cbtn.invoke()
        self.assertEqual(res, "cb test called")
        self.assertEqual(cbtn['onvalue'],
            cbtn.tk.globalgetvar(cbtn['variable']))
        self.assertTrue(success)

        cbtn['command'] = ''
        res = cbtn.invoke()
        self.assertFalse(str(res))
        self.assertLessEqual(len(success), 1)
        self.assertEqual(cbtn['offvalue'],
            cbtn.tk.globalgetvar(cbtn['variable']))


@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
class EntryTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'background', 'class', 'cursor',
        'exportselection', 'font', 'foreground',
        'invalidcommand', 'justify',
        'show', 'state', 'style', 'takefocus', 'textvariable',
        'validate', 'validatecommand', 'width', 'xscrollcommand',
    )

    def setUp(self):
        super(EntryTest, self).setUp()
        self.entry = self.create()

    def create(self, **kwargs):
        return ttk.Entry(self.root, **kwargs)

    def test_invalidcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'invalidcommand')

    def test_show(self):
        widget = self.create()
        self.checkParam(widget, 'show', '*')
        self.checkParam(widget, 'show', '')
        self.checkParam(widget, 'show', ' ')

    def test_state(self):
        widget = self.create()
        self.checkParams(widget, 'state',
                         'disabled', 'normal', 'readonly')

    def test_validate(self):
        widget = self.create()
        self.checkEnumParam(widget, 'validate',
                'all', 'key', 'focus', 'focusin', 'focusout', 'none')

    def test_validatecommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'validatecommand')


    def test_bbox(self):
        self.assertIsBoundingBox(self.entry.bbox(0))
        self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex')
        self.assertRaises(tkinter.TclError, self.entry.bbox, None)


    def test_identify(self):
        self.entry.pack()
        self.entry.wait_visibility()
        self.entry.update_idletasks()

        # bpo-27313: macOS Cocoa widget differs from X, allow either
        if sys.platform == 'darwin':
            self.assertIn(self.entry.identify(5, 5),
                ("textarea", "Combobox.button") )
        else:
            self.assertEqual(self.entry.identify(5, 5), "textarea")
        self.assertEqual(self.entry.identify(-1, -1), "")

        self.assertRaises(tkinter.TclError, self.entry.identify, None, 5)
        self.assertRaises(tkinter.TclError, self.entry.identify, 5, None)
        self.assertRaises(tkinter.TclError, self.entry.identify, 5, '')


    def test_validation_options(self):
        success = []
        test_invalid = lambda: success.append(True)

        self.entry['validate'] = 'none'
        self.entry['validatecommand'] = lambda: False

        self.entry['invalidcommand'] = test_invalid
        self.entry.validate()
        self.assertTrue(success)

        self.entry['invalidcommand'] = ''
        self.entry.validate()
        self.assertEqual(len(success), 1)

        self.entry['invalidcommand'] = test_invalid
        self.entry['validatecommand'] = lambda: True
        self.entry.validate()
        self.assertEqual(len(success), 1)

        self.entry['validatecommand'] = ''
        self.entry.validate()
        self.assertEqual(len(success), 1)

        self.entry['validatecommand'] = True
        self.assertRaises(tkinter.TclError, self.entry.validate)


    def test_validation(self):
        validation = []
        def validate(to_insert):
            if not 'a' <= to_insert.lower() <= 'z':
                validation.append(False)
                return False
            validation.append(True)
            return True

        self.entry['validate'] = 'key'
        self.entry['validatecommand'] = self.entry.register(validate), '%S'

        self.entry.insert('end', 1)
        self.entry.insert('end', 'a')
        self.assertEqual(validation, [False, True])
        self.assertEqual(self.entry.get(), 'a')


    def test_revalidation(self):
        def validate(content):
            for letter in content:
                if not 'a' <= letter.lower() <= 'z':
                    return False
            return True

        self.entry['validatecommand'] = self.entry.register(validate), '%P'

        self.entry.insert('end', 'avocado')
        self.assertEqual(self.entry.validate(), True)
        self.assertEqual(self.entry.state(), ())

        self.entry.delete(0, 'end')
        self.assertEqual(self.entry.get(), '')

        self.entry.insert('end', 'a1b')
        self.assertEqual(self.entry.validate(), False)
        self.assertEqual(self.entry.state(), ('invalid', ))

        self.entry.delete(1)
        self.assertEqual(self.entry.validate(), True)
        self.assertEqual(self.entry.state(), ())


@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
class ComboboxTest(EntryTest, unittest.TestCase):
    OPTIONS = (
        'background', 'class', 'cursor', 'exportselection',
        'font', 'foreground', 'height', 'invalidcommand',
        'justify', 'postcommand', 'show', 'state', 'style',
        'takefocus', 'textvariable',
        'validate', 'validatecommand', 'values',
        'width', 'xscrollcommand',
    )

    def setUp(self):
        super(ComboboxTest, self).setUp()
        self.combo = self.create()

    def create(self, **kwargs):
        return ttk.Combobox(self.root, **kwargs)

    def test_height(self):
        widget = self.create()
        self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i')

    def _show_drop_down_listbox(self):
        width = self.combo.winfo_width()
        self.combo.event_generate('<ButtonPress-1>', x=width - 5, y=5)
        self.combo.event_generate('<ButtonRelease-1>', x=width - 5, y=5)
        self.combo.update_idletasks()


    def test_virtual_event(self):
        success = []

        self.combo['values'] = [1]
        self.combo.bind('<<ComboboxSelected>>',
            lambda evt: success.append(True))
        self.combo.pack()
        self.combo.wait_visibility()

        height = self.combo.winfo_height()
        self._show_drop_down_listbox()
        self.combo.update()
        self.combo.event_generate('<Return>')
        self.combo.update()

        self.assertTrue(success)


    def test_postcommand(self):
        success = []

        self.combo['postcommand'] = lambda: success.append(True)
        self.combo.pack()
        self.combo.wait_visibility()

        self._show_drop_down_listbox()
        self.assertTrue(success)

        # testing postcommand removal
        self.combo['postcommand'] = ''
        self._show_drop_down_listbox()
        self.assertEqual(len(success), 1)


    def test_values(self):
        def check_get_current(getval, currval):
            self.assertEqual(self.combo.get(), getval)
            self.assertEqual(self.combo.current(), currval)

        self.assertEqual(self.combo['values'],
                         () if tcl_version < (8, 5) else '')
        check_get_current('', -1)

        self.checkParam(self.combo, 'values', 'mon tue wed thur',
                        expected=('mon', 'tue', 'wed', 'thur'))
        self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur'))
        self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string'))
        self.checkParam(self.combo, 'values', () if tcl_version < (8, 5) else '')

        self.combo['values'] = ['a', 1, 'c']

        self.combo.set('c')
        check_get_current('c', 2)

        self.combo.current(0)
        check_get_current('a', 0)

        self.combo.set('d')
        check_get_current('d', -1)

        # testing values with empty string
        self.combo.set('')
        self.combo['values'] = (1, 2, '', 3)
        check_get_current('', 2)

        # testing values with empty string set through configure
        self.combo.configure(values=[1, '', 2])
        self.assertEqual(self.combo['values'],
                         ('1', '', '2') if self.wantobjects else
                         '1 {} 2')

        # testing values with spaces
        self.combo['values'] = ['a b', 'a\tb', 'a\nb']
        self.assertEqual(self.combo['values'],
                         ('a b', 'a\tb', 'a\nb') if self.wantobjects else
                         '{a b} {a\tb} {a\nb}')

        # testing values with special characters
        self.combo['values'] = [r'a\tb', '"a"', '} {']
        self.assertEqual(self.combo['values'],
                         (r'a\tb', '"a"', '} {') if self.wantobjects else
                         r'a\\tb {"a"} \}\ \{')

        # out of range
        self.assertRaises(tkinter.TclError, self.combo.current,
            len(self.combo['values']))
        # it expects an integer (or something that can be converted to int)
        self.assertRaises(tkinter.TclError, self.combo.current, '')

        # testing creating combobox with empty string in values
        combo2 = ttk.Combobox(self.root, values=[1, 2, ''])
        self.assertEqual(combo2['values'],
                         ('1', '2', '') if self.wantobjects else '1 2 {}')
        combo2.destroy()


@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'cursor', 'height',
        'orient', 'style', 'takefocus', 'width',
    )

    def setUp(self):
        super(PanedWindowTest, self).setUp()
        self.paned = self.create()

    def create(self, **kwargs):
        return ttk.PanedWindow(self.root, **kwargs)

    def test_orient(self):
        widget = self.create()
        self.assertEqual(str(widget['orient']), 'vertical')
        errmsg='attempt to change read-only option'
        if get_tk_patchlevel() < (8, 6, 0, 'beta', 3):
            errmsg='Attempt to change read-only option'
        self.checkInvalidParam(widget, 'orient', 'horizontal',
                errmsg=errmsg)
        widget2 = self.create(orient='horizontal')
        self.assertEqual(str(widget2['orient']), 'horizontal')

    def test_add(self):
        # attempt to add a child that is not a direct child of the paned window
        label = ttk.Label(self.paned)
        child = ttk.Label(label)
        self.assertRaises(tkinter.TclError, self.paned.add, child)
        label.destroy()
        child.destroy()
        # another attempt
        label = ttk.Label(self.root)
        child = ttk.Label(label)
        self.assertRaises(tkinter.TclError, self.paned.add, child)
        child.destroy()
        label.destroy()

        good_child = ttk.Label(self.root)
        self.paned.add(good_child)
        # re-adding a child is not accepted
        self.assertRaises(tkinter.TclError, self.paned.add, good_child)

        other_child = ttk.Label(self.paned)
        self.paned.add(other_child)
        self.assertEqual(self.paned.pane(0), self.paned.pane(1))
        self.assertRaises(tkinter.TclError, self.paned.pane, 2)
        good_child.destroy()
        other_child.destroy()
        self.assertRaises(tkinter.TclError, self.paned.pane, 0)


    def test_forget(self):
        self.assertRaises(tkinter.TclError, self.paned.forget, None)
        self.assertRaises(tkinter.TclError, self.paned.forget, 0)

        self.paned.add(ttk.Label(self.root))
        self.paned.forget(0)
        self.assertRaises(tkinter.TclError, self.paned.forget, 0)


    def test_insert(self):
        self.assertRaises(tkinter.TclError, self.paned.insert, None, 0)
        self.assertRaises(tkinter.TclError, self.paned.insert, 0, None)
        self.assertRaises(tkinter.TclError, self.paned.insert, 0, 0)

        child = ttk.Label(self.root)
        child2 = ttk.Label(self.root)
        child3 = ttk.Label(self.root)

        self.assertRaises(tkinter.TclError, self.paned.insert, 0, child)

        self.paned.insert('end', child2)
        self.paned.insert(0, child)
        self.assertEqual(self.paned.panes(), (str(child), str(child2)))

        self.paned.insert(0, child2)
        self.assertEqual(self.paned.panes(), (str(child2), str(child)))

        self.paned.insert('end', child3)
        self.assertEqual(self.paned.panes(),
            (str(child2), str(child), str(child3)))

        # reinserting a child should move it to its current position
        panes = self.paned.panes()
        self.paned.insert('end', child3)
        self.assertEqual(panes, self.paned.panes())

        # moving child3 to child2 position should result in child2 ending up
        # in previous child position and child ending up in previous child3
        # position
        self.paned.insert(child2, child3)
        self.assertEqual(self.paned.panes(),
            (str(child3), str(child2), str(child)))


    def test_pane(self):
        self.assertRaises(tkinter.TclError, self.paned.pane, 0)

        child = ttk.Label(self.root)
        self.paned.add(child)
        self.assertIsInstance(self.paned.pane(0), dict)
        self.assertEqual(self.paned.pane(0, weight=None),
                         0 if self.wantobjects else '0')
        # newer form for querying a single option
        self.assertEqual(self.paned.pane(0, 'weight'),
                         0 if self.wantobjects else '0')
        self.assertEqual(self.paned.pane(0), self.paned.pane(str(child)))

        self.assertRaises(tkinter.TclError, self.paned.pane, 0,
            badoption='somevalue')


    def test_sashpos(self):
        self.assertRaises(tkinter.TclError, self.paned.sashpos, None)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, '')
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)

        child = ttk.Label(self.paned, text='a')
        self.paned.add(child, weight=1)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 0)
        child2 = ttk.Label(self.paned, text='b')
        self.paned.add(child2)
        self.assertRaises(tkinter.TclError, self.paned.sashpos, 1)

        self.paned.pack(expand=True, fill='both')
        self.paned.wait_visibility()

        curr_pos = self.paned.sashpos(0)
        self.paned.sashpos(0, 1000)
        self.assertNotEqual(curr_pos, self.paned.sashpos(0))
        self.assertIsInstance(self.paned.sashpos(0), int)


@add_standard_options(StandardTtkOptionsTests)
class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'class', 'command', 'compound', 'cursor',
        'image',
        'padding', 'state', 'style',
        'takefocus', 'text', 'textvariable',
        'underline', 'value', 'variable', 'width',
    )

    def create(self, **kwargs):
        return ttk.Radiobutton(self.root, **kwargs)

    def test_value(self):
        widget = self.create()
        self.checkParams(widget, 'value', 1, 2.3, '', 'any string')

    def test_invoke(self):
        success = []
        def cb_test():
            success.append(1)
            return "cb test called"

        myvar = tkinter.IntVar(self.root)
        cbtn = ttk.Radiobutton(self.root, command=cb_test,
                               variable=myvar, value=0)
        cbtn2 = ttk.Radiobutton(self.root, command=cb_test,
                                variable=myvar, value=1)

        if self.wantobjects:
            conv = lambda x: x
        else:
            conv = int

        res = cbtn.invoke()
        self.assertEqual(res, "cb test called")
        self.assertEqual(conv(cbtn['value']), myvar.get())
        self.assertEqual(myvar.get(),
            conv(cbtn.tk.globalgetvar(cbtn['variable'])))
        self.assertTrue(success)

        cbtn2['command'] = ''
        res = cbtn2.invoke()
        self.assertEqual(str(res), '')
        self.assertLessEqual(len(success), 1)
        self.assertEqual(conv(cbtn2['value']), myvar.get())
        self.assertEqual(myvar.get(),
            conv(cbtn.tk.globalgetvar(cbtn['variable'])))

        self.assertEqual(str(cbtn['variable']), str(cbtn2['variable']))


class MenubuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'class', 'compound', 'cursor', 'direction',
        'image', 'menu', 'padding', 'state', 'style',
        'takefocus', 'text', 'textvariable',
        'underline', 'width',
    )

    def create(self, **kwargs):
        return ttk.Menubutton(self.root, **kwargs)

    def test_direction(self):
        widget = self.create()
        self.checkEnumParam(widget, 'direction',
                'above', 'below', 'left', 'right', 'flush')

    def test_menu(self):
        widget = self.create()
        menu = tkinter.Menu(widget, name='menu')
        self.checkParam(widget, 'menu', menu, conv=str)
        menu.destroy()


@add_standard_options(StandardTtkOptionsTests)
class ScaleTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'command', 'cursor', 'from', 'length',
        'orient', 'style', 'takefocus', 'to', 'value', 'variable',
    )
    _conv_pixels = noconv_meth
    default_orient = 'horizontal'

    def setUp(self):
        super(ScaleTest, self).setUp()
        self.scale = self.create()
        self.scale.pack()
        self.scale.update()

    def create(self, **kwargs):
        return ttk.Scale(self.root, **kwargs)

    def test_from(self):
        widget = self.create()
        self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False)

    def test_length(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i')

    def test_to(self):
        widget = self.create()
        self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False)

    def test_value(self):
        widget = self.create()
        self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False)

    def test_custom_event(self):
        failure = [1, 1, 1] # will need to be empty

        funcid = self.scale.bind('<<RangeChanged>>', lambda evt: failure.pop())

        self.scale['from'] = 10
        self.scale['from_'] = 10
        self.scale['to'] = 3

        self.assertFalse(failure)

        failure = [1, 1, 1]
        self.scale.configure(from_=2, to=5)
        self.scale.configure(from_=0, to=-2)
        self.scale.configure(to=10)

        self.assertFalse(failure)


    def test_get(self):
        if self.wantobjects:
            conv = lambda x: x
        else:
            conv = float

        scale_width = self.scale.winfo_width()
        self.assertEqual(self.scale.get(scale_width, 0), self.scale['to'])

        self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from']))
        self.assertEqual(self.scale.get(), self.scale['value'])
        self.scale['value'] = 30
        self.assertEqual(self.scale.get(), self.scale['value'])

        self.assertRaises(tkinter.TclError, self.scale.get, '', 0)
        self.assertRaises(tkinter.TclError, self.scale.get, 0, '')


    def test_set(self):
        if self.wantobjects:
            conv = lambda x: x
        else:
            conv = float

        # set restricts the max/min values according to the current range
        max = conv(self.scale['to'])
        new_max = max + 10
        self.scale.set(new_max)
        self.assertEqual(conv(self.scale.get()), max)
        min = conv(self.scale['from'])
        self.scale.set(min - 1)
        self.assertEqual(conv(self.scale.get()), min)

        # changing directly the variable doesn't impose this limitation tho
        var = tkinter.DoubleVar(self.root)
        self.scale['variable'] = var
        var.set(max + 5)
        self.assertEqual(conv(self.scale.get()), var.get())
        self.assertEqual(conv(self.scale.get()), max + 5)
        del var

        # the same happens with the value option
        self.scale['value'] = max + 10
        self.assertEqual(conv(self.scale.get()), max + 10)
        self.assertEqual(conv(self.scale.get()), conv(self.scale['value']))

        # nevertheless, note that the max/min values we can get specifying
        # x, y coords are the ones according to the current range
        self.assertEqual(conv(self.scale.get(0, 0)), min)
        self.assertEqual(conv(self.scale.get(self.scale.winfo_width(), 0)), max)

        self.assertRaises(tkinter.TclError, self.scale.set, None)


@add_standard_options(StandardTtkOptionsTests)
class ProgressbarTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'cursor', 'orient', 'length',
        'mode', 'maximum', 'phase',
        'style', 'takefocus', 'value', 'variable',
    )
    _conv_pixels = noconv_meth
    default_orient = 'horizontal'

    def create(self, **kwargs):
        return ttk.Progressbar(self.root, **kwargs)

    def test_length(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i')

    def test_maximum(self):
        widget = self.create()
        self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False)

    def test_mode(self):
        widget = self.create()
        self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate')

    def test_phase(self):
        # XXX
        pass

    def test_value(self):
        widget = self.create()
        self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10,
                             conv=False)


@unittest.skipIf(sys.platform == 'darwin',
                 'ttk.Scrollbar is special on MacOSX')
@add_standard_options(StandardTtkOptionsTests)
class ScrollbarTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'command', 'cursor', 'orient', 'style', 'takefocus',
    )
    default_orient = 'vertical'

    def create(self, **kwargs):
        return ttk.Scrollbar(self.root, **kwargs)


@add_standard_options(IntegerSizeTests, StandardTtkOptionsTests)
class NotebookTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width',
    )

    def setUp(self):
        super(NotebookTest, self).setUp()
        self.nb = self.create(padding=0)
        self.child1 = ttk.Label(self.root)
        self.child2 = ttk.Label(self.root)
        self.nb.add(self.child1, text='a')
        self.nb.add(self.child2, text='b')

    def create(self, **kwargs):
        return ttk.Notebook(self.root, **kwargs)

    def test_tab_identifiers(self):
        self.nb.forget(0)
        self.nb.hide(self.child2)
        self.assertRaises(tkinter.TclError, self.nb.tab, self.child1)
        self.assertEqual(self.nb.index('end'), 1)
        self.nb.add(self.child2)
        self.assertEqual(self.nb.index('end'), 1)
        self.nb.select(self.child2)

        self.assertTrue(self.nb.tab('current'))
        self.nb.add(self.child1, text='a')

        self.nb.pack()
        self.nb.wait_visibility()
        if sys.platform == 'darwin':
            tb_idx = "@20,5"
        else:
            tb_idx = "@5,5"
        self.assertEqual(self.nb.tab(tb_idx), self.nb.tab('current'))

        for i in range(5, 100, 5):
            try:
                if self.nb.tab('@%d, 5' % i, text=None) == 'a':
                    break
            except tkinter.TclError:
                pass

        else:
            self.fail("Tab with text 'a' not found")


    def test_add_and_hidden(self):
        self.assertRaises(tkinter.TclError, self.nb.hide, -1)
        self.assertRaises(tkinter.TclError, self.nb.hide, 'hi')
        self.assertRaises(tkinter.TclError, self.nb.hide, None)
        self.assertRaises(tkinter.TclError, self.nb.add, None)
        self.assertRaises(tkinter.TclError, self.nb.add, ttk.Label(self.root),
            unknown='option')

        tabs = self.nb.tabs()
        self.nb.hide(self.child1)
        self.nb.add(self.child1)
        self.assertEqual(self.nb.tabs(), tabs)

        child = ttk.Label(self.root)
        self.nb.add(child, text='c')
        tabs = self.nb.tabs()

        curr = self.nb.index('current')
        # verify that the tab gets readded at its previous position
        child2_index = self.nb.index(self.child2)
        self.nb.hide(self.child2)
        self.nb.add(self.child2)
        self.assertEqual(self.nb.tabs(), tabs)
        self.assertEqual(self.nb.index(self.child2), child2_index)
        self.assertEqual(str(self.child2), self.nb.tabs()[child2_index])
        # but the tab next to it (not hidden) is the one selected now
        self.assertEqual(self.nb.index('current'), curr + 1)


    def test_forget(self):
        self.assertRaises(tkinter.TclError, self.nb.forget, -1)
        self.assertRaises(tkinter.TclError, self.nb.forget, 'hi')
        self.assertRaises(tkinter.TclError, self.nb.forget, None)

        tabs = self.nb.tabs()
        child1_index = self.nb.index(self.child1)
        self.nb.forget(self.child1)
        self.assertNotIn(str(self.child1), self.nb.tabs())
        self.assertEqual(len(tabs) - 1, len(self.nb.tabs()))

        self.nb.add(self.child1)
        self.assertEqual(self.nb.index(self.child1), 1)
        self.assertNotEqual(child1_index, self.nb.index(self.child1))


    def test_index(self):
        self.assertRaises(tkinter.TclError, self.nb.index, -1)
        self.assertRaises(tkinter.TclError, self.nb.index, None)

        self.assertIsInstance(self.nb.index('end'), int)
        self.assertEqual(self.nb.index(self.child1), 0)
        self.assertEqual(self.nb.index(self.child2), 1)
        self.assertEqual(self.nb.index('end'), 2)


    def test_insert(self):
        # moving tabs
        tabs = self.nb.tabs()
        self.nb.insert(1, tabs[0])
        self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0]))
        self.nb.insert(self.child1, self.child2)
        self.assertEqual(self.nb.tabs(), tabs)
        self.nb.insert('end', self.child1)
        self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0]))
        self.nb.insert('end', 0)
        self.assertEqual(self.nb.tabs(), tabs)
        # bad moves
        self.assertRaises(tkinter.TclError, self.nb.insert, 2, tabs[0])
        self.assertRaises(tkinter.TclError, self.nb.insert, -1, tabs[0])

        # new tab
        child3 = ttk.Label(self.root)
        self.nb.insert(1, child3)
        self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1]))
        self.nb.forget(child3)
        self.assertEqual(self.nb.tabs(), tabs)
        self.nb.insert(self.child1, child3)
        self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs)
        self.nb.forget(child3)
        self.assertRaises(tkinter.TclError, self.nb.insert, 2, child3)
        self.assertRaises(tkinter.TclError, self.nb.insert, -1, child3)

        # bad inserts
        self.assertRaises(tkinter.TclError, self.nb.insert, 'end', None)
        self.assertRaises(tkinter.TclError, self.nb.insert, None, 0)
        self.assertRaises(tkinter.TclError, self.nb.insert, None, None)


    def test_select(self):
        self.nb.pack()
        self.nb.wait_visibility()

        success = []
        tab_changed = []

        self.child1.bind('<Unmap>', lambda evt: success.append(True))
        self.nb.bind('<<NotebookTabChanged>>',
            lambda evt: tab_changed.append(True))

        self.assertEqual(self.nb.select(), str(self.child1))
        self.nb.select(self.child2)
        self.assertTrue(success)
        self.assertEqual(self.nb.select(), str(self.child2))

        self.nb.update()
        self.assertTrue(tab_changed)


    def test_tab(self):
        self.assertRaises(tkinter.TclError, self.nb.tab, -1)
        self.assertRaises(tkinter.TclError, self.nb.tab, 'notab')
        self.assertRaises(tkinter.TclError, self.nb.tab, None)

        self.assertIsInstance(self.nb.tab(self.child1), dict)
        self.assertEqual(self.nb.tab(self.child1, text=None), 'a')
        # newer form for querying a single option
        self.assertEqual(self.nb.tab(self.child1, 'text'), 'a')
        self.nb.tab(self.child1, text='abc')
        self.assertEqual(self.nb.tab(self.child1, text=None), 'abc')
        self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc')


    def test_tabs(self):
        self.assertEqual(len(self.nb.tabs()), 2)

        self.nb.forget(self.child1)
        self.nb.forget(self.child2)

        self.assertEqual(self.nb.tabs(), ())


    def test_traversal(self):
        self.nb.pack()
        self.nb.wait_visibility()

        self.nb.select(0)

        simulate_mouse_click(self.nb, 5, 5)
        self.nb.focus_force()
        self.nb.event_generate('<Control-Tab>')
        self.assertEqual(self.nb.select(), str(self.child2))
        self.nb.focus_force()
        self.nb.event_generate('<Shift-Control-Tab>')
        self.assertEqual(self.nb.select(), str(self.child1))
        self.nb.focus_force()
        self.nb.event_generate('<Shift-Control-Tab>')
        self.assertEqual(self.nb.select(), str(self.child2))

        self.nb.tab(self.child1, text='a', underline=0)
        self.nb.enable_traversal()
        self.nb.focus_force()
        simulate_mouse_click(self.nb, 5, 5)
        if sys.platform == 'darwin':
            self.nb.event_generate('<Option-a>')
        else:
            self.nb.event_generate('<Alt-a>')
        self.assertEqual(self.nb.select(), str(self.child1))


@add_standard_options(StandardTtkOptionsTests)
class TreeviewTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'columns', 'cursor', 'displaycolumns',
        'height', 'padding', 'selectmode', 'show',
        'style', 'takefocus', 'xscrollcommand', 'yscrollcommand',
    )

    def setUp(self):
        super(TreeviewTest, self).setUp()
        self.tv = self.create(padding=0)

    def create(self, **kwargs):
        return ttk.Treeview(self.root, **kwargs)

    def test_columns(self):
        widget = self.create()
        self.checkParam(widget, 'columns', 'a b c',
                        expected=('a', 'b', 'c'))
        self.checkParam(widget, 'columns', ('a', 'b', 'c'))
        self.checkParam(widget, 'columns', () if tcl_version < (8, 5) else '')

    def test_displaycolumns(self):
        widget = self.create()
        widget['columns'] = ('a', 'b', 'c')
        self.checkParam(widget, 'displaycolumns', 'b a c',
                        expected=('b', 'a', 'c'))
        self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c'))
        self.checkParam(widget, 'displaycolumns', '#all',
                        expected=('#all',))
        self.checkParam(widget, 'displaycolumns', (2, 1, 0))
        self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'),
                               errmsg='Invalid column index d')
        self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3),
                               errmsg='Column index 3 out of bounds')
        self.checkInvalidParam(widget, 'displaycolumns', (1, -2),
                               errmsg='Column index -2 out of bounds')

    def test_height(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', conv=False)
        self.checkPixelsParam(widget, 'height', 101.2, 102.6, conv=noconv)

    def test_selectmode(self):
        widget = self.create()
        self.checkEnumParam(widget, 'selectmode',
                            'none', 'browse', 'extended')

    def test_show(self):
        widget = self.create()
        self.checkParam(widget, 'show', 'tree headings',
                        expected=('tree', 'headings'))
        self.checkParam(widget, 'show', ('tree', 'headings'))
        self.checkParam(widget, 'show', ('headings', 'tree'))
        self.checkParam(widget, 'show', 'tree', expected=('tree',))
        self.checkParam(widget, 'show', 'headings', expected=('headings',))

    def test_bbox(self):
        self.tv.pack()
        self.assertEqual(self.tv.bbox(''), '')
        self.tv.wait_visibility()
        self.tv.update()

        item_id = self.tv.insert('', 'end')
        children = self.tv.get_children()
        self.assertTrue(children)

        bbox = self.tv.bbox(children[0])
        self.assertIsBoundingBox(bbox)

        # compare width in bboxes
        self.tv['columns'] = ['test']
        self.tv.column('test', width=50)
        bbox_column0 = self.tv.bbox(children[0], 0)
        root_width = self.tv.column('#0', width=None)
        if not self.wantobjects:
            root_width = int(root_width)
        self.assertEqual(bbox_column0[0], bbox[0] + root_width)

        # verify that bbox of a closed item is the empty string
        child1 = self.tv.insert(item_id, 'end')
        self.assertEqual(self.tv.bbox(child1), '')


    def test_children(self):
        # no children yet, should get an empty tuple
        self.assertEqual(self.tv.get_children(), ())

        item_id = self.tv.insert('', 'end')
        self.assertIsInstance(self.tv.get_children(), tuple)
        self.assertEqual(self.tv.get_children()[0], item_id)

        # add item_id and child3 as children of child2
        child2 = self.tv.insert('', 'end')
        child3 = self.tv.insert('', 'end')
        self.tv.set_children(child2, item_id, child3)
        self.assertEqual(self.tv.get_children(child2), (item_id, child3))

        # child3 has child2 as parent, thus trying to set child2 as a children
        # of child3 should result in an error
        self.assertRaises(tkinter.TclError,
            self.tv.set_children, child3, child2)

        # remove child2 children
        self.tv.set_children(child2)
        self.assertEqual(self.tv.get_children(child2), ())

        # remove root's children
        self.tv.set_children('')
        self.assertEqual(self.tv.get_children(), ())


    def test_column(self):
        # return a dict with all options/values
        self.assertIsInstance(self.tv.column('#0'), dict)
        # return a single value of the given option
        if self.wantobjects:
            self.assertIsInstance(self.tv.column('#0', width=None), int)
        # set a new value for an option
        self.tv.column('#0', width=10)
        # testing new way to get option value
        self.assertEqual(self.tv.column('#0', 'width'),
                         10 if self.wantobjects else '10')
        self.assertEqual(self.tv.column('#0', width=None),
                         10 if self.wantobjects else '10')
        # check read-only option
        self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X')

        self.assertRaises(tkinter.TclError, self.tv.column, 'invalid')
        invalid_kws = [
            {'unknown_option': 'some value'},  {'stretch': 'wrong'},
            {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'}
        ]
        for kw in invalid_kws:
            self.assertRaises(tkinter.TclError, self.tv.column, '#0',
                **kw)


    def test_delete(self):
        self.assertRaises(tkinter.TclError, self.tv.delete, '#0')

        item_id = self.tv.insert('', 'end')
        item2 = self.tv.insert(item_id, 'end')
        self.assertEqual(self.tv.get_children(), (item_id, ))
        self.assertEqual(self.tv.get_children(item_id), (item2, ))

        self.tv.delete(item_id)
        self.assertFalse(self.tv.get_children())

        # reattach should fail
        self.assertRaises(tkinter.TclError,
            self.tv.reattach, item_id, '', 'end')

        # test multiple item delete
        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        self.assertEqual(self.tv.get_children(), (item1, item2))

        self.tv.delete(item1, item2)
        self.assertFalse(self.tv.get_children())


    def test_detach_reattach(self):
        item_id = self.tv.insert('', 'end')
        item2 = self.tv.insert(item_id, 'end')

        # calling detach without items is valid, although it does nothing
        prev = self.tv.get_children()
        self.tv.detach() # this should do nothing
        self.assertEqual(prev, self.tv.get_children())

        self.assertEqual(self.tv.get_children(), (item_id, ))
        self.assertEqual(self.tv.get_children(item_id), (item2, ))

        # detach item with children
        self.tv.detach(item_id)
        self.assertFalse(self.tv.get_children())

        # reattach item with children
        self.tv.reattach(item_id, '', 'end')
        self.assertEqual(self.tv.get_children(), (item_id, ))
        self.assertEqual(self.tv.get_children(item_id), (item2, ))

        # move a children to the root
        self.tv.move(item2, '', 'end')
        self.assertEqual(self.tv.get_children(), (item_id, item2))
        self.assertEqual(self.tv.get_children(item_id), ())

        # bad values
        self.assertRaises(tkinter.TclError,
            self.tv.reattach, 'nonexistent', '', 'end')
        self.assertRaises(tkinter.TclError,
            self.tv.detach, 'nonexistent')
        self.assertRaises(tkinter.TclError,
            self.tv.reattach, item2, 'otherparent', 'end')
        self.assertRaises(tkinter.TclError,
            self.tv.reattach, item2, '', 'invalid')

        # multiple detach
        self.tv.detach(item_id, item2)
        self.assertEqual(self.tv.get_children(), ())
        self.assertEqual(self.tv.get_children(item_id), ())


    def test_exists(self):
        self.assertEqual(self.tv.exists('something'), False)
        self.assertEqual(self.tv.exists(''), True)
        self.assertEqual(self.tv.exists({}), False)

        # the following will make a tk.call equivalent to
        # tk.call(treeview, "exists") which should result in an error
        # in the tcl interpreter since tk requires an item.
        self.assertRaises(tkinter.TclError, self.tv.exists, None)


    def test_focus(self):
        # nothing is focused right now
        self.assertEqual(self.tv.focus(), '')

        item1 = self.tv.insert('', 'end')
        self.tv.focus(item1)
        self.assertEqual(self.tv.focus(), item1)

        self.tv.delete(item1)
        self.assertEqual(self.tv.focus(), '')

        # try focusing inexistent item
        self.assertRaises(tkinter.TclError, self.tv.focus, 'hi')


    def test_heading(self):
        # check a dict is returned
        self.assertIsInstance(self.tv.heading('#0'), dict)

        # check a value is returned
        self.tv.heading('#0', text='hi')
        self.assertEqual(self.tv.heading('#0', 'text'), 'hi')
        self.assertEqual(self.tv.heading('#0', text=None), 'hi')

        # invalid option
        self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
            background=None)
        # invalid value
        self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
            anchor=1)

    def test_heading_callback(self):
        def simulate_heading_click(x, y):
            simulate_mouse_click(self.tv, x, y)
            self.tv.update()

        success = [] # no success for now

        self.tv.pack()
        self.tv.wait_visibility()
        self.tv.heading('#0', command=lambda: success.append(True))
        self.tv.column('#0', width=100)
        self.tv.update()

        # assuming that the coords (5, 5) fall into heading #0
        simulate_heading_click(5, 5)
        if not success:
            self.fail("The command associated to the treeview heading wasn't "
                "invoked.")

        success = []
        commands = self.tv.master._tclCommands
        self.tv.heading('#0', command=str(self.tv.heading('#0', command=None)))
        self.assertEqual(commands, self.tv.master._tclCommands)
        simulate_heading_click(5, 5)
        if not success:
            self.fail("The command associated to the treeview heading wasn't "
                "invoked.")

        # XXX The following raises an error in a tcl interpreter, but not in
        # Python
        #self.tv.heading('#0', command='I dont exist')
        #simulate_heading_click(5, 5)


    def test_index(self):
        # item 'what' doesn't exist
        self.assertRaises(tkinter.TclError, self.tv.index, 'what')

        self.assertEqual(self.tv.index(''), 0)

        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        c1 = self.tv.insert(item1, 'end')
        c2 = self.tv.insert(item1, 'end')
        self.assertEqual(self.tv.index(item1), 0)
        self.assertEqual(self.tv.index(c1), 0)
        self.assertEqual(self.tv.index(c2), 1)
        self.assertEqual(self.tv.index(item2), 1)

        self.tv.move(item2, '', 0)
        self.assertEqual(self.tv.index(item2), 0)
        self.assertEqual(self.tv.index(item1), 1)

        # check that index still works even after its parent and siblings
        # have been detached
        self.tv.detach(item1)
        self.assertEqual(self.tv.index(c2), 1)
        self.tv.detach(c1)
        self.assertEqual(self.tv.index(c2), 0)

        # but it fails after item has been deleted
        self.tv.delete(item1)
        self.assertRaises(tkinter.TclError, self.tv.index, c2)


    def test_insert_item(self):
        # parent 'none' doesn't exist
        self.assertRaises(tkinter.TclError, self.tv.insert, 'none', 'end')

        # open values
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
            open='')
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
            open='please')
        self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True)))
        self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False)))

        # invalid index
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'middle')

        # trying to duplicate item id is invalid
        itemid = self.tv.insert('', 'end', 'first-item')
        self.assertEqual(itemid, 'first-item')
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
            'first-item')
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end',
            MockTclObj('first-item'))

        # unicode values
        value = u'\xe1ba'
        item = self.tv.insert('', 'end', values=(value, ))
        self.assertEqual(self.tv.item(item, 'values'),
                         (value,) if self.wantobjects else value)
        self.assertEqual(self.tv.item(item, values=None),
                         (value,) if self.wantobjects else value)

        self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None)))
        self.assertEqual(self.tv.item(item, values=None),
                         (value,) if self.wantobjects else value)

        self.assertIsInstance(self.tv.item(item), dict)

        # erase item values
        self.tv.item(item, values='')
        self.assertFalse(self.tv.item(item, values=None))

        # item tags
        item = self.tv.insert('', 'end', tags=[1, 2, value])
        self.assertEqual(self.tv.item(item, tags=None),
                         ('1', '2', value) if self.wantobjects else
                         '1 2 %s' % value)
        self.tv.item(item, tags=[])
        self.assertFalse(self.tv.item(item, tags=None))
        self.tv.item(item, tags=(1, 2))
        self.assertEqual(self.tv.item(item, tags=None),
                         ('1', '2') if self.wantobjects else '1 2')

        # values with spaces
        item = self.tv.insert('', 'end', values=('a b c',
            '%s %s' % (value, value)))
        self.assertEqual(self.tv.item(item, values=None),
            ('a b c', '%s %s' % (value, value)) if self.wantobjects else
            '{a b c} {%s %s}' % (value, value))

        # text
        self.assertEqual(self.tv.item(
            self.tv.insert('', 'end', text="Label here"), text=None),
            "Label here")
        self.assertEqual(self.tv.item(
            self.tv.insert('', 'end', text=value), text=None),
            value)

        # test for values which are not None
        itemid = self.tv.insert('', 'end', 0)
        self.assertEqual(itemid, '0')
        itemid = self.tv.insert('', 'end', 0.0)
        self.assertEqual(itemid, '0.0')
        # this is because False resolves to 0 and element with 0 iid is already present
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', False)
        self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', '')


    def test_selection(self):
        # item 'none' doesn't exist
        self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none')
        self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none')
        self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none')
        self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none')

        item1 = self.tv.insert('', 'end')
        item2 = self.tv.insert('', 'end')
        c1 = self.tv.insert(item1, 'end')
        c2 = self.tv.insert(item1, 'end')
        c3 = self.tv.insert(item1, 'end')
        self.assertEqual(self.tv.selection(), ())

        self.tv.selection_set((c1, item2))
        self.assertEqual(self.tv.selection(), (c1, item2))
        self.tv.selection_set(c2)
        self.assertEqual(self.tv.selection(), (c2,))

        self.tv.selection_add((c1, item2))
        self.assertEqual(self.tv.selection(), (c1, c2, item2))
        self.tv.selection_add(item1)
        self.assertEqual(self.tv.selection(), (item1, c1, c2, item2))

        self.tv.selection_remove((item1, c3))
        self.assertEqual(self.tv.selection(), (c1, c2, item2))
        self.tv.selection_remove(c2)
        self.assertEqual(self.tv.selection(), (c1, item2))

        self.tv.selection_toggle((c1, c3))
        self.assertEqual(self.tv.selection(), (c3, item2))
        self.tv.selection_toggle(item2)
        self.assertEqual(self.tv.selection(), (c3,))

        self.tv.insert('', 'end', id='with spaces')
        self.tv.selection_set('with spaces')
        self.assertEqual(self.tv.selection(), ('with spaces',))

        self.tv.insert('', 'end', id='{brace')
        self.tv.selection_set('{brace')
        self.assertEqual(self.tv.selection(), ('{brace',))

        if have_unicode:
            self.tv.insert('', 'end', id=u(r'unicode\u20ac'))
            self.tv.selection_set(u(r'unicode\u20ac'))
            self.assertEqual(self.tv.selection(), (u(r'unicode\u20ac'),))

        self.tv.insert('', 'end', id='bytes\xe2\x82\xac')
        self.tv.selection_set('bytes\xe2\x82\xac')
        self.assertEqual(self.tv.selection(),
                         (u(r'bytes\u20ac') if have_unicode else
                          'bytes\xe2\x82\xac',))


    def test_set(self):
        self.tv['columns'] = ['A', 'B']
        item = self.tv.insert('', 'end', values=['a', 'b'])
        self.assertEqual(self.tv.set(item), {'A': 'a', 'B': 'b'})

        self.tv.set(item, 'B', 'a')
        self.assertEqual(self.tv.item(item, values=None),
                         ('a', 'a') if self.wantobjects else 'a a')

        self.tv['columns'] = ['B']
        self.assertEqual(self.tv.set(item), {'B': 'a'})

        self.tv.set(item, 'B', 'b')
        self.assertEqual(self.tv.set(item, column='B'), 'b')
        self.assertEqual(self.tv.item(item, values=None),
                         ('b', 'a') if self.wantobjects else 'b a')

        self.tv.set(item, 'B', 123)
        self.assertEqual(self.tv.set(item, 'B'),
                         123 if self.wantobjects else '123')
        self.assertEqual(self.tv.item(item, values=None),
                         (123, 'a') if self.wantobjects else '123 a')
        self.assertEqual(self.tv.set(item),
                         {'B': 123} if self.wantobjects else {'B': '123'})

        # inexistent column
        self.assertRaises(tkinter.TclError, self.tv.set, item, 'A')
        self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b')

        # inexistent item
        self.assertRaises(tkinter.TclError, self.tv.set, 'notme')


    def test_tag_bind(self):
        events = []
        item1 = self.tv.insert('', 'end', tags=['call'])
        item2 = self.tv.insert('', 'end', tags=['call'])
        self.tv.tag_bind('call', '<ButtonPress-1>',
            lambda evt: events.append(1))
        self.tv.tag_bind('call', '<ButtonRelease-1>',
            lambda evt: events.append(2))

        self.tv.pack()
        self.tv.wait_visibility()
        self.tv.update()

        pos_y = set()
        found = set()
        for i in range(0, 100, 10):
            if len(found) == 2: # item1 and item2 already found
                break
            item_id = self.tv.identify_row(i)
            if item_id and item_id not in found:
                pos_y.add(i)
                found.add(item_id)

        self.assertEqual(len(pos_y), 2) # item1 and item2 y pos
        for y in pos_y:
            simulate_mouse_click(self.tv, 0, y)

        # by now there should be 4 things in the events list, since each
        # item had a bind for two events that were simulated above
        self.assertEqual(len(events), 4)
        for evt in zip(events[::2], events[1::2]):
            self.assertEqual(evt, (1, 2))


    def test_tag_configure(self):
        # Just testing parameter passing for now
        self.assertRaises(TypeError, self.tv.tag_configure)
        self.assertRaises(tkinter.TclError, self.tv.tag_configure,
            'test', sky='blue')
        self.tv.tag_configure('test', foreground='blue')
        self.assertEqual(str(self.tv.tag_configure('test', 'foreground')),
            'blue')
        self.assertEqual(str(self.tv.tag_configure('test', foreground=None)),
            'blue')
        self.assertIsInstance(self.tv.tag_configure('test'), dict)

    def test_tag_has(self):
        item1 = self.tv.insert('', 'end', text='Item 1', tags=['tag1'])
        item2 = self.tv.insert('', 'end', text='Item 2', tags=['tag2'])
        self.assertRaises(TypeError, self.tv.tag_has)
        self.assertRaises(TclError, self.tv.tag_has, 'tag1', 'non-existing')
        self.assertTrue(self.tv.tag_has('tag1', item1))
        self.assertFalse(self.tv.tag_has('tag1', item2))
        self.assertFalse(self.tv.tag_has('tag2', item1))
        self.assertTrue(self.tv.tag_has('tag2', item2))
        self.assertFalse(self.tv.tag_has('tag3', item1))
        self.assertFalse(self.tv.tag_has('tag3', item2))
        self.assertEqual(self.tv.tag_has('tag1'), (item1,))
        self.assertEqual(self.tv.tag_has('tag2'), (item2,))
        self.assertEqual(self.tv.tag_has('tag3'), ())


@add_standard_options(StandardTtkOptionsTests)
class SeparatorTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'cursor', 'orient', 'style', 'takefocus',
        # 'state'?
    )
    default_orient = 'horizontal'

    def create(self, **kwargs):
        return ttk.Separator(self.root, **kwargs)


@add_standard_options(StandardTtkOptionsTests)
class SizegripTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'class', 'cursor', 'style', 'takefocus',
        # 'state'?
    )

    def create(self, **kwargs):
        return ttk.Sizegrip(self.root, **kwargs)


tests_gui = (
        ButtonTest, CheckbuttonTest, ComboboxTest, EntryTest,
        FrameTest, LabelFrameTest, LabelTest, MenubuttonTest,
        NotebookTest, PanedWindowTest, ProgressbarTest,
        RadiobuttonTest, ScaleTest, ScrollbarTest, SeparatorTest,
        SizegripTest, TreeviewTest, WidgetTest,
        )

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK'/�Ztest_ttk/__init__.pynu�[���PK'/�Zž��'�'test_ttk/test_extensions.pycnu�[����
zfc@s�ddlZddlZddlZddlZddlmZmZmZddl	m
Z
mZed�de
ejfd��YZ
de
ejfd��YZe
efZed	kr�ee�ndS(
i����N(trequirestrun_unittestt	swap_attr(tAbstractTkTesttdestroy_default_roottguitLabeledScaleTestcBsGeZd�Zd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs$|jj�tt|�j�dS(N(troottupdate_idletaskstsuperRttearDown(tself((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
s
cCsltj|j�}|jj}|j�|jtj|j	j
|�tj|j�}|j}tj|jd|�}|j�|jr�|j
|j	j
|�|j��n(|j
t|j	j
|��|j��~|jtj|j	j
|�tj|j�}tj|jd|�}|j�tj|jd|�ttd�rh|jtjtj�ndS(Ntvariablet	last_type(tttktLabeledScaleRt	_variablet_nametdestroytassertRaisesttkintertTclErrorttktglobalgetvart	DoubleVartwantobjectstassertEqualtgettfloattIntVarthasattrtsystassertNotEqualR
(Rtxtvartmyvartname((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_widget_destroys&
	
	%(
cCs�ttdd���ttdt��izYtj�}|jtj�|j|j	tj�|j|j
tjj
�|j�Wdt�XWdQXWdQXdS(Nt
_default_roott_support_default_root(
RRtNonetTrueRRtassertIsNotNoneR&RtmasterRRR(RR!((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_initialization_no_master2scs�tj�j�}tj|�}�j|j|�|j�ddddtj	dtj	dff}�j
r}|d7}nxK|D]C}tj�jd|d�}�j|j|d�|j�q�Wtj�jdd	�}�jt
|jj�|j�tj�jdd�}�jt
|jj�|j�tj�jd
d�}tj�jd|�}�j|jd�|j�tj�jd|dd
�}�j|jd
��j|jj|j�|j��fd�}tj�jdd�}||jd|jd�|j�tj�jdd�}||jd|jd�|j�tj�jdd�}||jd|jd�|j�tj�j�}||jd|jd�|j��jtjtj|dd�dS(Nt0ii
i����ig@itfrom_s2.5tvalueiRg�?cs8�j|j�d|��j|j�d|�dS(Ntsidetanchor(Rt	pack_infot
place_info(tscalet	scale_postlabelt	label_pos(R(s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pytcheck_positionsastcompoundttoptbottomtntstunknowntatb(R-i(ii(i
i
(i����i����(g@i((g@i(RtFrameRRRRR+RRtmaxintRR/Rt
ValueErrorRRR(RRR4R6R(RR+R!tpassed_expectedtpairR#R8((Rs</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_initialization?sP
	 	









cCs^tj|jdddd�}|j�|j�|j�|jj�}|jj	�d}|j
|t|d��|jjdddd�|j�|jj	�d}|j
||�|jj�}|j
|jd|jr�dnd	�|j
|t|d��|jjdddd�|j
||�|j
|t|d��|j�dS(
NR.ittoi
R!i����ittextR-(RRRtpacktwait_visibilitytupdateR6R3R4tcoordsRtintt	configureR RR(Rtlscaletlinfo_1tprev_xcoordtcurr_xcoordtlinfo_2((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_horizontal_rangevs$



&cCsvtj|j�}|j�|j�|j�|jj�d}|jd}||_|j�|j	|j
d|jr�|n	t|��|j
|jj�d|�|j	|jj�dt|j
j�d��|jr�d�}nt}||jd�d|_|j�|j	||j
d�|�|j	|jj�dt|j
j�d��|j�dS(NiiRHR!cSs|S(N((R!((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt<lambda>�tRG(RRRRIRJRKR4RLR/RR6Rtstrt
assertGreaterRMR3R(RR!RRtnewvaltconv((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_variable_change�s,



	
	
cCs�tj|j�}|jdtdd�|j�|j�|jj�|jj	�}}|d|d}}d|_
|j�|jjd||f�|jt
|jj�d�|jj�d�|jjd||f�|j�dS(	Ntexpandtfilltbothiis%dx%dR!i(RRRRIR)RJRKR+twinfo_widthtwinfo_heightR/twm_geometryRRMR6R3R4RLR(RR!twidththeightt	width_newt
height_new((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_resize�s

	
(	t__name__t
__module__R
R%R,RFRTR[Rf(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
s		"	
	7		 tOptionMenuTestcBs>eZd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(R	RitsetUpRt	StringVarRttextvar(R((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRj�scCs|`tt|�j�dS(N(RlR	RiR
(R((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
�scCs�tj|j�}tj|j|�}|j}|j�|j�|j|j	j
|�|j��~|jtj
|j	j
|�dS(N(RRkRRt
OptionMenuRRRRRRRRR(RR"toptmenuR$((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR%�s	

"cCs�|jtjtj|j|jdd�tj|j|jddd�}|j|jj	�d�|j
|d�|j
|d�|j�dS(NtinvalidtthingR@R?tmenuttextvariable(RRRRRmRRlRRRt
assertTrueR(RRn((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRF�s!c	s7d
�d}tj�j�j|��}t}xYtt���D]E}|dj|d�}�j|�|�||krCt	}qCqCW�j
|�|j�d}tj�j�j|��}d}d}xQt	r&||dj
|d�}}||kr	Pn�j||�|d7}q�W�j|t���|j�|j�|djd��j|jj��d��jtj|djd	��j|jj��d�|j�g����fd
�}tj�j�jdd|��}|djd��s)�jd�n|j�dS(NR?R@tcRqR/tdiii����cs%�j|�d��jt�dS(Ni(RtappendR)(titem(titemsRtsuccess(s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pytcb_teststcommandsMenu callback not invoked(R?R@Rt(RRmRRltFalsetrangetlent	entrycgetRR)RsRR(tentryconfigureR RIRJtinvokeRRRRRtfail(	RtdefaultRnt
found_defaulttiR/tcurrtlastRz((RxRRys</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt	test_menu�sJ


	


	cCs;d	}d}tj|j|j||�}tj|j�}tj|j|||�}|j�|j�|j�|j�|djd�|djd�|dj	dd�}|dj	dd�}|j
||�|j|jjj
|�|d�|j|jjj
|�|d�|j�|j�dS(
NR?R@RtRqiiiR(R?R@Rt(RRmRRlRRkRIRJR�RR RRRR(RRxR�Rnttextvar2toptmenu2toptmenu_stringvar_nametoptmenu2_stringvar_name((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_unique_radiobuttonss*



	
(RgRhRjR
R%RFR�R�(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRi�s				
	4t__main__(RtunittesttTkinterRRttest.test_supportRRRttest_ttk.supportRRtTestCaseRRit	tests_guiRg(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt<module>s
�qPK'/�Z�p���test_ttk/__init__.pyonu�[����
zfc@sdS(N((((s5/usr/lib64/python2.7/lib-tk/test/test_ttk/__init__.pyt<module>tPK'/�ZG����C�Ctest_ttk/test_functions.pynu�[���# -*- encoding: utf-8 -*-
import sys
import unittest
import ttk

class MockTkApp:

    def splitlist(self, arg):
        if isinstance(arg, tuple):
            return arg
        return arg.split(':')

    def wantobjects(self):
        return True


class MockTclObj(object):
    typename = 'test'

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

    def __str__(self):
        return unicode(self.val)


class MockStateSpec(object):
    typename = 'StateSpec'

    def __init__(self, *args):
        self.val = args

    def __str__(self):
        return ' '.join(self.val)


class InternalFunctionsTest(unittest.TestCase):

    def test_format_optdict(self):
        def check_against(fmt_opts, result):
            for i in range(0, len(fmt_opts), 2):
                self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
            if result:
                self.fail("result still got elements: %s" % result)

        # passing an empty dict should return an empty object (tuple here)
        self.assertFalse(ttk._format_optdict({}))

        # check list formatting
        check_against(
            ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
            {'-fg': 'blue', '-padding': '1 2 3 4'})

        # check tuple formatting (same as list)
        check_against(
            ttk._format_optdict({'test': (1, 2, '', 0)}),
            {'-test': '1 2 {} 0'})

        # check untouched values
        check_against(
            ttk._format_optdict({'test': {'left': 'as is'}}),
            {'-test': {'left': 'as is'}})

        # check script formatting
        check_against(
            ttk._format_optdict(
                {'test': [1, -1, '', '2m', 0], 'test2': 3,
                 'test3': '', 'test4': 'abc def',
                 'test5': '"abc"', 'test6': '{}',
                 'test7': '} -spam {'}, script=True),
            {'-test': '{1 -1 {} 2m 0}', '-test2': '3',
             '-test3': '{}', '-test4': '{abc def}',
             '-test5': '{"abc"}', '-test6': r'\{\}',
             '-test7': r'\}\ -spam\ \{'})

        opts = {u'αβγ': True, u'á': False}
        orig_opts = opts.copy()
        # check if giving unicode keys is fine
        check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False})
        # opts should remain unchanged
        self.assertEqual(opts, orig_opts)

        # passing values with spaces inside a tuple/list
        check_against(
            ttk._format_optdict(
                {'option': ('one two', 'three')}),
            {'-option': '{one two} three'})
        check_against(
            ttk._format_optdict(
                {'option': ('one\ttwo', 'three')}),
            {'-option': '{one\ttwo} three'})

        # passing empty strings inside a tuple/list
        check_against(
            ttk._format_optdict(
                {'option': ('', 'one')}),
            {'-option': '{} one'})

        # passing values with braces inside a tuple/list
        check_against(
            ttk._format_optdict(
                {'option': ('one} {two', 'three')}),
            {'-option': r'one\}\ \{two three'})

        # passing quoted strings inside a tuple/list
        check_against(
            ttk._format_optdict(
                {'option': ('"one"', 'two')}),
            {'-option': '{"one"} two'})
        check_against(
            ttk._format_optdict(
                {'option': ('{one}', 'two')}),
            {'-option': r'\{one\} two'})

        # ignore an option
        amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) // 2
        self.assertEqual(amount_opts, len(opts) - 1)

        # ignore non-existing options
        amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) // 2
        self.assertEqual(amount_opts, len(opts) - 1)

        # ignore every option
        self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys()))


    def test_format_mapdict(self):
        opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
        result = ttk._format_mapdict(opts)
        self.assertEqual(len(result), len(opts.keys()) * 2)
        self.assertEqual(result, ('-a', '{b c} val d otherval {} single'))
        self.assertEqual(ttk._format_mapdict(opts, script=True),
            ('-a', '{{b c} val d otherval {} single}'))

        self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))

        opts = {u'üñíćódè': [(u'á', u'vãl')]}
        result = ttk._format_mapdict(opts)
        self.assertEqual(result, (u'-üñíćódè', u'á vãl'))

        # empty states
        valid = {'opt': [('', u'', 'hi')]}
        self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))

        # when passing multiple states, they all must be strings
        invalid = {'opt': [(1, 2, 'valid val')]}
        self.assertRaises(TypeError, ttk._format_mapdict, invalid)
        invalid = {'opt': [([1], '2', 'valid val')]}
        self.assertRaises(TypeError, ttk._format_mapdict, invalid)
        # but when passing a single state, it can be anything
        valid = {'opt': [[1, 'value']]}
        self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
        # special attention to single states which evalute to False
        for stateval in (None, 0, False, '', set()): # just some samples
            valid = {'opt': [(stateval, 'value')]}
            self.assertEqual(ttk._format_mapdict(valid),
                ('-opt', '{} value'))

        # values must be iterable
        opts = {'a': None}
        self.assertRaises(TypeError, ttk._format_mapdict, opts)

        # items in the value must have size >= 2
        self.assertRaises(IndexError, ttk._format_mapdict,
            {'a': [('invalid', )]})


    def test_format_elemcreate(self):
        self.assertTrue(ttk._format_elemcreate(None), (None, ()))

        ## Testing type = image
        # image type expects at least an image name, so this should raise
        # IndexError since it tries to access the index 0 of an empty tuple
        self.assertRaises(IndexError, ttk._format_elemcreate, 'image')

        # don't format returned values as a tcl script
        # minimum acceptable for image type
        self.assertEqual(ttk._format_elemcreate('image', False, 'test'),
            ("test ", ()))
        # specifying a state spec
        self.assertEqual(ttk._format_elemcreate('image', False, 'test',
            ('', 'a')), ("test {} a", ()))
        # state spec with multiple states
        self.assertEqual(ttk._format_elemcreate('image', False, 'test',
            ('a', 'b', 'c')), ("test {a b} c", ()))
        # state spec and options
        res = ttk._format_elemcreate('image', False, 'test',
                                     ('a', 'b'), a='x', b='y')
        self.assertEqual(res[0], "test a b")
        self.assertEqual(set(res[1]), {"-a", "x", "-b", "y"})
        # format returned values as a tcl script
        # state spec with multiple states and an option with a multivalue
        self.assertEqual(ttk._format_elemcreate('image', True, 'test',
            ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}"))

        ## Testing type = vsapi
        # vsapi type expects at least a class name and a part_id, so this
        # should raise a ValueError since it tries to get two elements from
        # an empty tuple
        self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')

        # don't format returned values as a tcl script
        # minimum acceptable for vsapi
        self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),
            ("a b ", ()))
        # now with a state spec with multiple states
        self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
            ('a', 'b', 'c')), ("a b {a b} c", ()))
        # state spec and option
        self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
            ('a', 'b'), opt='x'), ("a b a b", ("-opt", "x")))
        # format returned values as a tcl script
        # state spec with a multivalue and an option
        self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',
            ('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x"))

        # Testing type = from
        # from type expects at least a type name
        self.assertRaises(IndexError, ttk._format_elemcreate, 'from')

        self.assertEqual(ttk._format_elemcreate('from', False, 'a'),
            ('a', ()))
        self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
            ('a', ('b', )))
        self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
            ('{a}', 'b'))


    def test_format_layoutlist(self):
        def sample(indent=0, indent_size=2):
            return ttk._format_layoutlist(
            [('a', {'other': [1, 2, 3], 'children':
                [('b', {'children':
                    [('c', {'children':
                        [('d', {'nice': 'opt'})], 'something': (1, 2)
                    })]
                })]
            })], indent=indent, indent_size=indent_size)[0]

        def sample_expected(indent=0, indent_size=2):
            spaces = lambda amount=0: ' ' * (amount + indent)
            return (
                "%sa -other {1 2 3} -children {\n"
                "%sb -children {\n"
                "%sc -something {1 2} -children {\n"
                "%sd -nice opt\n"
                "%s}\n"
                "%s}\n"
                "%s}" % (spaces(), spaces(indent_size),
                    spaces(2 * indent_size), spaces(3 * indent_size),
                    spaces(2 * indent_size), spaces(indent_size), spaces()))

        # empty layout
        self.assertEqual(ttk._format_layoutlist([])[0], '')

        # smallest (after an empty one) acceptable layout
        smallest = ttk._format_layoutlist([('a', None)], indent=0)
        self.assertEqual(smallest,
            ttk._format_layoutlist([('a', '')], indent=0))
        self.assertEqual(smallest[0], 'a')

        # testing indentation levels
        self.assertEqual(sample(), sample_expected())
        for i in range(4):
            self.assertEqual(sample(i), sample_expected(i))
            self.assertEqual(sample(i, i), sample_expected(i, i))

        # invalid layout format, different kind of exceptions will be
        # raised

        # plain wrong format
        self.assertRaises(ValueError, ttk._format_layoutlist,
            ['bad', 'format'])
        self.assertRaises(TypeError, ttk._format_layoutlist, None)
        # _format_layoutlist always expects the second item (in every item)
        # to act like a dict (except when the value evalutes to False).
        self.assertRaises(AttributeError,
            ttk._format_layoutlist, [('a', 'b')])
        # bad children formatting
        self.assertRaises(ValueError, ttk._format_layoutlist,
            [('name', {'children': {'a': None}})])


    def test_script_from_settings(self):
        # empty options
        self.assertFalse(ttk._script_from_settings({'name':
            {'configure': None, 'map': None, 'element create': None}}))

        # empty layout
        self.assertEqual(
            ttk._script_from_settings({'name': {'layout': None}}),
            "ttk::style layout name {\nnull\n}")

        configdict = {u'αβγ': True, u'á': False}
        self.assertTrue(
            ttk._script_from_settings({'name': {'configure': configdict}}))

        mapdict = {u'üñíćódè': [(u'á', u'vãl')]}
        self.assertTrue(
            ttk._script_from_settings({'name': {'map': mapdict}}))

        # invalid image element
        self.assertRaises(IndexError,
            ttk._script_from_settings, {'name': {'element create': ['image']}})

        # minimal valid image
        self.assertTrue(ttk._script_from_settings({'name':
            {'element create': ['image', 'name']}}))

        image = {'thing': {'element create':
            ['image', 'name', ('state1', 'state2', 'val')]}}
        self.assertEqual(ttk._script_from_settings(image),
            "ttk::style element create thing image {name {state1 state2} val} ")

        image['thing']['element create'].append({'opt': 30})
        self.assertEqual(ttk._script_from_settings(image),
            "ttk::style element create thing image {name {state1 state2} val} "
            "-opt 30")

        image['thing']['element create'][-1]['opt'] = [MockTclObj(3),
            MockTclObj('2m')]
        self.assertEqual(ttk._script_from_settings(image),
            "ttk::style element create thing image {name {state1 state2} val} "
            "-opt {3 2m}")


    def test_tclobj_to_py(self):
        self.assertEqual(
            ttk._tclobj_to_py((MockStateSpec('a', 'b'), 'val')),
            [('a', 'b', 'val')])
        self.assertEqual(
            ttk._tclobj_to_py([MockTclObj('1'), 2, MockTclObj('3m')]),
            [1, 2, '3m'])


    def test_list_from_statespec(self):
        def test_it(sspec, value, res_value, states):
            self.assertEqual(ttk._list_from_statespec(
                (sspec, value)), [states + (res_value, )])

        states_even = tuple('state%d' % i for i in range(6))
        statespec = MockStateSpec(*states_even)
        test_it(statespec, 'val', 'val', states_even)
        test_it(statespec, MockTclObj('val'), 'val', states_even)

        states_odd = tuple('state%d' % i for i in range(5))
        statespec = MockStateSpec(*states_odd)
        test_it(statespec, 'val', 'val', states_odd)

        test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))


    def test_list_from_layouttuple(self):
        tk = MockTkApp()

        # empty layout tuple
        self.assertFalse(ttk._list_from_layouttuple(tk, ()))

        # shortest layout tuple
        self.assertEqual(ttk._list_from_layouttuple(tk, ('name', )),
            [('name', {})])

        # not so interesting ltuple
        sample_ltuple = ('name', '-option', 'value')
        self.assertEqual(ttk._list_from_layouttuple(tk, sample_ltuple),
            [('name', {'option': 'value'})])

        # empty children
        self.assertEqual(ttk._list_from_layouttuple(tk,
            ('something', '-children', ())),
            [('something', {'children': []})]
        )

        # more interesting ltuple
        ltuple = (
            'name', '-option', 'niceone', '-children', (
                ('otherone', '-children', (
                    ('child', )), '-otheropt', 'othervalue'
                )
            )
        )
        self.assertEqual(ttk._list_from_layouttuple(tk, ltuple),
            [('name', {'option': 'niceone', 'children':
                [('otherone', {'otheropt': 'othervalue', 'children':
                    [('child', {})]
                })]
            })]
        )

        # bad tuples
        self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
            ('name', 'no_minus'))
        self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
            ('name', 'no_minus', 'value'))
        self.assertRaises(ValueError, ttk._list_from_layouttuple, tk,
            ('something', '-children')) # no children


    def test_val_or_dict(self):
        def func(res, opt=None, val=None):
            if opt is None:
                return res
            if val is None:
                return "test val"
            return (opt, val)

        tk = MockTkApp()
        tk.call = func

        self.assertEqual(ttk._val_or_dict(tk, {}, '-test:3'),
                         {'test': '3'})
        self.assertEqual(ttk._val_or_dict(tk, {}, ('-test', 3)),
                         {'test': 3})

        self.assertEqual(ttk._val_or_dict(tk, {'test': None}, 'x:y'),
                         'test val')

        self.assertEqual(ttk._val_or_dict(tk, {'test': 3}, 'x:y'),
                         {'test': 3})


    def test_convert_stringval(self):
        tests = (
            (0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),
            (None, 'None')
        )
        for orig, expected in tests:
            self.assertEqual(ttk._convert_stringval(orig), expected)

        if sys.getdefaultencoding() == 'ascii':
            self.assertRaises(UnicodeDecodeError,
                ttk._convert_stringval, 'á')


class TclObjsToPyTest(unittest.TestCase):

    def test_unicode(self):
        adict = {'opt': u'välúè'}
        self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})

        adict['opt'] = MockTclObj(adict['opt'])
        self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})

    def test_multivalues(self):
        adict = {'opt': [1, 2, 3, 4]}
        self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})

        adict['opt'] = [1, 'xm', 3]
        self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})

        adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')
        self.assertEqual(ttk.tclobjs_to_py(adict),
            {'opt': [('a', 'b', u'válũè')]})

        self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),
            {'x': ['y z']})

    def test_nosplit(self):
        self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),
            {'text': 'some text'})

tests_nogui = (InternalFunctionsTest, TclObjsToPyTest)

if __name__ == "__main__":
    from test.test_support import run_unittest
    run_unittest(*tests_nogui)
PK'/�Z�d67�>�>test_ttk/test_functions.pycnu�[����
zfc@s�ddlZddlZddlZdfd��YZdefd��YZdefd��YZdejfd	��YZd
ejfd��YZ	ee	fZ
edkr�dd
lm
Z
e
e
�ndS(i����Nt	MockTkAppcBseZd�Zd�ZRS(cCs t|t�r|S|jd�S(Nt:(t
isinstancettupletsplit(tselftarg((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt	splitlistscCstS(N(tTrue(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytwantobjects
s(t__name__t
__module__RR	(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	t
MockTclObjcBs eZdZd�Zd�ZRS(ttestcCs
||_dS(N(tval(RR((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt__init__scCs
t|j�S(N(tunicodeR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt__str__s(R
RttypenameRR(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	t
MockStateSpeccBs eZdZd�Zd�ZRS(t	StateSpeccGs
||_dS(N(R(Rtargs((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRscCsdj|j�S(Nt (tjoinR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR!s(R
RRRR(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	tInternalFunctionsTestcBsbeZd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d	�ZRS(
cs
�fd�}�jtji��|tjidd6ddddgd6�idd	6d
d6�|tjidBd6�idd6�|tjiidd6d6�iidd6d6�|tjiddddd
gd6dd6dd6dd6dd6dd6dd6dt�id d6d!d"6dd#6d$d%6d&d'6d(d)6d*d+6�itd,6td-6}|j�}|tj|�itd.6td/6��j||�|tjidCd26�id3d46�|tjidDd26�id6d46�|tjidEd26�id8d46�|tjidFd26�id:d46�|tjidGd26�id=d46�|tjidHd26�id?d46�ttj|d@d-��d}�j|t|�d�ttj|d@dI��d}�j|t|�d��jtj|d@|j���dS(JNcsfxEtdt|�d�D]+}�j|j||�||d�qW|rb�jd|�ndS(Niiisresult still got elements: %s(trangetlentassertEqualtpoptfail(tfmt_optstresultti(R(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt
check_against(s)tbluetfgiiiitpaddings-fgs1 2 3 4s-paddingtiR
s1 2 {} 0s-testsas istlefti����t2mttest2ttest3sabc defttest4s"abc"ttest5s{}ttest6s	} -spam {ttest7tscripts{1 -1 {} 2m 0}t3s-test2s-test3s	{abc def}s-test4s{"abc"}s-test5s\{\}s-test6s
\}\ -spam\ \{s-test7uαβγuáu-αβγu-ásone twotthreetoptions{one two} threes-optionsone	twos{one	two} threetones{} ones	one} {twosone\}\ \{two threes"one"ttwos{"one"} twos{one}s\{one\} twotignoretb(iiR%i(sone twoR0(sone	twoR0(R%R2(s	one} {twoR0(s"one"R3(s{one}R3(uáR5(	tassertFalsetttkt_format_optdictRtFalsetcopyRRtkeys(RR!toptst	orig_optstamount_opts((Rs;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_optdict'sl& $





cCsid!d"d#gd6}tj|�}|jt|�t|j��d	�|j|d$�|jtj|dt�d%�|jtjigd	6�d&�id'gd6}tj|�}|j|d(�id)gd6}|jtj|�d*�id+gd6}|jttj|�idgddfgd6}|jttj|�iddggd6}|jtj|�d,�xOddt	dt
�fD]5}i|dfgd6}|jtj|�d-�q�Widd6}|jttj|�|jttjid.gd6�dS(/NR5tcRtdtothervalR%tsingletais-as{b c} val d otherval {} singleR.s {{b c} val d otherval {} single}s-2uáuvãlu
üñíćódèu-üñíćódèuá vãluthitopts-opts{ } hiis	valid valt2tvalues1 valueis{} valuetinvalid(R5R@R(RARB(R%RC(s-as{b c} val d otherval {} single(s-as {{b c} val d otherval {} single}(s-2R%(uáuvãl(u-üñíćódèuá vãl(R%uRE(s-opts{ } hi(iis	valid val(s-opts1 value(s-opts{} value(RI(R7t_format_mapdictRRR;RtassertRaisest	TypeErrortNoneR9tsett
IndexError(RR<RtvalidRItstateval((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_mapdicts4& 
c
Cs�|jtjd�dd f�|jttjd�|jtjdtd�dd!f�|jtjdtdd"�dd#f�|jtjdtdd$�d	d%f�tjdtdd&dd
dd�}|j|dd
�|jt|d�dd
ddh�|jtjdt	dd'd
ddg�d(�|jt
tjd�|jtjdtdd�dd)f�|jtjdtddd*�dd+f�|jtjdtddd,dd
�dd-f�|jtjdt	ddddddgfdd
�d.�|jttjd�|jtjdtd�dd/f�|jtjdtdd�dd0f�|jtjdt	dd�d1�dS(2NtimageR
stest R%RDs	test {} aR5R@stest {a b} ctxtyistest a bis-as-bRAiis{test {a b c} d}s-x {2 3}tvsapisa b sa b {a b} cRFsa b a bs-opts{a b {a b} {1 2}}s-opt xtfroms{a}(((R%RD((RDR5R@((RDR5(RDR5R@RA(s{test {a b c} d}s-x {2 3}((RDR5R@((RDR5(s-optRT(s{a b {a b} {1 2}}s-opt x((R5(s{a}R5(t
assertTrueR7t_format_elemcreateRMRKRORR9RNRt
ValueError(Rtres((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_elemcreate�s<
&
"

cCspddd�}ddd�}|jtjg�dd�tjdgdd�}|j|tjdgdd��|j|dd�|j|�|��xRtd�D]D}|j||�||��|j|||�|||��q�W|jttjd	d
g�|jttjd�|jttjdg�|jttjdiidd6d
6fg�dS(NiicSsttjdidddgd6dididid	d
6fgd6dd6fgd6fgd6fgd
|d|�dS(NRDiiitotherR5R@RARFtnicetchildrent	somethingtindenttindent_sizei(ii(R7t_format_layoutlist(RaRb((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytsample�s;cs_d�fd�}d|�||�|d|�|d|�|d|�||�|�fS(Nicsd|�S(NR((tamount(Ra(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt<lambda>�R%si%sa -other {1 2 3} -children {
%sb -children {
%sc -something {1 2} -children {
%sd -nice opt
%s}
%s}
%s}ii((RaRbtspaces((Ras;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytsample_expected�s
R%RDRaitbadtformatR5tnameR_(RDN(RDR%(RDR5(	RR7RcRMRRKRZRLtAttributeError(RRdRhtsmallestR ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_layoutlist�s$
	&
	cCs�|jtjiidd6dd6dd6d6��|jtjiidd6d6�d�itd6td6}|jtjii|d6d6��idgd
6}|jtjii|d6d6��|jt	tjiidgd6d6�|jtjiiddgd6d6��iidddgd6d6}|jtj|�d�|ddj
idd6�|jtj|�d�td�td�g|dddd<|jtj|�d�dS(Nt	configuretmapselement createRktlayoutsttk::style layout name {
null
}uαβγuáuvãlu
üñíćódèRStstate1tstate2RtthingsAttk::style element create thing image {name {state1 state2} val} iRFsHttk::style element create thing image {name {state1 state2} val} -opt 30iR'i����sLttk::style element create thing image {name {state1 state2} val} -opt {3 2m}(uáuvãl(RrRsR(R6R7t_script_from_settingsRMRRR9RXRKROtappendR(Rt
configdicttmapdictRS((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_script_from_settingss4#		cCsf|jtjtdd�df�dg�|jtjtd�dtd�g�dddg�dS(	NRDR5Rt1it3mi(RDR5R(RR7t
_tclobj_to_pyRR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_tclobj_to_pyGs
!cs��fd�}td�td�D��}t|�}||dd|�||td�d|�td�td�D��}t|�}||dd|�|d
td�dd�dS(Ncs-�jtj||f�||fg�dS(N(RR7t_list_from_statespec(tsspecRHt	res_valuetstates(R(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_itQscss|]}d|VqdS(sstate%dN((t.0R ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pys	<genexpr>UsiRcss|]}d|VqdS(sstate%dN((R�R ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pys	<genexpr>ZsiRDR5R@(RDR5R@(RDR5R@(RRRR(RR�tstates_event	statespect
states_odd((Rs;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_list_from_statespecPsc	Cstt�}|jtj|d��|jtj|d�difg�d}|jtj||�didd6fg�|jtj|dddf�digd6fg�ddddd	ddddff}|jtj||�didd6d	idd
6d
ifgd6fgd6fg�|jttj|d�|jttj|d�|jttj|d�dS(NRks-optionRHR1R`s	-childrenR_tniceonetotheronetchilds	-otheroptt
othervaluetotheropttno_minus((Rk(Rks-optionRH((R�(RkR�(RkR�RH(R`s	-children(RR6R7t_list_from_layouttupleRRKRZ(Rttkt
sample_ltupletltuple((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_list_from_layouttupleas.	

$cCs�ddd�}t�}||_|jtj|id�idd6�|jtj|id	�idd6�|jtj|idd6d�d�|jtj|idd6d�idd6�dS(
NcSs*|dkr|S|dkr dS||fS(Nstest val(RM(R[RFR((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytfunc�s
s-test:3R/R
s-testisx:ystest val(s-testi(RMRtcallRR7t_val_or_dict(RR�R�((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_val_or_dict�s		cCs}d
ddd
gdfdf}x-|D]%\}}|jtj|�|�q%Wtj�dkry|jttjd	�ndS(Nit09i	RDuáÚs[]RMtasciisá(ii(R�i	(RDRD(uáÚuáÚ(NRM(RMRR7t_convert_stringvaltsystgetdefaultencodingRKtUnicodeDecodeError(Rtteststorigtexpected((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_convert_stringval�s		(R
RR?RRR\RnRyR}R�R�R�R�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR%s	X	)	=	7	+				.	tTclObjsToPyTestcBs#eZd�Zd�Zd�ZRS(cCseidd6}|jtj|�idd6�t|d�|d<|jtj|�idd6�dS(NuvälúèRF(RR7t
tclobjs_to_pyR(Rtadict((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_unicode�s
 cCs�iddddgd6}|jtj|�iddddgd6�dddg|d<|jtj|�idddgd6�tdd�d	f|d<|jtj|�idgd6�|jtjid
gd6�id
gd6�dS(
NiiiiRFtxmRDR5uválũèsy zRT(RDR5uválũè(RR7R�R(RR�((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_multivalues�s,)cCs+|jtjidd6�idd6�dS(Ns	some textttext(RR7R�(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_nosplit�s(R
RR�R�R�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR��s		t__main__(trun_unittest(R�tunittestR7RtobjectRRtTestCaseRR�ttests_noguiR
ttest.test_supportR�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt<module>s

��PK'/�Z@
S���test_ttk/support.pycnu�[����
zfc@s�ddlZddlZddlZddlZddd��YZd�Zd�ZddlZe	e
eejj
d���Zd�Zdad�Zid	d
d6d	d6d	d
d6dd6Zd�Zd�Zd�ZdS(i����NtAbstractTkTestcBs8eZed��Zed��Zd�Zd�ZRS(cCs�tj|_t�tj�tj�|_|jj�|_|jjd�y|jj	dt
�Wntjk
r{nXdS(Ntnormals-zoomed(ttkintert_support_default_roott_old_support_default_roottdestroy_default_roott
NoDefaultRoottTktroottwantobjectstwm_statet
wm_attributestFalsetTclError(tcls((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt
setUpClasss
cCs9|jj�|jj�|`dt_|jt_dS(N(Rtupdate_idletaskstdestroytNoneRt
_default_rootRR(R((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt
tearDownClasss


	cCs|jj�dS(N(Rt	deiconify(tself((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytsetUpscCs5x!|jj�D]}|j�qW|jj�dS(N(Rtwinfo_childrenRtwithdraw(Rtw((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyttearDown"s(t__name__t
__module__tclassmethodRRRR(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyRs	cCs<ttdd�r8tjj�tjj�dt_ndS(NR(tgetattrRRRRR(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyR's

cCsh|jddddd�|jdd|d|�|jdd|d|�|jdd|d|�dS(	sYGenerate proper events to click at the x, y position (tries to act
    like an X server).s<Enter>txitys<Motion>s<ButtonPress-1>s<ButtonRelease-1>N(tevent_generate(twidgetR R!((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytsimulate_mouse_click-st.csQt��dkr>tjt�kddjtt����S�fd�}|S(Nisrequires Tcl version >= R%cs%tj����fd��}|S(NcsCt��kr5|jddjtt����n�|�dS(Nsrequires Tcl version >= R%(tget_tk_patchleveltskipTesttjointmaptstr(R(ttesttversion(s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytnewtest?s	(t	functoolstwraps(R+R-(R,(R+s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytdeco>s!(tlentunittestt
skipUnlessttcl_versionR(R)R*(R,R0((R,s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytrequires_tcl9s
cCs�tdkr�tj�}|jdd�}tjd|�}|j�\}}}}t|�t|�t|�}}}idd6dd6dd	6|}|dkr�||||d
faq�||d
||fantS(Ntinfot
patchlevels(\d+)\.(\d+)([ab.])(\d+)$talphatatbetatbtfinalR%i(	t_tk_patchlevelRRtTcltcalltretmatchtgroupstint(ttclR7tmtmajortminortreleaseleveltserial((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyR&Is&iHgR���Q@tctigffffff9@REitpcCst|d �t|dS(Ni����(tfloattunits(tvalue((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytpixels_conv_scCs�||krtSt|tj�rDt|t�rDt|�|kSnt|t�r�t|t�r�t|�t|�ko�td�t||�D��Snt	S(Ncss$|]\}}t||�VqdS(N(t
tcl_obj_eq(t.0tacttexp((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pys	<genexpr>ks(
tTruet
isinstancet_tkintertTcl_ObjR*ttupleR1talltzipR(tactualtexpected((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyRQbs	cCs]||krtSt|ttjf�rYt|ttjf�rYt|�t|�kSntS(N(RURVR*RtWidgetR(R\R]((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt	widget_eqos((R.R@R2tTkinterRRRR$RWRYR)RCtTCL_VERSIONtsplitR4R5RR=R&RNRPRQR_(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt<module>s&!			!		
		
PK'/�Zž��'�'test_ttk/test_extensions.pyonu�[����
zfc@s�ddlZddlZddlZddlZddlmZmZmZddl	m
Z
mZed�de
ejfd��YZ
de
ejfd��YZe
efZed	kr�ee�ndS(
i����N(trequirestrun_unittestt	swap_attr(tAbstractTkTesttdestroy_default_roottguitLabeledScaleTestcBsGeZd�Zd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs$|jj�tt|�j�dS(N(troottupdate_idletaskstsuperRttearDown(tself((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
s
cCsltj|j�}|jj}|j�|jtj|j	j
|�tj|j�}|j}tj|jd|�}|j�|jr�|j
|j	j
|�|j��n(|j
t|j	j
|��|j��~|jtj|j	j
|�tj|j�}tj|jd|�}|j�tj|jd|�ttd�rh|jtjtj�ndS(Ntvariablet	last_type(tttktLabeledScaleRt	_variablet_nametdestroytassertRaisesttkintertTclErrorttktglobalgetvart	DoubleVartwantobjectstassertEqualtgettfloattIntVarthasattrtsystassertNotEqualR
(Rtxtvartmyvartname((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_widget_destroys&
	
	%(
cCs�ttdd���ttdt��izYtj�}|jtj�|j|j	tj�|j|j
tjj
�|j�Wdt�XWdQXWdQXdS(Nt
_default_roott_support_default_root(
RRtNonetTrueRRtassertIsNotNoneR&RtmasterRRR(RR!((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_initialization_no_master2scs�tj�j�}tj|�}�j|j|�|j�ddddtj	dtj	dff}�j
r}|d7}nxK|D]C}tj�jd|d�}�j|j|d�|j�q�Wtj�jdd	�}�jt
|jj�|j�tj�jdd�}�jt
|jj�|j�tj�jd
d�}tj�jd|�}�j|jd�|j�tj�jd|dd
�}�j|jd
��j|jj|j�|j��fd�}tj�jdd�}||jd|jd�|j�tj�jdd�}||jd|jd�|j�tj�jdd�}||jd|jd�|j�tj�j�}||jd|jd�|j��jtjtj|dd�dS(Nt0ii
i����ig@itfrom_s2.5tvalueiRg�?cs8�j|j�d|��j|j�d|�dS(Ntsidetanchor(Rt	pack_infot
place_info(tscalet	scale_postlabelt	label_pos(R(s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pytcheck_positionsastcompoundttoptbottomtntstunknowntatb(R-i(ii(i
i
(i����i����(g@i((g@i(RtFrameRRRRR+RRtmaxintRR/Rt
ValueErrorRRR(RRR4R6R(RR+R!tpassed_expectedtpairR#R8((Rs</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_initialization?sP
	 	









cCs^tj|jdddd�}|j�|j�|j�|jj�}|jj	�d}|j
|t|d��|jjdddd�|j�|jj	�d}|j
||�|jj�}|j
|jd|jr�dnd	�|j
|t|d��|jjdddd�|j
||�|j
|t|d��|j�dS(
NR.ittoi
R!i����ittextR-(RRRtpacktwait_visibilitytupdateR6R3R4tcoordsRtintt	configureR RR(Rtlscaletlinfo_1tprev_xcoordtcurr_xcoordtlinfo_2((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_horizontal_rangevs$



&cCsvtj|j�}|j�|j�|j�|jj�d}|jd}||_|j�|j	|j
d|jr�|n	t|��|j
|jj�d|�|j	|jj�dt|j
j�d��|jr�d�}nt}||jd�d|_|j�|j	||j
d�|�|j	|jj�dt|j
j�d��|j�dS(NiiRHR!cSs|S(N((R!((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt<lambda>�tRG(RRRRIRJRKR4RLR/RR6Rtstrt
assertGreaterRMR3R(RR!RRtnewvaltconv((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_variable_change�s,



	
	
cCs�tj|j�}|jdtdd�|j�|j�|jj�|jj	�}}|d|d}}d|_
|j�|jjd||f�|jt
|jj�d�|jj�d�|jjd||f�|j�dS(	Ntexpandtfilltbothiis%dx%dR!i(RRRRIR)RJRKR+twinfo_widthtwinfo_heightR/twm_geometryRRMR6R3R4RLR(RR!twidththeightt	width_newt
height_new((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_resize�s

	
(	t__name__t
__module__R
R%R,RFRTR[Rf(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
s		"	
	7		 tOptionMenuTestcBs>eZd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(R	RitsetUpRt	StringVarRttextvar(R((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRj�scCs|`tt|�j�dS(N(RlR	RiR
(R((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR
�scCs�tj|j�}tj|j|�}|j}|j�|j�|j|j	j
|�|j��~|jtj
|j	j
|�dS(N(RRkRRt
OptionMenuRRRRRRRRR(RR"toptmenuR$((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyR%�s	

"cCs�|jtjtj|j|jdd�tj|j|jddd�}|j|jj	�d�|j
|d�|j
|d�|j�dS(NtinvalidtthingR@R?tmenuttextvariable(RRRRRmRRlRRRt
assertTrueR(RRn((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRF�s!c	s7d
�d}tj�j�j|��}t}xYtt���D]E}|dj|d�}�j|�|�||krCt	}qCqCW�j
|�|j�d}tj�j�j|��}d}d}xQt	r&||dj
|d�}}||kr	Pn�j||�|d7}q�W�j|t���|j�|j�|djd��j|jj��d��jtj|djd	��j|jj��d�|j�g����fd
�}tj�j�jdd|��}|djd��s)�jd�n|j�dS(NR?R@tcRqR/tdiii����cs%�j|�d��jt�dS(Ni(RtappendR)(titem(titemsRtsuccess(s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pytcb_teststcommandsMenu callback not invoked(R?R@Rt(RRmRRltFalsetrangetlent	entrycgetRR)RsRR(tentryconfigureR RIRJtinvokeRRRRRtfail(	RtdefaultRnt
found_defaulttiR/tcurrtlastRz((RxRRys</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt	test_menu�sJ


	


	cCs;d	}d}tj|j|j||�}tj|j�}tj|j|||�}|j�|j�|j�|j�|djd�|djd�|dj	dd�}|dj	dd�}|j
||�|j|jjj
|�|d�|j|jjj
|�|d�|j�|j�dS(
NR?R@RtRqiiiR(R?R@Rt(RRmRRlRRkRIRJR�RR RRRR(RRxR�Rnttextvar2toptmenu2toptmenu_stringvar_nametoptmenu2_stringvar_name((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyttest_unique_radiobuttonss*



	
(RgRhRjR
R%RFR�R�(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyRi�s				
	4t__main__(RtunittesttTkinterRRttest.test_supportRRRttest_ttk.supportRRtTestCaseRRit	tests_guiRg(((s</usr/lib64/python2.7/lib-tk/test/test_ttk/test_extensions.pyt<module>s
�qPK'/�ZM,�7��test_ttk/support.pynu�[���import functools
import re
import unittest
import Tkinter as tkinter

class AbstractTkTest:

    @classmethod
    def setUpClass(cls):
        cls._old_support_default_root = tkinter._support_default_root
        destroy_default_root()
        tkinter.NoDefaultRoot()
        cls.root = tkinter.Tk()
        cls.wantobjects = cls.root.wantobjects()
        # De-maximize main window.
        # Some window managers can maximize new windows.
        cls.root.wm_state('normal')
        try:
            cls.root.wm_attributes('-zoomed', False)
        except tkinter.TclError:
            pass

    @classmethod
    def tearDownClass(cls):
        cls.root.update_idletasks()
        cls.root.destroy()
        del cls.root
        tkinter._default_root = None
        tkinter._support_default_root = cls._old_support_default_root

    def setUp(self):
        self.root.deiconify()

    def tearDown(self):
        for w in self.root.winfo_children():
            w.destroy()
        self.root.withdraw()

def destroy_default_root():
    if getattr(tkinter, '_default_root', None):
        tkinter._default_root.update_idletasks()
        tkinter._default_root.destroy()
        tkinter._default_root = None

def simulate_mouse_click(widget, x, y):
    """Generate proper events to click at the x, y position (tries to act
    like an X server)."""
    widget.event_generate('<Enter>', x=0, y=0)
    widget.event_generate('<Motion>', x=x, y=y)
    widget.event_generate('<ButtonPress-1>', x=x, y=y)
    widget.event_generate('<ButtonRelease-1>', x=x, y=y)


import _tkinter
tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.')))

def requires_tcl(*version):
    if len(version) <= 2:
        return unittest.skipUnless(tcl_version >= version,
            'requires Tcl version >= ' + '.'.join(map(str, version)))

    def deco(test):
        @functools.wraps(test)
        def newtest(self):
            if get_tk_patchlevel() < version:
                self.skipTest('requires Tcl version >= ' +
                                '.'.join(map(str, version)))
            test(self)
        return newtest
    return deco

_tk_patchlevel = None
def get_tk_patchlevel():
    global _tk_patchlevel
    if _tk_patchlevel is None:
        tcl = tkinter.Tcl()
        patchlevel = tcl.call('info', 'patchlevel')
        m = re.match(r'(\d+)\.(\d+)([ab.])(\d+)$', patchlevel)
        major, minor, releaselevel, serial = m.groups()
        major, minor, serial = int(major), int(minor), int(serial)
        releaselevel = {'a': 'alpha', 'b': 'beta', '.': 'final'}[releaselevel]
        if releaselevel == 'final':
            _tk_patchlevel = major, minor, serial, releaselevel, 0
        else:
            _tk_patchlevel = major, minor, 0, releaselevel, serial
    return _tk_patchlevel

units = {
    'c': 72 / 2.54,     # centimeters
    'i': 72,            # inches
    'm': 72 / 25.4,     # millimeters
    'p': 1,             # points
}

def pixels_conv(value):
    return float(value[:-1]) * units[value[-1:]]

def tcl_obj_eq(actual, expected):
    if actual == expected:
        return True
    if isinstance(actual, _tkinter.Tcl_Obj):
        if isinstance(expected, str):
            return str(actual) == expected
    if isinstance(actual, tuple):
        if isinstance(expected, tuple):
            return (len(actual) == len(expected) and
                    all(tcl_obj_eq(act, exp)
                        for act, exp in zip(actual, expected)))
    return False

def widget_eq(actual, expected):
    if actual == expected:
        return True
    if isinstance(actual, (str, tkinter.Widget)):
        if isinstance(expected, (str, tkinter.Widget)):
            return str(actual) == str(expected)
    return False
PK'/�Z�d67�>�>test_ttk/test_functions.pyonu�[����
zfc@s�ddlZddlZddlZdfd��YZdefd��YZdefd��YZdejfd	��YZd
ejfd��YZ	ee	fZ
edkr�dd
lm
Z
e
e
�ndS(i����Nt	MockTkAppcBseZd�Zd�ZRS(cCs t|t�r|S|jd�S(Nt:(t
isinstancettupletsplit(tselftarg((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt	splitlistscCstS(N(tTrue(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytwantobjects
s(t__name__t
__module__RR	(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	t
MockTclObjcBs eZdZd�Zd�ZRS(ttestcCs
||_dS(N(tval(RR((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt__init__scCs
t|j�S(N(tunicodeR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt__str__s(R
RttypenameRR(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	t
MockStateSpeccBs eZdZd�Zd�ZRS(t	StateSpeccGs
||_dS(N(R(Rtargs((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRscCsdj|j�S(Nt (tjoinR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR!s(R
RRRR(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyRs	tInternalFunctionsTestcBsbeZd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d	�ZRS(
cs
�fd�}�jtji��|tjidd6ddddgd6�idd	6d
d6�|tjidBd6�idd6�|tjiidd6d6�iidd6d6�|tjiddddd
gd6dd6dd6dd6dd6dd6dd6dt�id d6d!d"6dd#6d$d%6d&d'6d(d)6d*d+6�itd,6td-6}|j�}|tj|�itd.6td/6��j||�|tjidCd26�id3d46�|tjidDd26�id6d46�|tjidEd26�id8d46�|tjidFd26�id:d46�|tjidGd26�id=d46�|tjidHd26�id?d46�ttj|d@d-��d}�j|t|�d�ttj|d@dI��d}�j|t|�d��jtj|d@|j���dS(JNcsfxEtdt|�d�D]+}�j|j||�||d�qW|rb�jd|�ndS(Niiisresult still got elements: %s(trangetlentassertEqualtpoptfail(tfmt_optstresultti(R(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt
check_against(s)tbluetfgiiiitpaddings-fgs1 2 3 4s-paddingtiR
s1 2 {} 0s-testsas istlefti����t2mttest2ttest3sabc defttest4s"abc"ttest5s{}ttest6s	} -spam {ttest7tscripts{1 -1 {} 2m 0}t3s-test2s-test3s	{abc def}s-test4s{"abc"}s-test5s\{\}s-test6s
\}\ -spam\ \{s-test7uαβγuáu-αβγu-ásone twotthreetoptions{one two} threes-optionsone	twos{one	two} threetones{} ones	one} {twosone\}\ \{two threes"one"ttwos{"one"} twos{one}s\{one\} twotignoretb(iiR%i(sone twoR0(sone	twoR0(R%R2(s	one} {twoR0(s"one"R3(s{one}R3(uáR5(	tassertFalsetttkt_format_optdictRtFalsetcopyRRtkeys(RR!toptst	orig_optstamount_opts((Rs;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_optdict'sl& $





cCsid!d"d#gd6}tj|�}|jt|�t|j��d	�|j|d$�|jtj|dt�d%�|jtjigd	6�d&�id'gd6}tj|�}|j|d(�id)gd6}|jtj|�d*�id+gd6}|jttj|�idgddfgd6}|jttj|�iddggd6}|jtj|�d,�xOddt	dt
�fD]5}i|dfgd6}|jtj|�d-�q�Widd6}|jttj|�|jttjid.gd6�dS(/NR5tcRtdtothervalR%tsingletais-as{b c} val d otherval {} singleR.s {{b c} val d otherval {} single}s-2uáuvãlu
üñíćódèu-üñíćódèuá vãluthitopts-opts{ } hiis	valid valt2tvalues1 valueis{} valuetinvalid(R5R@R(RARB(R%RC(s-as{b c} val d otherval {} single(s-as {{b c} val d otherval {} single}(s-2R%(uáuvãl(u-üñíćódèuá vãl(R%uRE(s-opts{ } hi(iis	valid val(s-opts1 value(s-opts{} value(RI(R7t_format_mapdictRRR;RtassertRaisest	TypeErrortNoneR9tsett
IndexError(RR<RtvalidRItstateval((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_mapdicts4& 
c
Cs�|jtjd�dd f�|jttjd�|jtjdtd�dd!f�|jtjdtdd"�dd#f�|jtjdtdd$�d	d%f�tjdtdd&dd
dd�}|j|dd
�|jt|d�dd
ddh�|jtjdt	dd'd
ddg�d(�|jt
tjd�|jtjdtdd�dd)f�|jtjdtddd*�dd+f�|jtjdtddd,dd
�dd-f�|jtjdt	ddddddgfdd
�d.�|jttjd�|jtjdtd�dd/f�|jtjdtdd�dd0f�|jtjdt	dd�d1�dS(2NtimageR
stest R%RDs	test {} aR5R@stest {a b} ctxtyistest a bis-as-bRAiis{test {a b c} d}s-x {2 3}tvsapisa b sa b {a b} cRFsa b a bs-opts{a b {a b} {1 2}}s-opt xtfroms{a}(((R%RD((RDR5R@((RDR5(RDR5R@RA(s{test {a b c} d}s-x {2 3}((RDR5R@((RDR5(s-optRT(s{a b {a b} {1 2}}s-opt x((R5(s{a}R5(t
assertTrueR7t_format_elemcreateRMRKRORR9RNRt
ValueError(Rtres((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_elemcreate�s<
&
"

cCspddd�}ddd�}|jtjg�dd�tjdgdd�}|j|tjdgdd��|j|dd�|j|�|��xRtd�D]D}|j||�||��|j|||�|||��q�W|jttjd	d
g�|jttjd�|jttjdg�|jttjdiidd6d
6fg�dS(NiicSsttjdidddgd6dididid	d
6fgd6dd6fgd6fgd6fgd
|d|�dS(NRDiiitotherR5R@RARFtnicetchildrent	somethingtindenttindent_sizei(ii(R7t_format_layoutlist(RaRb((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytsample�s;cs_d�fd�}d|�||�|d|�|d|�|d|�||�|�fS(Nicsd|�S(NR((tamount(Ra(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt<lambda>�R%si%sa -other {1 2 3} -children {
%sb -children {
%sc -something {1 2} -children {
%sd -nice opt
%s}
%s}
%s}ii((RaRbtspaces((Ras;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytsample_expected�s
R%RDRaitbadtformatR5tnameR_(RDN(RDR%(RDR5(	RR7RcRMRRKRZRLtAttributeError(RRdRhtsmallestR ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_format_layoutlist�s$
	&
	cCs�|jtjiidd6dd6dd6d6��|jtjiidd6d6�d�itd6td6}|jtjii|d6d6��idgd
6}|jtjii|d6d6��|jt	tjiidgd6d6�|jtjiiddgd6d6��iidddgd6d6}|jtj|�d�|ddj
idd6�|jtj|�d�td�td�g|dddd<|jtj|�d�dS(Nt	configuretmapselement createRktlayoutsttk::style layout name {
null
}uαβγuáuvãlu
üñíćódèRStstate1tstate2RtthingsAttk::style element create thing image {name {state1 state2} val} iRFsHttk::style element create thing image {name {state1 state2} val} -opt 30iR'i����sLttk::style element create thing image {name {state1 state2} val} -opt {3 2m}(uáuvãl(RrRsR(R6R7t_script_from_settingsRMRRR9RXRKROtappendR(Rt
configdicttmapdictRS((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_script_from_settingss4#		cCsf|jtjtdd�df�dg�|jtjtd�dtd�g�dddg�dS(	NRDR5Rt1it3mi(RDR5R(RR7t
_tclobj_to_pyRR(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_tclobj_to_pyGs
!cs��fd�}td�td�D��}t|�}||dd|�||td�d|�td�td�D��}t|�}||dd|�|d
td�dd�dS(Ncs-�jtj||f�||fg�dS(N(RR7t_list_from_statespec(tsspecRHt	res_valuetstates(R(s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_itQscss|]}d|VqdS(sstate%dN((t.0R ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pys	<genexpr>UsiRcss|]}d|VqdS(sstate%dN((R�R ((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pys	<genexpr>ZsiRDR5R@(RDR5R@(RDR5R@(RRRR(RR�tstates_event	statespect
states_odd((Rs;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_list_from_statespecPsc	Cstt�}|jtj|d��|jtj|d�difg�d}|jtj||�didd6fg�|jtj|dddf�digd6fg�ddddd	ddddff}|jtj||�didd6d	idd
6d
ifgd6fgd6fg�|jttj|d�|jttj|d�|jttj|d�dS(NRks-optionRHR1R`s	-childrenR_tniceonetotheronetchilds	-otheroptt
othervaluetotheropttno_minus((Rk(Rks-optionRH((R�(RkR�(RkR�RH(R`s	-children(RR6R7t_list_from_layouttupleRRKRZ(Rttkt
sample_ltupletltuple((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_list_from_layouttupleas.	

$cCs�ddd�}t�}||_|jtj|id�idd6�|jtj|id	�idd6�|jtj|idd6d�d�|jtj|idd6d�idd6�dS(
NcSs*|dkr|S|dkr dS||fS(Nstest val(RM(R[RFR((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pytfunc�s
s-test:3R/R
s-testisx:ystest val(s-testi(RMRtcallRR7t_val_or_dict(RR�R�((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_val_or_dict�s		cCs}d
ddd
gdfdf}x-|D]%\}}|jtj|�|�q%Wtj�dkry|jttjd	�ndS(Nit09i	RDuáÚs[]RMtasciisá(ii(R�i	(RDRD(uáÚuáÚ(NRM(RMRR7t_convert_stringvaltsystgetdefaultencodingRKtUnicodeDecodeError(Rtteststorigtexpected((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_convert_stringval�s		(R
RR?RRR\RnRyR}R�R�R�R�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR%s	X	)	=	7	+				.	tTclObjsToPyTestcBs#eZd�Zd�Zd�ZRS(cCseidd6}|jtj|�idd6�t|d�|d<|jtj|�idd6�dS(NuvälúèRF(RR7t
tclobjs_to_pyR(Rtadict((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_unicode�s
 cCs�iddddgd6}|jtj|�iddddgd6�dddg|d<|jtj|�idddgd6�tdd�d	f|d<|jtj|�idgd6�|jtjid
gd6�id
gd6�dS(
NiiiiRFtxmRDR5uválũèsy zRT(RDR5uválũè(RR7R�R(RR�((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_multivalues�s,)cCs+|jtjidd6�idd6�dS(Ns	some textttext(RR7R�(R((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyttest_nosplit�s(R
RR�R�R�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyR��s		t__main__(trun_unittest(R�tunittestR7RtobjectRRtTestCaseRR�ttests_noguiR
ttest.test_supportR�(((s;/usr/lib64/python2.7/lib-tk/test/test_ttk/test_functions.pyt<module>s

��PK'/�ZB���,�,test_ttk/test_extensions.pynu�[���import sys
import unittest
import Tkinter as tkinter
import ttk
from test.test_support import requires, run_unittest, swap_attr
from test_ttk.support import AbstractTkTest, destroy_default_root

requires('gui')

class LabeledScaleTest(AbstractTkTest, unittest.TestCase):

    def tearDown(self):
        self.root.update_idletasks()
        super(LabeledScaleTest, self).tearDown()

    def test_widget_destroy(self):
        # automatically created variable
        x = ttk.LabeledScale(self.root)
        var = x._variable._name
        x.destroy()
        self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var)

        # manually created variable
        myvar = tkinter.DoubleVar(self.root)
        name = myvar._name
        x = ttk.LabeledScale(self.root, variable=myvar)
        x.destroy()
        if self.wantobjects:
            self.assertEqual(x.tk.globalgetvar(name), myvar.get())
        else:
            self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get())
        del myvar
        self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name)

        # checking that the tracing callback is properly removed
        myvar = tkinter.IntVar(self.root)
        # LabeledScale will start tracing myvar
        x = ttk.LabeledScale(self.root, variable=myvar)
        x.destroy()
        # Unless the tracing callback was removed, creating a new
        # LabeledScale with the same var will cause an error now. This
        # happens because the variable will be set to (possibly) a new
        # value which causes the tracing callback to be called and then
        # it tries calling instance attributes not yet defined.
        ttk.LabeledScale(self.root, variable=myvar)
        if hasattr(sys, 'last_type'):
            self.assertNotEqual(sys.last_type, tkinter.TclError)


    def test_initialization_no_master(self):
        # no master passing
        with swap_attr(tkinter, '_default_root', None), \
             swap_attr(tkinter, '_support_default_root', True):
            try:
                x = ttk.LabeledScale()
                self.assertIsNotNone(tkinter._default_root)
                self.assertEqual(x.master, tkinter._default_root)
                self.assertEqual(x.tk, tkinter._default_root.tk)
                x.destroy()
            finally:
                destroy_default_root()

    def test_initialization(self):
        # master passing
        master = tkinter.Frame(self.root)
        x = ttk.LabeledScale(master)
        self.assertEqual(x.master, master)
        x.destroy()

        # variable initialization/passing
        passed_expected = (('0', 0), (0, 0), (10, 10),
            (-1, -1), (sys.maxint + 1, sys.maxint + 1))
        if self.wantobjects:
            passed_expected += ((2.5, 2),)
        for pair in passed_expected:
            x = ttk.LabeledScale(self.root, from_=pair[0])
            self.assertEqual(x.value, pair[1])
            x.destroy()
        x = ttk.LabeledScale(self.root, from_='2.5')
        self.assertRaises(ValueError, x._variable.get)
        x.destroy()
        x = ttk.LabeledScale(self.root, from_=None)
        self.assertRaises(ValueError, x._variable.get)
        x.destroy()
        # variable should have its default value set to the from_ value
        myvar = tkinter.DoubleVar(self.root, value=20)
        x = ttk.LabeledScale(self.root, variable=myvar)
        self.assertEqual(x.value, 0)
        x.destroy()
        # check that it is really using a DoubleVar
        x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5)
        self.assertEqual(x.value, 0.5)
        self.assertEqual(x._variable._name, myvar._name)
        x.destroy()

        # widget positionment
        def check_positions(scale, scale_pos, label, label_pos):
            self.assertEqual(scale.pack_info()['side'], scale_pos)
            self.assertEqual(label.place_info()['anchor'], label_pos)
        x = ttk.LabeledScale(self.root, compound='top')
        check_positions(x.scale, 'bottom', x.label, 'n')
        x.destroy()
        x = ttk.LabeledScale(self.root, compound='bottom')
        check_positions(x.scale, 'top', x.label, 's')
        x.destroy()
        # invert default positions
        x = ttk.LabeledScale(self.root, compound='unknown')
        check_positions(x.scale, 'top', x.label, 's')
        x.destroy()
        x = ttk.LabeledScale(self.root) # take default positions
        check_positions(x.scale, 'bottom', x.label, 'n')
        x.destroy()

        # extra, and invalid, kwargs
        self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b')


    def test_horizontal_range(self):
        lscale = ttk.LabeledScale(self.root, from_=0, to=10)
        lscale.pack()
        lscale.wait_visibility()
        lscale.update()

        linfo_1 = lscale.label.place_info()
        prev_xcoord = lscale.scale.coords()[0]
        self.assertEqual(prev_xcoord, int(linfo_1['x']))
        # change range to: from -5 to 5. This should change the x coord of
        # the scale widget, since 0 is at the middle of the new
        # range.
        lscale.scale.configure(from_=-5, to=5)
        # The following update is needed since the test doesn't use mainloop,
        # at the same time this shouldn't affect test outcome
        lscale.update()
        curr_xcoord = lscale.scale.coords()[0]
        self.assertNotEqual(prev_xcoord, curr_xcoord)
        # the label widget should have been repositioned too
        linfo_2 = lscale.label.place_info()
        self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0')
        self.assertEqual(curr_xcoord, int(linfo_2['x']))
        # change the range back
        lscale.scale.configure(from_=0, to=10)
        self.assertNotEqual(prev_xcoord, curr_xcoord)
        self.assertEqual(prev_xcoord, int(linfo_1['x']))

        lscale.destroy()


    def test_variable_change(self):
        x = ttk.LabeledScale(self.root)
        x.pack()
        x.wait_visibility()
        x.update()

        curr_xcoord = x.scale.coords()[0]
        newval = x.value + 1
        x.value = newval
        # The following update is needed since the test doesn't use mainloop,
        # at the same time this shouldn't affect test outcome
        x.update()
        self.assertEqual(x.label['text'],
                         newval if self.wantobjects else str(newval))
        self.assertGreater(x.scale.coords()[0], curr_xcoord)
        self.assertEqual(x.scale.coords()[0],
            int(x.label.place_info()['x']))

        # value outside range
        if self.wantobjects:
            conv = lambda x: x
        else:
            conv = int
        x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen
        x.update()
        self.assertEqual(conv(x.label['text']), newval)
        self.assertEqual(x.scale.coords()[0],
            int(x.label.place_info()['x']))

        x.destroy()


    def test_resize(self):
        x = ttk.LabeledScale(self.root)
        x.pack(expand=True, fill='both')
        x.wait_visibility()
        x.update()

        width, height = x.master.winfo_width(), x.master.winfo_height()
        width_new, height_new = width * 2, height * 2

        x.value = 3
        x.update()
        x.master.wm_geometry("%dx%d" % (width_new, height_new))
        self.assertEqual(int(x.label.place_info()['x']),
            x.scale.coords()[0])

        # Reset geometry
        x.master.wm_geometry("%dx%d" % (width, height))
        x.destroy()


class OptionMenuTest(AbstractTkTest, unittest.TestCase):

    def setUp(self):
        super(OptionMenuTest, self).setUp()
        self.textvar = tkinter.StringVar(self.root)

    def tearDown(self):
        del self.textvar
        super(OptionMenuTest, self).tearDown()


    def test_widget_destroy(self):
        var = tkinter.StringVar(self.root)
        optmenu = ttk.OptionMenu(self.root, var)
        name = var._name
        optmenu.update_idletasks()
        optmenu.destroy()
        self.assertEqual(optmenu.tk.globalgetvar(name), var.get())
        del var
        self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name)


    def test_initialization(self):
        self.assertRaises(tkinter.TclError,
            ttk.OptionMenu, self.root, self.textvar, invalid='thing')

        optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b')
        self.assertEqual(optmenu._variable.get(), 'b')

        self.assertTrue(optmenu['menu'])
        self.assertTrue(optmenu['textvariable'])

        optmenu.destroy()


    def test_menu(self):
        items = ('a', 'b', 'c')
        default = 'a'
        optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items)
        found_default = False
        for i in range(len(items)):
            value = optmenu['menu'].entrycget(i, 'value')
            self.assertEqual(value, items[i])
            if value == default:
                found_default = True
        self.assertTrue(found_default)
        optmenu.destroy()

        # default shouldn't be in menu if it is not part of values
        default = 'd'
        optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items)
        curr = None
        i = 0
        while True:
            last, curr = curr, optmenu['menu'].entryconfigure(i, 'value')
            if last == curr:
                # no more menu entries
                break
            self.assertNotEqual(curr, default)
            i += 1
        self.assertEqual(i, len(items))

        # check that variable is updated correctly
        optmenu.pack()
        optmenu.wait_visibility()
        optmenu['menu'].invoke(0)
        self.assertEqual(optmenu._variable.get(), items[0])

        # changing to an invalid index shouldn't change the variable
        self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1)
        self.assertEqual(optmenu._variable.get(), items[0])

        optmenu.destroy()

        # specifying a callback
        success = []
        def cb_test(item):
            self.assertEqual(item, items[1])
            success.append(True)
        optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test,
            *items)
        optmenu['menu'].invoke(1)
        if not success:
            self.fail("Menu callback not invoked")

        optmenu.destroy()

    def test_unique_radiobuttons(self):
        # check that radiobuttons are unique across instances (bpo25684)
        items = ('a', 'b', 'c')
        default = 'a'
        optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items)
        textvar2 = tkinter.StringVar(self.root)
        optmenu2 = ttk.OptionMenu(self.root, textvar2, default, *items)
        optmenu.pack()
        optmenu.wait_visibility()
        optmenu2.pack()
        optmenu2.wait_visibility()
        optmenu['menu'].invoke(1)
        optmenu2['menu'].invoke(2)
        optmenu_stringvar_name = optmenu['menu'].entrycget(0, 'variable')
        optmenu2_stringvar_name = optmenu2['menu'].entrycget(0, 'variable')
        self.assertNotEqual(optmenu_stringvar_name,
                            optmenu2_stringvar_name)
        self.assertEqual(self.root.tk.globalgetvar(optmenu_stringvar_name),
                         items[1])
        self.assertEqual(self.root.tk.globalgetvar(optmenu2_stringvar_name),
                         items[2])

        optmenu.destroy()
        optmenu2.destroy()


tests_gui = (LabeledScaleTest, OptionMenuTest)

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK'/�Z@
S���test_ttk/support.pyonu�[����
zfc@s�ddlZddlZddlZddlZddd��YZd�Zd�ZddlZe	e
eejj
d���Zd�Zdad�Zid	d
d6d	d6d	d
d6dd6Zd�Zd�Zd�ZdS(i����NtAbstractTkTestcBs8eZed��Zed��Zd�Zd�ZRS(cCs�tj|_t�tj�tj�|_|jj�|_|jjd�y|jj	dt
�Wntjk
r{nXdS(Ntnormals-zoomed(ttkintert_support_default_roott_old_support_default_roottdestroy_default_roott
NoDefaultRoottTktroottwantobjectstwm_statet
wm_attributestFalsetTclError(tcls((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt
setUpClasss
cCs9|jj�|jj�|`dt_|jt_dS(N(Rtupdate_idletaskstdestroytNoneRt
_default_rootRR(R((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt
tearDownClasss


	cCs|jj�dS(N(Rt	deiconify(tself((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytsetUpscCs5x!|jj�D]}|j�qW|jj�dS(N(Rtwinfo_childrenRtwithdraw(Rtw((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyttearDown"s(t__name__t
__module__tclassmethodRRRR(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyRs	cCs<ttdd�r8tjj�tjj�dt_ndS(NR(tgetattrRRRRR(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyR's

cCsh|jddddd�|jdd|d|�|jdd|d|�|jdd|d|�dS(	sYGenerate proper events to click at the x, y position (tries to act
    like an X server).s<Enter>txitys<Motion>s<ButtonPress-1>s<ButtonRelease-1>N(tevent_generate(twidgetR R!((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytsimulate_mouse_click-st.csQt��dkr>tjt�kddjtt����S�fd�}|S(Nisrequires Tcl version >= R%cs%tj����fd��}|S(NcsCt��kr5|jddjtt����n�|�dS(Nsrequires Tcl version >= R%(tget_tk_patchleveltskipTesttjointmaptstr(R(ttesttversion(s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytnewtest?s	(t	functoolstwraps(R+R-(R,(R+s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytdeco>s!(tlentunittestt
skipUnlessttcl_versionR(R)R*(R,R0((R,s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytrequires_tcl9s
cCs�tdkr�tj�}|jdd�}tjd|�}|j�\}}}}t|�t|�t|�}}}idd6dd6dd	6|}|dkr�||||d
faq�||d
||fantS(Ntinfot
patchlevels(\d+)\.(\d+)([ab.])(\d+)$talphatatbetatbtfinalR%i(	t_tk_patchlevelRRtTcltcalltretmatchtgroupstint(ttclR7tmtmajortminortreleaseleveltserial((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyR&Is&iHgR���Q@tctigffffff9@REitpcCst|d �t|dS(Ni����(tfloattunits(tvalue((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pytpixels_conv_scCs�||krtSt|tj�rDt|t�rDt|�|kSnt|t�r�t|t�r�t|�t|�ko�td�t||�D��Snt	S(Ncss$|]\}}t||�VqdS(N(t
tcl_obj_eq(t.0tacttexp((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pys	<genexpr>ks(
tTruet
isinstancet_tkintertTcl_ObjR*ttupleR1talltzipR(tactualtexpected((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyRQbs	cCs]||krtSt|ttjf�rYt|ttjf�rYt|�t|�kSntS(N(RURVR*RtWidgetR(R\R]((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt	widget_eqos((R.R@R2tTkinterRRRR$RWRYR)RCtTCL_VERSIONtsplitR4R5RR=R&RNRPRQR_(((s4/usr/lib64/python2.7/lib-tk/test/test_ttk/support.pyt<module>s&!			!		
		
PK'/�Zܐ��bbtest_ttk/test_style.pynu�[���import unittest
import Tkinter as tkinter
import ttk
from test.test_support import requires, run_unittest
from test_ttk.support import AbstractTkTest

requires('gui')

class StyleTest(AbstractTkTest, unittest.TestCase):

    def setUp(self):
        super(StyleTest, self).setUp()
        self.style = ttk.Style(self.root)


    def test_configure(self):
        style = self.style
        style.configure('TButton', background='yellow')
        self.assertEqual(style.configure('TButton', 'background'),
            'yellow')
        self.assertIsInstance(style.configure('TButton'), dict)


    def test_map(self):
        style = self.style
        style.map('TButton', background=[('active', 'background', 'blue')])
        self.assertEqual(style.map('TButton', 'background'),
            [('active', 'background', 'blue')] if self.wantobjects else
            [('active background', 'blue')])
        self.assertIsInstance(style.map('TButton'), dict)


    def test_lookup(self):
        style = self.style
        style.configure('TButton', background='yellow')
        style.map('TButton', background=[('active', 'background', 'blue')])

        self.assertEqual(style.lookup('TButton', 'background'), 'yellow')
        self.assertEqual(style.lookup('TButton', 'background',
            ['active', 'background']), 'blue')
        self.assertEqual(style.lookup('TButton', 'optionnotdefined',
            default='iknewit'), 'iknewit')


    def test_layout(self):
        style = self.style
        self.assertRaises(tkinter.TclError, style.layout, 'NotALayout')
        tv_style = style.layout('Treeview')

        # "erase" Treeview layout
        style.layout('Treeview', '')
        self.assertEqual(style.layout('Treeview'),
            [('null', {'sticky': 'nswe'})]
        )

        # restore layout
        style.layout('Treeview', tv_style)
        self.assertEqual(style.layout('Treeview'), tv_style)

        # should return a list
        self.assertIsInstance(style.layout('TButton'), list)

        # correct layout, but "option" doesn't exist as option
        self.assertRaises(tkinter.TclError, style.layout, 'Treeview',
            [('name', {'option': 'inexistent'})])


    def test_theme_use(self):
        self.assertRaises(tkinter.TclError, self.style.theme_use,
            'nonexistingname')

        curr_theme = self.style.theme_use()
        new_theme = None
        for theme in self.style.theme_names():
            if theme != curr_theme:
                new_theme = theme
                self.style.theme_use(theme)
                break
        else:
            # just one theme available, can't go on with tests
            return

        self.assertFalse(curr_theme == new_theme)
        self.assertFalse(new_theme != self.style.theme_use())

        self.style.theme_use(curr_theme)


tests_gui = (StyleTest, )

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK'/�Z8����test_ttk/test_widgets.pyonu�[����
zfc@sUddlZddlZddlmZddlZddlmZmZmZm	Z	ddl
Z
ddlmZddl
mZmZmZmZddlmZmZmZmZmZmZmZmZed�defd	��YZd
eejfd��YZdeefd
��YZee�deejfd��Y�Zee�deejfd��Y�Z defd��YZ!ee�de!ejfd��Y�Z"ee�de!ejfd��Y�Z#ee�de!ejfd��Y�Z$eee�deejfd��Y�Z%eee�de%ejfd��Y�Z&eee�deejfd��Y�Z'ee�d e!ejfd!��Y�Z(d"e!ejfd#��YZ)ee�d$eejfd%��Y�Z*ee�d&eejfd'��Y�Z+ej,e
j-d(kd)�ee�d*eejfd+��Y��Z.eee�d,eejfd-��Y�Z/ee�d.eejfd/��Y�Z0ee�d0eejfd1��Y�Z1ee�d2eejfd3��Y�Z2e#e$e&e%ee e"e)e/e'e+e(e*e.e1e2e0efZ3e4d4krQee3�ndS(5i����N(tTclError(trequirestrun_unittestthave_unicodetu(t
MockTclObj(tAbstractTkTestttcl_versiontget_tk_patchleveltsimulate_mouse_click(tadd_standard_optionstnoconvtnoconv_methtAbstractWidgetTesttStandardOptionsTeststIntegerSizeTeststPixelSizeTeststsetUpModuletguitStandardTtkOptionsTestscBs#eZd�Zd�Zd�ZRS(cCs�|j�}|j|dd�d}t�d
kr>d	}n|j|dd
d|�|jdd
�}|j|dd
�dS(Ntclassts"attempt to change read-only optioniiitbetais"Attempt to change read-only optiontFooterrmsgtclass_(iiiRi(tcreatetassertEqualRtcheckInvalidParam(tselftwidgetRtwidget2((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_classs	c	Cs�|j�}|j|dddd�|j|dddd�|j|dddd�|j|dddd�|j|dddd�|j|dd�|j|dddd�dS(Ntpaddingitexpectedt0it5it6it7it8t5pt6pt7pt8pR(R#(R$(ii(R$R%(iii(R$R%R&(iiii(R$R%R&R'(R(R)R*R+((Rt
checkParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_paddingscCs�|j�}|j|dd�d}t|d�rQdt|d�j�}n|j|ddd|�|jdd�}|j|d	d�dS(
NtstyleRsLayout Foo not foundtdefault_orientsLayout %s.Foo not foundRRRR(RRthasattrtgetattrttitleR(RRRR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_style+s(t__name__t
__module__R R-R3(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRs	
	t
WidgetTestcBs)eZdZd�Zd�Zd�ZRS(s,Tests methods available in every ttk widget.cCsRtt|�j�tj|jdddd�|_|jj�|jj�dS(NtwidthittexttText(	tsuperR6tsetUptttktButtontrootRtpacktwait_visibility(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;=s!
cCs�|jj�|j|jj|jj�d|jj�d�d�|j|jjdd�d�|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�dS(Nitlabeli����Ri(
Rtupdate_idletasksRtidentifytwinfo_widthtwinfo_heighttassertRaisesttkinterRtNone(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_identifyDs
cCs�|j|jj�d
�|j|jjdg�t�|j|jjdg�d�|j|jjdg�d�|j|jjddg�d
�|j|jjddg�d�|j|jjddg�d�d�}|j|jjdg|didd6�didd6f�|jj�}|jtj|jjd	g�|jtj|jjdd	g�|j||jj��|jjddg�|j|jj�d�dS(Ns	!disabledtdisabledtactives!activec[s
||fS(N((targ1tkw((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_cbasthittheretmsgtbadstate((s	!disabled((s!activeRJ(((RK(RRtstatetinstatetTrueRFRGR(RRNt	currstate((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_widget_stateQs(""	

(R4R5t__doc__R;RIRW(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR6:s		
tAbstractToplevelTestcBseZeZRS((R4R5Rt_conv_pixels(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRYust	FrameTestc	BseZd
Zd	�ZRS(tborderwidthRtcursortheightR!treliefR.t	takefocusR7cKstj|j|�S(N(R<tFrameR>(Rtkwargs((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(	R\RR]R^R!R_R.R`R7(R4R5tOPTIONSR(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR[ystLabelFrameTestc
Bs)eZdZd
�Zd�Zd�ZRS(R\RR]R^tlabelanchortlabelwidgetR!R_R.R`R8t	underlineR7cKstj|j|�S(N(R<t
LabelFrameR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs]|j�}|j|ddddddddd	d
ddd
dd�|j|dd�dS(NRetetentestntnetnwtstsetswtwtwntwsRs!Bad label anchor specification {}tcenter(RtcheckEnumParamR(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_labelanchor�s
'cCsQ|j�}tj|jdddd�}|j|d|dd�|j�dS(NR8tMupptnametfooRfR"s.foo(RR<tLabelR>R,tdestroy(RRRA((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_labelwidget�s(
R\RR]R^ReRfR!R_R.R`R8RgR7(R4R5RcRRwR}(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRd�s		tAbstractLabelTestcBs,eZd�Zd�Zd�Zd�ZRS(cCs�tjd|jdd�}tjd|jdd�}|j|||dd�|j||ddd�|j|||fdd
�|j|||d|fdd�|j||ddd�|j||dd	d
�dS(NtmasterRytimage1timage2R"RKsimage1 active image2tspamRsimage "spam" doesn't exist(R�(R�(R�(R�RKR�(R�RKR�(RGt
PhotoImageR>R,R(RRRytimageR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcheckImageParam�scCs8|j�}|j|ddddddddd	�
dS(
NtcompoundtnoneR8R�Ruttoptbottomtlefttright(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_compound�scCs)|j�}|j|dddd�dS(NRSRKRJtnormal(RtcheckParams(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_state�scCs)|j�}|j|dddd�dS(NR7i�in���i(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_width�s(R4R5R�R�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR~�s	
		t	LabelTestcBs&eZdZeZd�Zd�ZRS(tanchort
backgroundR\RR�R]tfontt
foregroundR�tjustifyR!R_RSR.R`R8ttextvariableRgR7t
wraplengthcKstj|j|�S(N(R<R{R>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs#|j�}|j|dd�dS(NR�s3-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*(RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_font�s(R�R�R\RR�R]R�R�R�R�R!R_RSR.R`R8R�RgR7R�(R4R5RcRRZRR�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s	t
ButtonTestcBs)eZdZd�Zd�Zd�ZRS(RtcommandR�R]tdefaultR�R!RSR.R`R8R�RgR7cKstj|j|�S(N(R<R=R>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR�R�RKRJ(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_default�scsBg�tj|jd�fd��}|j�|j��dS(NR�cs
�jd�S(Ni(tappend((tsuccess(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt<lambda>�R(R<R=R>tinvoket
assertTrue(Rtbtn((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_invoke�s!
(RR�R�R]R�R�R!RSR.R`R8R�RgR7(R4R5RcRR�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s		tCheckbuttonTestcBs2eZdZd�Zd�Zd�Zd�ZRS(RR�R�R]R�toffvaluetonvalueR!RSR.R`R8R�RgtvariableR7cKstj|j|�S(N(R<tCheckbuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_offvalue�scCs,|j�}|j|ddddd�dS(NR�igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_onvalue�scsg��fd�}tj|jd|�}|j|j�d
�|jtj|jj	|d�|j
�}|j|d�|j|d|jj	|d��|j��d|d<|j
�}|jt
|��|jt��d�|j|d	|jj	|d��dS(Ncs�jd�dS(Niscb test called(R�((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcb_tests
R�t	alternateR�scb test calledR�RiR�(R�(R<R�R>RRSRFRGRttktglobalgetvarR�R�tassertFalsetstrtassertLessEqualtlen(RR�tcbtntres((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s"



(RR�R�R]R�R�R�R!RSR.R`R8R�RgR�R7(R4R5RcRR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s			t	EntryTestcBszeZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(R�RR]texportselectionR�R�tinvalidcommandR�tshowRSR.R`R�tvalidatetvalidatecommandR7txscrollcommandcCs&tt|�j�|j�|_dS(N(R:R�R;Rtentry(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;#scKstj|j|�S(N(R<tEntryR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR'scCs |j�}|j|d�dS(NR�(RtcheckCommandParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_invalidcommand*scCsI|j�}|j|dd�|j|dd�|j|dd�dS(NR�t*Rt (RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_show.scCs)|j�}|j|dddd�dS(NRSRJR�treadonly(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�4sc	Cs2|j�}|j|ddddddd�dS(NR�talltkeytfocustfocusintfocusoutR�(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_validate9scCs |j�}|j|d�dS(NR�(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validatecommand>scCsU|j|jjd��|jtj|jjd�|jtj|jjd�dS(Nitnoindex(tassertIsBoundingBoxR�tbboxRFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_bboxCscCs�|jj�|jj�|jj�tjdkrX|j|jjdd�d�n|j|jjdd�d�|j|jjdd�d�|j	t
j|jjdd�|j	t
j|jjdd�|j	t
j|jjdd�dS(NtdarwinittextareasCombobox.buttoni����R(R�sCombobox.button(
R�R?R@RBtsystplatformtassertInRCRRFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRIIs



cs#g��fd�}d|jd<d�|jd<||jd<|jj�|j��d|jd<|jj�|jt��d�||jd<d	�|jd<|jj�|jt��d�d|jd<|jj�|jt��d�t|jd<|jtj|jj�dS(
Ncs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�]RR�R�cSstS(N(tFalse(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�`RR�R�RicSstS(N(RU(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�kR(	R�R�R�RR�RURFRGR(Rttest_invalid((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validation_options[s&










cs�g��fd�}d|jd<|jj|�df|jd<|jjdd�|jjdd�|j�ttg�|j|jj�d�dS(	NcsDd|j�kodkns3�jt�tS�jt�tS(Ntatz(tlowerR�R�RU(t	to_insert(t
validation(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�ys
"

R�R�s%SR�tendiR�(R�tregistertinsertRR�RUtget(RR�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validationws
cCs$d�}|jj|�df|jd<|jjdd�|j|jj�t�|j|jj�d�|jjdd�|j|jj�d�|jjdd�|j|jj�t	�|j|jj�d�|jjd
�|j|jj�t�|j|jj�d
�dS(NcSs;x4|D],}d|j�ko*dknstSqWtS(NR�R�(R�R�RU(tcontenttletter((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s
"s%PR�R�tavocadoiRta1btinvalidi((R�((
R�R�R�RR�RURStdeleteR�R�(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_revalidation�s	(R�RR]R�R�R�R�R�R�RSR.R`R�R�R�R7R�(R4R5RcR;RR�R�R�R�R�R�RIR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s"											tComboboxTestcBsMeZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	RS(R�RR]R�R�R�R^R�R�tpostcommandR�RSR.R`R�R�R�tvaluesR7R�cCs&tt|�j�|j�|_dS(N(R:R�R;Rtcombo(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�scKstj|j|�S(N(R<tComboboxR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�sc	Cs2|j�}|j|ddddddd�dS(NR^idg�����LY@gfffff�Y@i����it1i(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_height�scCs`|jj�}|jjdd|ddd�|jjdd|ddd�|jj�dS(Ns<ButtonPress-1>txitys<ButtonRelease-1>(R�RDtevent_generateRB(RR7((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt_show_drop_down_listbox�s  cs�g�dg|jd<|jjd�fd��|jj�|jj�|jj�}|j�|jj�|jjd�|jj�|j��dS(NiR�s<<ComboboxSelected>>cs
�jt�S(N(R�RU(tevt(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��Rs<Return>(	R�tbindR?R@RER�tupdateR�R�(RR^((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_virtual_event�s




cs~g��fd�|jd<|jj�|jj�|j�|j��d|jd<|j�|jt��d�dS(Ncs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��RR�Ri(R�R?R@R�R�RR�(R((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_postcommand�s





c	s��fd�}�j�jdtd#kr1d$nd�|dd��j�jdddd%��j�jdd&��j�jdd'��j�jdtd(kr�d)nd�dddg�jd<�jjd�|dd��jjd�|dd��jjd�|dd��jjd�d*�jd<|dd��jjddddg��j�jd�jr�d+nd�dddg�jd<�j�jd�jr�d,nd�ddd g�jd<�j�jd�jr�d-nd!��jt	j
�jjt�jd���jt	j
�jjd�tj
�jddddg�}�j|d�jr�d.nd"�|j�dS(/Ncs6�j�jj�|��j�jj�|�dS(N(RR�R�tcurrent(tgetvaltcurrval(R(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcheck_get_current�sR�iiRi����smon tue wed thurR"tmonttuetwedtthuri*g��Q�	@s
any stringR�itciitdit1t2s1 {} 2sa bsa	bsa
bs{a b} {a	b} {a
b}sa\tbs"a"s} {sa\\tb {"a"} \}\ \{s1 2 {}(ii((R�R�R�R(R�R�R�R(i*g��Q�	@Rs
any string(ii((iiRi(RRR(sa bsa	bsa
b(sa\tbs"a"s} {(RRR(RR�RR,tsetR�t	configuretwantobjectsRFRGRR�R<R�R>R|(RR�tcombo2((Rs9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_values�sL
(




!
(R�RR]R�R�R�R^R�R�R�R�RSR.R`R�R�R�R�R7R�(
R4R5RcR;RR�R�R�R�R	(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s						tPanedWindowTestcBsVeZdZd�Zd�Zd	�Zd
�Zd�Zd�Zd
�Z	d�Z
RS(RR]R^torientR.R`R7cCs&tt|�j�|j�|_dS(N(R:R
R;Rtpaned(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;&scKstj|j|�S(N(R<tPanedWindowR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR*scCs�|j�}|jt|d�d�d}t�dkrDd	}n|j|dd
d|�|jdd
�}|jt|d�d
�dS(
NRtverticals"attempt to change read-only optioniiiRis"Attempt to change read-only optiont
horizontalR(iiiRi(RRR�RR(RRRR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_orient-s	cCsztj|j�}tj|�}|jtj|jj|�|j�|j�tj|j�}tj|�}|jtj|jj|�|j�|j�tj|j�}|jj|�|jtj|jj|�tj|j�}|jj|�|j	|jj
d�|jj
d��|jtj|jj
d�|j�|j�|jtj|jj
d�dS(Niii(R<R{RRFRGRtaddR|R>Rtpane(RRAtchildt
good_childtother_child((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_add8s(



(

cCs�|jtj|jjd�|jtj|jjd�|jjtj|j	��|jjd�|jtj|jjd�dS(Ni(
RFRGRRtforgetRHRR<R{R>(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_forgetTs
cCs|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�tj|j�}tj|j�}tj|j�}|jtj|jjd|�|jjd|�|jjd|�|j	|jj
�t|�t|�f�|jjd|�|j	|jj
�t|�t|�f�|jjd|�|j	|jj
�t|�t|�t|�f�|jj
�}|jjd|�|j	||jj
��|jj||�|j	|jj
�t|�t|�t|�f�dS(NiR�(RFRGRRR�RHR<R{R>RtpanesR�(RRtchild2tchild3R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_insert]s*++"cCs
|jtj|jjd�tj|j�}|jj|�|j	|jjd�t
�|j|jjddd�|j
r�dnd�|j|jjdd�|j
r�dnd�|j|jjd�|jjt|���|jtj|jjddd�dS(NitweightR#t	badoptiont	somevalue(RFRGRRRR<R{R>RtassertIsInstancetdictRRHRR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_pane�s.cCsi|jtj|jjd�|jtj|jjd�|jtj|jjd�tj|jdd�}|jj|dd�|jtj|jjd�tj|jdd�}|jj|�|jtj|jjd�|jj	dt
d	d
�|jj�|jjd�}|jjdd�|j||jjd��|j
|jjd�t�dS(NRiR8R�Ritbtexpandtfilltbothi�(RFRGRRtsashposRHR<R{RR?RUR@tassertNotEqualR tint(RRRtcurr_pos((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_sashpos�s
(RR]R^RR.R`R7(R4R5RcR;RRRRRR"R+(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR
s							#	tRadiobuttonTestcBs)eZdZd�Zd�Zd�ZRS(RR�R�R]R�R!RSR.R`R8R�RgtvalueR�R7cKstj|j|�S(N(R<tRadiobuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR-igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_value�scs�g��fd�}tj|j�}tj|jd|d|dd�}tj|jd|d|dd�}|jr�d�}nt}|j�}|j|d�|j||d�|j	��|j|j	�||j
j|d���|j��d	|d<|j�}|jt
|�d	�|jt��d�|j||d�|j	��|j|j	�||j
j|d���|jt
|d�t
|d��dS(
Ncs�jd�dS(Niscb test called(R�((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s
R�R�R-iicSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��Rscb test calledR(RGtIntVarR>R<R.RR)R�RR�R�R�R�R�R�R�(RR�tmyvarR�tcbtn2tconvR�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s0	 

 (RR�R�R]R�R!RSR.R`R8R�RgR-R�R7(R4R5RcRR/R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR,�s		tMenubuttonTestcBs)eZdZd�Zd�Zd�ZRS(RR�R]t	directionR�tmenuR!RSR.R`R8R�RgR7cKstj|j|�S(N(R<t
MenubuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR5tabovetbelowR�R�tflush(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_direction�scCsH|j�}tj|dd�}|j|d|dt�|j�dS(NRyR6R3(RRGtMenuR,R�R|(RRR6((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_menu�s(RR�R]R5R�R6R!RSR.R`R8R�RgR7(R4R5RcRR;R=(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR4�s		t	ScaleTestcBskeZdZeZdZd�Zd
�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(RR�R]tfromtlengthRR.R`ttoR-R�RcCs@tt|�j�|j�|_|jj�|jj�dS(N(R:R>R;RtscaleR?R�(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�s
cKstj|j|�S(N(R<tScaleR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRscCs/|j�}|j|dddddt�dS(NR?idg������-@g333333.@R3(RtcheckFloatParamR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_fromscCs,|j�}|j|ddddd�dS(NR@i�gffffff`@g33333�`@t5i(RtcheckPixelsParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_lengthsc	Cs2|j�}|j|ddddddt�dS(NRAi,g������-@g333333.@i����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tosc	Cs2|j�}|j|ddddddt�dS(NR-i,g������-@g333333.@i����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR/scs�dddg�|jjd�fd��}d|jd<d|jd<d|jd<|j��dddg�|jjdd	dd
�|jjdddd�|jjdd�|j��dS(
Nis<<RangeChanged>>cs
�j�S(N(tpop(R�(tfailure(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�Ri
R?tfrom_iRAiiii����(RBR�R�R(Rtfuncid((RKs9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_custom_events



cCs|jrd�}nt}|jj�}|j|jj|d�|jd�|j||jjdd��||jd��|j|jj�|jd�d|jd<|j|jj�|jd�|jtj|jjdd�|jtj|jjdd�dS(NcSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�(RiRAR?R-iR(	RtfloatRBRDRR�RFRGR(RR3tscale_width((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_get&s	&2 
 cCs�|jrd�}nt}||jd�}|d}|jj|�|j||jj��|�||jd�}|jj|d�|j||jj��|�tj|j�}||jd<|j|d�|j||jj��|j��|j||jj��|d�~|d|jd<|j||jj��|d�|j||jj��||jd��|j||jjd	d	��|�|j||jj|jj	�d	��|�|j
tj|jjd�dS(
NcSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�:RRAi
R?iR�iR-i(
RRORBRRR�RGt	DoubleVarR>RDRFRRH(RR3tmaxtnew_maxtmintvar((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_set8s,	

%##,%.(RR�R]R?R@RR.R`RAR-R�(R4R5RcRRZR/R;RRERHRIR/RNRQRW(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR>�s								tProgressbarTestcBsPeZdZeZdZd�Zd
�Zd�Zd�Z	d�Z
d�ZRS(RR]RR@tmodetmaximumtphaseR.R`R-R�RcKstj|j|�S(N(R<tProgressbarR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRfscCs)|j�}|j|dddd�dS(NR@gfffffY@g�����YL@t2i(RRG(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRHisc	Cs2|j�}|j|ddddddt�dS(NRZgfffff�b@g�����lS@ii����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_maximummscCs&|j�}|j|ddd�dS(NRYtdeterminatet
indeterminate(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_modeqscCsdS(N((R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_phaseusc	Cs2|j�}|j|ddddddt�dS(NR-gfffff�b@g�����lS@ii����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR/ys(RR]RR@RYRZR[R.R`R-R�(R4R5RcRRZR/RRHR^RaRbR/(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRX\s					R�s"ttk.Scrollbar is special on MacOSXt
ScrollbarTestcBseZdZdZd�ZRS(	RR�R]RR.R`RcKstj|j|�S(N(R<t	ScrollbarR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(RR�R]RR.R`(R4R5RcR/R(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRcstNotebookTestcBsqeZdZd�Zd�Zd	�Zd
�Zd�Zd�Zd
�Z	d�Z
d�Zd�Zd�Z
RS(RR]R^R!R.R`R7cCs�tt|�j�|jdd�|_tj|j�|_tj|j�|_	|jj
|jdd�|jj
|j	dd�dS(NR!iR8R�R#(R:ReR;RtnbR<R{R>tchild1RR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�scKstj|j|�S(N(R<tNotebookR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs�|jjd�|jj|j�|jtj|jj|j�|j	|jj
d�d�|jj|j�|j	|jj
d�d�|jj|j�|j
|jjd��|jj|jdd�|jj�|jj�tjdkrd}nd	}|j	|jj|�|jjd��xhtd
dd
�D]G}y*|jjd|dd�dkrtPnWqEtjk
r�qEXqEW|jd
�dS(NiR�iR�R8R�R�s@20,5s@5,5iids@%d, 5sTab with text 'a' not found(RfRthideRRFRGRttabRgRtindexRtselectR�R?R@R�R�trangeRHtfail(Rttb_idxti((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tab_identifiers�s,

	("cCs�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjtj|j	�dd�|jj
�}|jj|j�|jj|j�|j|jj
�|�tj|j	�}|jj|dd�|jj
�}|jj
d�}|jj
|j�}|jj|j�|jj|j�|j|jj
�|�|j|jj
|j�|�|jt|j�|jj
�|�|j|jj
d�|d�dS(	Ni����ROtunknowntoptionR8RR�i(RFRGRRfRiRHRR<R{R>ttabsRgRRkRR�(RRtRtcurrtchild2_index((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_add_and_hidden�s*'&cCs+|jtj|jjd�|jtj|jjd�|jtj|jjd�|jj�}|jj|j�}|jj|j�|j	t
|j�|jj��|jt|�dt|jj���|jj
|j�|j|jj|j�d�|j||jj|j��dS(Ni����ROi(RFRGRRfRRHRtRkRgtassertNotInR�RR�RR((RRttchild1_index((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s")cCs�|jtj|jjd�|jtj|jjd�|j|jjd�t�|j|jj|j	�d�|j|jj|j
�d�|j|jjd�d�dS(Ni����R�iii(RFRGRRfRkRHR R)RRgR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_index�scCs�|jj�}|jjd|d�|j|jj�|d|df�|jj|j|j�|j|jj�|�|jjd|j�|j|jj�|d|df�|jjdd�|j|jj�|�|jtj|jjd|d�|jtj|jjd|d�t	j
|j�}|jjd|�|j|jj�|dt|�|df�|jj
|�|j|jj�|�|jj|j|�|j|jj�t|�f|�|jj
|�|jtj|jjd|�|jtj|jjd|�|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�dS(NiiR�ii����(RfRtR�RRgRRFRGRR<R{R>R�RRH(RRtR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s0''##0&cs�|jj�|jj�g�g�|jjd�fd��|jjd�fd��|j|jj�t|j��|jj|j�|j	��|j|jj�t|j��|jj
�|j	��dS(Ns<Unmap>cs
�jt�S(N(R�RU(R�(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�Rs<<NotebookTabChanged>>cs
�jt�S(N(R�RU(R�(ttab_changed(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�R(RfR?R@RgR�RRlR�RR�R�(R((R�R{s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selects

"
"
cCs|jtj|jjd�|jtj|jjd�|jtj|jjd�|j|jj|j�t�|j	|jj|jdd�d�|j	|jj|jd�d�|jj|jdd�|j	|jj|jdd�d�|j	|jj|jd�d�dS(Ni����tnotabR8R�tabc(
RFRGRRfRjRHR RgR!R(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tab(s%"%cCsb|jt|jj��d�|jj|j�|jj|j�|j|jj�d�dS(Ni((RR�RfRtRRgR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_tabs6scCs�|jj�|jj�|jjd�t|jdd�|jj�|jjd�|j|jj�t|j	��|jj�|jjd�|j|jj�t|j
��|jj�|jjd�|j|jj�t|j	��|jj|j
dddd�|jj�|jj�t|jdd�t
jdkrh|jjd	�n|jjd
�|j|jj�t|j
��dS(Niis
<Control-Tab>s<Shift-Control-Tab>R8R�RgR�s
<Option-a>s<Alt-a>(RfR?R@RlR	tfocus_forceR�RR�RRgRjtenable_traversalR�R�(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_traversal?s*


"
"
"

(RR]R^R!R.R`R7(R4R5RcR;RRqRwRRzRR|RR�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRe�s						
	!				tTreeviewTestcBs�eZd#Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd �Zd!�Zd"�ZRS($RtcolumnsR]tdisplaycolumnsR^R!t
selectmodeR�R.R`R�tyscrollcommandcCs,tt|�j�|jdd�|_dS(NR!i(R:R�R;Rttv(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;cscKstj|j|�S(N(R<tTreeviewR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRgscCsa|j�}|j|dddd
�|j|dd�|j|dtdkrVd
nd	�dS(NR�sa b cR"R�R#RiiR(R�R#R(R�R#R(ii((RR,R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_columnsjs
cCs�|j�}d|d<|j|dddd�|j|dd�|j|dddd�|j|dd�|j|ddd
d�|j|ddd
d�|j|ddd
d�dS(NR�R#RR�R�sb a cR"s#alliiiRRsInvalid column index disColumn index 3 out of boundsi����sColumn index -2 out of bounds(R�R#R(R#R�R(R#R�R(s#all(iii(R�R#R(iii(ii����(RR,R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_displaycolumnsqs
c	CsN|j�}|j|ddddddt�|j|ddddt�dS(	NR^idi����it3cR3g�����LY@gfffff�Y@(RRGR�R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s"cCs)|j�}|j|dddd�dS(NR�R�tbrowsetextended(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selectmode�scCs�|j�}|j|dddd�|j|dd�|j|dd�|j|dddd	�|j|dddd
�dS(NR�s
tree headingsR"ttreetheadings(R�R�(R�R�(R�R�(R�(R�(RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��scCsW|jj�|j|jjd�d�|jj�|jj�|jjdd�}|jj�}|j|�|jj|d�}|j	|�dg|jd<|jj
ddd�|jj|dd�}|jj
ddd�}|jst
|�}n|j|d|d|�|jj|d�}|j|jj|�d�dS(	NRR�ittestR�R7i2s#0(R�R?RR�R@R�R�tget_childrenR�R�tcolumnRHRR)(Rtitem_idtchildrenR�tbbox_column0t
root_widthRg((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s$




	cCs>|j|jj�d�|jjdd�}|j|jj�t�|j|jj�d|�|jjdd�}|jjdd�}|jj|||�|j|jj|�||f�|jtj	|jj||�|jj|�|j|jj|�d�|jjd�|j|jj�d�dS(NRR�i((((
RR�R�R�R ttupletset_childrenRFRGR(RR�RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_children�s"cCsi|j|jjd�t�|jrJ|j|jjddd�t�n|jjddd�|j|jjdd�|jr�dnd�|j|jjddd�|jr�dnd�|jt	j
|jjddd�|jt	j
|jjd�idd	6id
d6id
d6id
d6id
d
6g}x-|D]%}|jt	j
|jjd|�q<WdS(Ns#0R7i
t10tidtXR�s
some valuetunknown_optiontwrongtstretchR�tminwidth(R R�R�R!RRHR)RRFRGR(Rtinvalid_kwsRM((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_column�s	%"$
cCs?|jtj|jjd�|jjdd�}|jj|d�}|j|jj�|f�|j|jj|�|f�|jj|�|j|jj��|jtj|jj	|dd�|jjdd�}|jjdd�}|j|jj�||f�|jj||�|j|jj��dS(Ns#0RR�(
RFRGRR�R�R�RR�R�treattach(RR�titem2titem1((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_delete�scCs0|jjdd�}|jj|d�}|jj�}|jj�|j||jj��|j|jj�|f�|j|jj|�|f�|jj|�|j|jj��|jj|dd�|j|jj�|f�|j|jj|�|f�|jj|dd�|j|jj�||f�|j|jj|�d�|jt	j
|jjddd�|jt	j
|jjd�|jt	j
|jj|dd�|jt	j
|jj|dd�|jj||�|j|jj�d�|j|jj|�d�dS(	NRR�tnonexistenttotherparentR�((((R�R�R�tdetachRR�R�tmoveRFRGR(RR�R�tprev((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_detach_reattach�s4
cCst|j|jjd�t�|j|jjd�t�|j|jji�t�|jtj|jjd�dS(Nt	somethingR(	RR�texistsR�RURFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_exists'scCs�|j|jj�d�|jjdd�}|jj|�|j|jj�|�|jj|�|j|jj�d�|jtj|jjd�dS(NRR�RO(RR�R�R�R�RFRGR(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_focus2scCs�|j|jjd�t�|jjddd�|j|jjdd�d�|j|jjddd�d�|jtj|jjddd�|jtj|jjddd�dS(Ns#0R8ROR�R�i(	R R�theadingR!RRHRFRGR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_headingAs"cs�fd�}g��jj��jj��jjdd�fd���jjddd��jj�|dd��s��jd�ng��jjj}�jjddt	�jjddd����j|�jjj�|dd��s�jd�ndS(	Ncs$t�j||��jj�dS(N(R	R�R�(R�R�(R(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytsimulate_heading_clickRss#0R�cs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�ZRR7idis>The command associated to the treeview heading wasn't invoked.(R�R?R@R�R�R�RnRt_tclCommandsR�RHR(RR�tcommands((RR�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_heading_callbackQs"



.
cCs�|jtj|jjd�|j|jjd�d�|jjdd�}|jjdd�}|jj|d�}|jj|d�}|j|jj|�d�|j|jj|�d�|j|jj|�d�|j|jj|�d�|jj|dd�|j|jj|�d�|j|jj|�d�|jj|�|j|jj|�d�|jj|�|j|jj|�d�|jj	|�|jtj|jj|�dS(NtwhatRiR�i(
RFRGRR�RkRR�R�R�R�(RR�R�tc1tc2((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRzss&cCs�|jtj|jjdd�|jtj|jjdddd�|jtj|jjdddd�|j|jj|jjdddt���|j|jj|jjdddt���|jtj|jjdd�|jjddd�}|j	|d�|jtj|jjddd�|jtj|jjddt
d��d}|jjddd	|f�}|j	|jj|d	�|jr�|fn|�|j	|jj|d	d�|jr�|fn|�|jj|d	|jj|jj|d	d���|j	|jj|d	d�|jr@|fn|�|j|jj|�t�|jj|d	d�|j|jj|d	d��|jjddd
dd|g�}|j	|jj|d
d�|jr�d
d|fnd|�|jj|d
g�|j|jj|d
d��|jj|d
d�|j	|jj|d
d�|jrodnd�|jjddd	dd||ff�}|j	|jj|d	d�|jr�dd||ffn
d||f�|j	|jj|jjdddd�dd�d�|j	|jj|jjddd|�dd�|�|jjddd�}|j	|d�|jjddd�}|j	|d�|jtj|jjddt�|jtj|jjddd�dS(NR�R�Rtopentpleasetmiddles
first-itemuábaR�ttagsiiRRs1 2 %ss1 2sa b cs%s %ss{a b c} {%s %s}R8s
Label hereiR#gs0.0(ii(RR(RFRGRR�R�R�R�RUR�RRtitemRRHR>t	splitlistR R!(RtitemidR-R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_insert_item�sh..
4$!!"cCs�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jjdd�}|jjdd�}|jj|d�}|jj|d�}|jj|d�}|j	|jj
�d
�|jj||f�|j	|jj
�||f�|jj|�|j	|jj
�|f�|jj||f�|j	|jj
�|||f�|jj|�|j	|jj
�||||f�|jj||f�|j	|jj
�|||f�|jj|�|j	|jj
�||f�|jj||f�|j	|jj
�||f�|jj|�|j	|jj
�|f�|jjdddd�|jjd�|j	|jj
�d�|jjdddd�|jjd�|j	|jj
�d�trl|jjdddtd��|jjtd��|j	|jj
�td�f�n|jjdddd�|jjd�|j	|jj
�tr�td	�ndf�dS(
NR�RR�R�swith spacess{braces
unicode\u20acsbytes€sbytes\u20ac((swith spaces(s{brace(
RFRGRR�t
selection_sett
selection_addtselection_removetselection_toggleR�Rt	selectionRR(RR�R�R�R�tc3((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selection�sR"%"%cCsPddg|jd<|jjdddddg�}|j|jj|�idd6dd6�|jj|dd�|j|jj|dd�|jr�dnd	�dg|jd<|j|jj|�idd6�|jj|dd�|j|jj|d
d�d�|j|jj|dd�|jr:dnd�|jj|dd�|j|jj|d�|jr~dnd
�|j|jj|dd�|jr�dnd�|j|jj|�|jr�idd6n
id
d6�|jtj	|jj|d�|jtj	|jj|dd�|jtj	|jjd�dS(NtAtBR�RR�R�R�R#sa aR�sb ai{t123s123 atnotme(R�R�(R#R�(i{R�(
R�R�RRR�RHRRFRGR(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRWs,!*#"$"c	s�g�|jjddddg�}|jjddddg�}|jjdd�fd��|jjdd�fd��|jj�|jj�|jj�t�}t�}xqtd	d
d�D]]}t|�dkr�Pn|jj	|�}|r�||kr�|j
|�|j
|�q�q�W|jt|�d�x!|D]}t|jd	|�qJW|jt��d
�xAt
�ddd��ddd��D]}|j|d�q�WdS(NRR�R�tcalls<ButtonPress-1>cs
�jd�S(Ni(R�(R�(tevents(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�;Rs<ButtonRelease-1>cs
�jd�S(Ni(R�(R�(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�=Riidi
iii(ii(R�R�ttag_bindR?R@R�RRmR�tidentify_rowRRR	tzip(	RR�R�tpos_ytfoundRpR�R�R�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_tag_bind6s2


		

0cCs�|jt|jj�|jtj|jjddd�|jjddd�|jt|jjdd��d�|jt|jjddd��d�|j	|jjd�t
�dS(NR�tskytblueR�(RFt	TypeErrorR�t
tag_configureRGRRR�RHR R!(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tag_configureXs
!cCs�|jjddddddg�}|jjddddddg�}|jt|jj�|jt|jjdd	�|j|jjd|��|j|jjd|��|j|jjd|��|j|jjd|��|j|jjd
|��|j|jjd
|��|j|jjd�|f�|j|jjd�|f�|j|jjd
�d�dS(NRR�R8sItem 1R�ttag1sItem 2ttag2snon-existingttag3((	R�R�RFR�ttag_hasRR�R�R(RR�R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tag_hasds$$(RR�R]R�R^R!R�R�R.R`R�R�(R4R5RcR;RR�R�R�R�R�R�R�R�R�R�R�R�R�R�RzR�R�RWR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�[s4													*				"		M	6	!	"	t
SeparatorTestcBseZdZdZd�ZRS(RR]RR.R`RcKstj|j|�S(N(R<t	SeparatorR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR|s(RR]RR.R`(R4R5RcR/R(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�tstSizegripTestcBseZdZd�ZRS(RR]R.R`cKstj|j|�S(N(R<tSizegripR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(RR]R.R`(R4R5RcR(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��st__main__(5tunittesttTkinterRGRR<ttest.test_supportRRRRR�ttest_functionsRtsupportRRRR	twidget_testsR
RRR
RRRRRtTestCaseR6RYR[RdR~R�R�R�R�R�R
R,R4R>RXtskipIfR�RcReR�R�R�t	tests_guiR4(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt<module>sr"":
';0�|�3j"
���	PK'/�ZM�3��test_ttk/test_style.pyonu�[����
zfc@s�ddlZddlZddlZddlmZmZddlmZed�deej	fd��YZ
e
fZedkr�ee�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguit	StyleTestcBs>eZd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(tsuperRtsetUptttktStyletroottstyle(tself((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyRscCsU|j}|jddd�|j|jdd�d�|j|jd�t�dS(NtTButtont
backgroundtyellow(R
t	configuretassertEqualtassertIsInstancetdict(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_configures
	cCsm|j}|jdddg�|j|jdd�|jrFdgndg�|j|jd�t�dS(	NRR
tactivetbluesactive background(RR
R(RR
R(sactive backgroundR(R
tmapRtwantobjectsRR(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_maps	
cCs�|j}|jddd�|jddd	g�|j|jdd�d�|j|jddddg�d�|j|jdddd�d�dS(
NRR
RRRtoptionnotdefinedtdefaulttiknewit(RR
R(R
RRRtlookup(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_lookup!s	cCs�|j}|jtj|jd�|jd�}|jdd�|j|jd�didd6fg�|jd|�|j|jd�|�|j|jd�t�|jtj|jddid	d
6fg�dS(Nt
NotALayouttTreeviewttnulltnswetstickyRtnamet
inexistenttoption(R
tassertRaisesttkintertTclErrortlayoutRRtlist(RR
ttv_style((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_layout-s	cCs�|jtj|jjd�|jj�}d}xA|jj�D],}||krA|}|jj|�PqAqAWdS|j||k�|j||jj�k�|jj|�dS(Ntnonexistingname(R'R(R)R
t	theme_usetNonettheme_namestassertFalse(Rt
curr_themet	new_themettheme((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_theme_useDs(t__name__t
__module__RRRRR-R6(((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyR	s						t__main__(
tunittesttTkinterR(Rttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR7(((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyt<module>s
P	PK'/�Z�p���test_ttk/__init__.pycnu�[����
zfc@sdS(N((((s5/usr/lib64/python2.7/lib-tk/test/test_ttk/__init__.pyt<module>tPK'/�ZM�3��test_ttk/test_style.pycnu�[����
zfc@s�ddlZddlZddlZddlmZmZddlmZed�deej	fd��YZ
e
fZedkr�ee�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguit	StyleTestcBs>eZd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(tsuperRtsetUptttktStyletroottstyle(tself((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyRscCsU|j}|jddd�|j|jdd�d�|j|jd�t�dS(NtTButtont
backgroundtyellow(R
t	configuretassertEqualtassertIsInstancetdict(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_configures
	cCsm|j}|jdddg�|j|jdd�|jrFdgndg�|j|jd�t�dS(	NRR
tactivetbluesactive background(RR
R(RR
R(sactive backgroundR(R
tmapRtwantobjectsRR(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_maps	
cCs�|j}|jddd�|jddd	g�|j|jdd�d�|j|jddddg�d�|j|jdddd�d�dS(
NRR
RRRtoptionnotdefinedtdefaulttiknewit(RR
R(R
RRRtlookup(RR
((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_lookup!s	cCs�|j}|jtj|jd�|jd�}|jdd�|j|jd�didd6fg�|jd|�|j|jd�|�|j|jd�t�|jtj|jddid	d
6fg�dS(Nt
NotALayouttTreeviewttnulltnswetstickyRtnamet
inexistenttoption(R
tassertRaisesttkintertTclErrortlayoutRRtlist(RR
ttv_style((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_layout-s	cCs�|jtj|jjd�|jj�}d}xA|jj�D],}||krA|}|jj|�PqAqAWdS|j||k�|j||jj�k�|jj|�dS(Ntnonexistingname(R'R(R)R
t	theme_usetNonettheme_namestassertFalse(Rt
curr_themet	new_themettheme((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyttest_theme_useDs(t__name__t
__module__RRRRR-R6(((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyR	s						t__main__(
tunittesttTkinterR(Rttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR7(((s7/usr/lib64/python2.7/lib-tk/test/test_ttk/test_style.pyt<module>s
P	PK'/�Z8����test_ttk/test_widgets.pycnu�[����
zfc@sUddlZddlZddlmZddlZddlmZmZmZm	Z	ddl
Z
ddlmZddl
mZmZmZmZddlmZmZmZmZmZmZmZmZed�defd	��YZd
eejfd��YZdeefd
��YZee�deejfd��Y�Zee�deejfd��Y�Z defd��YZ!ee�de!ejfd��Y�Z"ee�de!ejfd��Y�Z#ee�de!ejfd��Y�Z$eee�deejfd��Y�Z%eee�de%ejfd��Y�Z&eee�deejfd��Y�Z'ee�d e!ejfd!��Y�Z(d"e!ejfd#��YZ)ee�d$eejfd%��Y�Z*ee�d&eejfd'��Y�Z+ej,e
j-d(kd)�ee�d*eejfd+��Y��Z.eee�d,eejfd-��Y�Z/ee�d.eejfd/��Y�Z0ee�d0eejfd1��Y�Z1ee�d2eejfd3��Y�Z2e#e$e&e%ee e"e)e/e'e+e(e*e.e1e2e0efZ3e4d4krQee3�ndS(5i����N(tTclError(trequirestrun_unittestthave_unicodetu(t
MockTclObj(tAbstractTkTestttcl_versiontget_tk_patchleveltsimulate_mouse_click(tadd_standard_optionstnoconvtnoconv_methtAbstractWidgetTesttStandardOptionsTeststIntegerSizeTeststPixelSizeTeststsetUpModuletguitStandardTtkOptionsTestscBs#eZd�Zd�Zd�ZRS(cCs�|j�}|j|dd�d}t�d
kr>d	}n|j|dd
d|�|jdd
�}|j|dd
�dS(Ntclassts"attempt to change read-only optioniiitbetais"Attempt to change read-only optiontFooterrmsgtclass_(iiiRi(tcreatetassertEqualRtcheckInvalidParam(tselftwidgetRtwidget2((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_classs	c	Cs�|j�}|j|dddd�|j|dddd�|j|dddd�|j|dddd�|j|dddd�|j|dd�|j|dddd�dS(Ntpaddingitexpectedt0it5it6it7it8t5pt6pt7pt8pR(R#(R$(ii(R$R%(iii(R$R%R&(iiii(R$R%R&R'(R(R)R*R+((Rt
checkParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_paddingscCs�|j�}|j|dd�d}t|d�rQdt|d�j�}n|j|ddd|�|jdd�}|j|d	d�dS(
NtstyleRsLayout Foo not foundtdefault_orientsLayout %s.Foo not foundRRRR(RRthasattrtgetattrttitleR(RRRR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_style+s(t__name__t
__module__R R-R3(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRs	
	t
WidgetTestcBs)eZdZd�Zd�Zd�ZRS(s,Tests methods available in every ttk widget.cCsRtt|�j�tj|jdddd�|_|jj�|jj�dS(NtwidthittexttText(	tsuperR6tsetUptttktButtontrootRtpacktwait_visibility(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;=s!
cCs�|jj�|j|jj|jj�d|jj�d�d�|j|jjdd�d�|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�dS(Nitlabeli����Ri(
Rtupdate_idletasksRtidentifytwinfo_widthtwinfo_heighttassertRaisesttkinterRtNone(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_identifyDs
cCs�|j|jj�d
�|j|jjdg�t�|j|jjdg�d�|j|jjdg�d�|j|jjddg�d
�|j|jjddg�d�|j|jjddg�d�d�}|j|jjdg|didd6�didd6f�|jj�}|jtj|jjd	g�|jtj|jjdd	g�|j||jj��|jjddg�|j|jj�d�dS(Ns	!disabledtdisabledtactives!activec[s
||fS(N((targ1tkw((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_cbasthittheretmsgtbadstate((s	!disabled((s!activeRJ(((RK(RRtstatetinstatetTrueRFRGR(RRNt	currstate((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_widget_stateQs(""	

(R4R5t__doc__R;RIRW(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR6:s		
tAbstractToplevelTestcBseZeZRS((R4R5Rt_conv_pixels(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRYust	FrameTestc	BseZd
Zd	�ZRS(tborderwidthRtcursortheightR!treliefR.t	takefocusR7cKstj|j|�S(N(R<tFrameR>(Rtkwargs((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(	R\RR]R^R!R_R.R`R7(R4R5tOPTIONSR(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR[ystLabelFrameTestc
Bs)eZdZd
�Zd�Zd�ZRS(R\RR]R^tlabelanchortlabelwidgetR!R_R.R`R8t	underlineR7cKstj|j|�S(N(R<t
LabelFrameR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs]|j�}|j|ddddddddd	d
ddd
dd�|j|dd�dS(NRetetentestntnetnwtstsetswtwtwntwsRs!Bad label anchor specification {}tcenter(RtcheckEnumParamR(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_labelanchor�s
'cCsQ|j�}tj|jdddd�}|j|d|dd�|j�dS(NR8tMupptnametfooRfR"s.foo(RR<tLabelR>R,tdestroy(RRRA((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_labelwidget�s(
R\RR]R^ReRfR!R_R.R`R8RgR7(R4R5RcRRwR}(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRd�s		tAbstractLabelTestcBs,eZd�Zd�Zd�Zd�ZRS(cCs�tjd|jdd�}tjd|jdd�}|j|||dd�|j||ddd�|j|||fdd
�|j|||d|fdd�|j||ddd�|j||dd	d
�dS(NtmasterRytimage1timage2R"RKsimage1 active image2tspamRsimage "spam" doesn't exist(R�(R�(R�(R�RKR�(R�RKR�(RGt
PhotoImageR>R,R(RRRytimageR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcheckImageParam�scCs8|j�}|j|ddddddddd	�
dS(
NtcompoundtnoneR8R�Ruttoptbottomtlefttright(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_compound�scCs)|j�}|j|dddd�dS(NRSRKRJtnormal(RtcheckParams(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_state�scCs)|j�}|j|dddd�dS(NR7i�in���i(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_width�s(R4R5R�R�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR~�s	
		t	LabelTestcBs&eZdZeZd�Zd�ZRS(tanchort
backgroundR\RR�R]tfontt
foregroundR�tjustifyR!R_RSR.R`R8ttextvariableRgR7t
wraplengthcKstj|j|�S(N(R<R{R>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs#|j�}|j|dd�dS(NR�s3-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*(RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_font�s(R�R�R\RR�R]R�R�R�R�R!R_RSR.R`R8R�RgR7R�(R4R5RcRRZRR�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s	t
ButtonTestcBs)eZdZd�Zd�Zd�ZRS(RtcommandR�R]tdefaultR�R!RSR.R`R8R�RgR7cKstj|j|�S(N(R<R=R>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR�R�RKRJ(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_default�scsBg�tj|jd�fd��}|j�|j��dS(NR�cs
�jd�S(Ni(tappend((tsuccess(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt<lambda>�R(R<R=R>tinvoket
assertTrue(Rtbtn((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_invoke�s!
(RR�R�R]R�R�R!RSR.R`R8R�RgR7(R4R5RcRR�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s		tCheckbuttonTestcBs2eZdZd�Zd�Zd�Zd�ZRS(RR�R�R]R�toffvaluetonvalueR!RSR.R`R8R�RgtvariableR7cKstj|j|�S(N(R<tCheckbuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_offvalue�scCs,|j�}|j|ddddd�dS(NR�igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_onvalue�scsg��fd�}tj|jd|�}|j|j�d
�|jtj|jj	|d�|j
�}|j|d�|j|d|jj	|d��|j��d|d<|j
�}|jt
|��|jt��d�|j|d	|jj	|d��dS(Ncs�jd�dS(Niscb test called(R�((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcb_tests
R�t	alternateR�scb test calledR�RiR�(R�(R<R�R>RRSRFRGRttktglobalgetvarR�R�tassertFalsetstrtassertLessEqualtlen(RR�tcbtntres((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s"



(RR�R�R]R�R�R�R!RSR.R`R8R�RgR�R7(R4R5RcRR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s			t	EntryTestcBszeZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(R�RR]texportselectionR�R�tinvalidcommandR�tshowRSR.R`R�tvalidatetvalidatecommandR7txscrollcommandcCs&tt|�j�|j�|_dS(N(R:R�R;Rtentry(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;#scKstj|j|�S(N(R<tEntryR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR'scCs |j�}|j|d�dS(NR�(RtcheckCommandParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_invalidcommand*scCsI|j�}|j|dd�|j|dd�|j|dd�dS(NR�t*Rt (RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_show.scCs)|j�}|j|dddd�dS(NRSRJR�treadonly(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�4sc	Cs2|j�}|j|ddddddd�dS(NR�talltkeytfocustfocusintfocusoutR�(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_validate9scCs |j�}|j|d�dS(NR�(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validatecommand>scCsU|j|jjd��|jtj|jjd�|jtj|jjd�dS(Nitnoindex(tassertIsBoundingBoxR�tbboxRFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_bboxCscCs�|jj�|jj�|jj�tjdkrX|j|jjdd�d�n|j|jjdd�d�|j|jjdd�d�|j	t
j|jjdd�|j	t
j|jjdd�|j	t
j|jjdd�dS(NtdarwinittextareasCombobox.buttoni����R(R�sCombobox.button(
R�R?R@RBtsystplatformtassertInRCRRFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRIIs



cs#g��fd�}d|jd<d�|jd<||jd<|jj�|j��d|jd<|jj�|jt��d�||jd<d	�|jd<|jj�|jt��d�d|jd<|jj�|jt��d�t|jd<|jtj|jj�dS(
Ncs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�]RR�R�cSstS(N(tFalse(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�`RR�R�RicSstS(N(RU(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�kR(	R�R�R�RR�RURFRGR(Rttest_invalid((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validation_options[s&










cs�g��fd�}d|jd<|jj|�df|jd<|jjdd�|jjdd�|j�ttg�|j|jj�d�dS(	NcsDd|j�kodkns3�jt�tS�jt�tS(Ntatz(tlowerR�R�RU(t	to_insert(t
validation(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�ys
"

R�R�s%SR�tendiR�(R�tregistertinsertRR�RUtget(RR�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_validationws
cCs$d�}|jj|�df|jd<|jjdd�|j|jj�t�|j|jj�d�|jjdd�|j|jj�d�|jjdd�|j|jj�t	�|j|jj�d�|jjd
�|j|jj�t�|j|jj�d
�dS(NcSs;x4|D],}d|j�ko*dknstSqWtS(NR�R�(R�R�RU(tcontenttletter((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s
"s%PR�R�tavocadoiRta1btinvalidi((R�((
R�R�R�RR�RURStdeleteR�R�(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_revalidation�s	(R�RR]R�R�R�R�R�R�RSR.R`R�R�R�R7R�(R4R5RcR;RR�R�R�R�R�R�RIR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s"											tComboboxTestcBsMeZdZd�Zd�Zd�Zd�Zd�Zd�Zd�Z	RS(R�RR]R�R�R�R^R�R�tpostcommandR�RSR.R`R�R�R�tvaluesR7R�cCs&tt|�j�|j�|_dS(N(R:R�R;Rtcombo(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�scKstj|j|�S(N(R<tComboboxR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�sc	Cs2|j�}|j|ddddddd�dS(NR^idg�����LY@gfffff�Y@i����it1i(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_height�scCs`|jj�}|jjdd|ddd�|jjdd|ddd�|jj�dS(Ns<ButtonPress-1>txitys<ButtonRelease-1>(R�RDtevent_generateRB(RR7((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt_show_drop_down_listbox�s  cs�g�dg|jd<|jjd�fd��|jj�|jj�|jj�}|j�|jj�|jjd�|jj�|j��dS(NiR�s<<ComboboxSelected>>cs
�jt�S(N(R�RU(tevt(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��Rs<Return>(	R�tbindR?R@RER�tupdateR�R�(RR^((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_virtual_event�s




cs~g��fd�|jd<|jj�|jj�|j�|j��d|jd<|j�|jt��d�dS(Ncs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��RR�Ri(R�R?R@R�R�RR�(R((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_postcommand�s





c	s��fd�}�j�jdtd#kr1d$nd�|dd��j�jdddd%��j�jdd&��j�jdd'��j�jdtd(kr�d)nd�dddg�jd<�jjd�|dd��jjd�|dd��jjd�|dd��jjd�d*�jd<|dd��jjddddg��j�jd�jr�d+nd�dddg�jd<�j�jd�jr�d,nd�ddd g�jd<�j�jd�jr�d-nd!��jt	j
�jjt�jd���jt	j
�jjd�tj
�jddddg�}�j|d�jr�d.nd"�|j�dS(/Ncs6�j�jj�|��j�jj�|�dS(N(RR�R�tcurrent(tgetvaltcurrval(R(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytcheck_get_current�sR�iiRi����smon tue wed thurR"tmonttuetwedtthuri*g��Q�	@s
any stringR�itciitdit1t2s1 {} 2sa bsa	bsa
bs{a b} {a	b} {a
b}sa\tbs"a"s} {sa\\tb {"a"} \}\ \{s1 2 {}(ii((R�R�R�R(R�R�R�R(i*g��Q�	@Rs
any string(ii((iiRi(RRR(sa bsa	bsa
b(sa\tbs"a"s} {(RRR(RR�RR,tsetR�t	configuretwantobjectsRFRGRR�R<R�R>R|(RR�tcombo2((Rs9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_values�sL
(




!
(R�RR]R�R�R�R^R�R�R�R�RSR.R`R�R�R�R�R7R�(
R4R5RcR;RR�R�R�R�R	(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s						tPanedWindowTestcBsVeZdZd�Zd�Zd	�Zd
�Zd�Zd�Zd
�Z	d�Z
RS(RR]R^torientR.R`R7cCs&tt|�j�|j�|_dS(N(R:R
R;Rtpaned(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;&scKstj|j|�S(N(R<tPanedWindowR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR*scCs�|j�}|jt|d�d�d}t�dkrDd	}n|j|dd
d|�|jdd
�}|jt|d�d
�dS(
NRtverticals"attempt to change read-only optioniiiRis"Attempt to change read-only optiont
horizontalR(iiiRi(RRR�RR(RRRR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_orient-s	cCsztj|j�}tj|�}|jtj|jj|�|j�|j�tj|j�}tj|�}|jtj|jj|�|j�|j�tj|j�}|jj|�|jtj|jj|�tj|j�}|jj|�|j	|jj
d�|jj
d��|jtj|jj
d�|j�|j�|jtj|jj
d�dS(Niii(R<R{RRFRGRtaddR|R>Rtpane(RRAtchildt
good_childtother_child((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_add8s(



(

cCs�|jtj|jjd�|jtj|jjd�|jjtj|j	��|jjd�|jtj|jjd�dS(Ni(
RFRGRRtforgetRHRR<R{R>(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_forgetTs
cCs|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�tj|j�}tj|j�}tj|j�}|jtj|jjd|�|jjd|�|jjd|�|j	|jj
�t|�t|�f�|jjd|�|j	|jj
�t|�t|�f�|jjd|�|j	|jj
�t|�t|�t|�f�|jj
�}|jjd|�|j	||jj
��|jj||�|j	|jj
�t|�t|�t|�f�dS(NiR�(RFRGRRR�RHR<R{R>RtpanesR�(RRtchild2tchild3R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_insert]s*++"cCs
|jtj|jjd�tj|j�}|jj|�|j	|jjd�t
�|j|jjddd�|j
r�dnd�|j|jjdd�|j
r�dnd�|j|jjd�|jjt|���|jtj|jjddd�dS(NitweightR#t	badoptiont	somevalue(RFRGRRRR<R{R>RtassertIsInstancetdictRRHRR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_pane�s.cCsi|jtj|jjd�|jtj|jjd�|jtj|jjd�tj|jdd�}|jj|dd�|jtj|jjd�tj|jdd�}|jj|�|jtj|jjd�|jj	dt
d	d
�|jj�|jjd�}|jjdd�|j||jjd��|j
|jjd�t�dS(NRiR8R�Ritbtexpandtfilltbothi�(RFRGRRtsashposRHR<R{RR?RUR@tassertNotEqualR tint(RRRtcurr_pos((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_sashpos�s
(RR]R^RR.R`R7(R4R5RcR;RRRRRR"R+(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR
s							#	tRadiobuttonTestcBs)eZdZd�Zd�Zd�ZRS(RR�R�R]R�R!RSR.R`R8R�RgtvalueR�R7cKstj|j|�S(N(R<tRadiobuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR-igffffff@Rs
any string(RR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_value�scs�g��fd�}tj|j�}tj|jd|d|dd�}tj|jd|d|dd�}|jr�d�}nt}|j�}|j|d�|j||d�|j	��|j|j	�||j
j|d���|j��d	|d<|j�}|jt
|�d	�|jt��d�|j||d�|j	��|j|j	�||j
j|d���|jt
|d�t
|d��dS(
Ncs�jd�dS(Niscb test called(R�((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s
R�R�R-iicSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��Rscb test calledR(RGtIntVarR>R<R.RR)R�RR�R�R�R�R�R�R�(RR�tmyvarR�tcbtn2tconvR�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s0	 

 (RR�R�R]R�R!RSR.R`R8R�RgR-R�R7(R4R5RcRR/R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR,�s		tMenubuttonTestcBs)eZdZd�Zd�Zd�ZRS(RR�R]t	directionR�tmenuR!RSR.R`R8R�RgR7cKstj|j|�S(N(R<t
MenubuttonR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR5tabovetbelowR�R�tflush(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_direction�scCsH|j�}tj|dd�}|j|d|dt�|j�dS(NRyR6R3(RRGtMenuR,R�R|(RRR6((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_menu�s(RR�R]R5R�R6R!RSR.R`R8R�RgR7(R4R5RcRR;R=(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR4�s		t	ScaleTestcBskeZdZeZdZd�Zd
�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(RR�R]tfromtlengthRR.R`ttoR-R�RcCs@tt|�j�|j�|_|jj�|jj�dS(N(R:R>R;RtscaleR?R�(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�s
cKstj|j|�S(N(R<tScaleR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRscCs/|j�}|j|dddddt�dS(NR?idg������-@g333333.@R3(RtcheckFloatParamR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_fromscCs,|j�}|j|ddddd�dS(NR@i�gffffff`@g33333�`@t5i(RtcheckPixelsParam(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_lengthsc	Cs2|j�}|j|ddddddt�dS(NRAi,g������-@g333333.@i����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tosc	Cs2|j�}|j|ddddddt�dS(NR-i,g������-@g333333.@i����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR/scs�dddg�|jjd�fd��}d|jd<d|jd<d|jd<|j��dddg�|jjdd	dd
�|jjdddd�|jjdd�|j��dS(
Nis<<RangeChanged>>cs
�j�S(N(tpop(R�(tfailure(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�Ri
R?tfrom_iRAiiii����(RBR�R�R(Rtfuncid((RKs9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_custom_events



cCs|jrd�}nt}|jj�}|j|jj|d�|jd�|j||jjdd��||jd��|j|jj�|jd�d|jd<|j|jj�|jd�|jtj|jjdd�|jtj|jjdd�dS(NcSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�(RiRAR?R-iR(	RtfloatRBRDRR�RFRGR(RR3tscale_width((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_get&s	&2 
 cCs�|jrd�}nt}||jd�}|d}|jj|�|j||jj��|�||jd�}|jj|d�|j||jj��|�tj|j�}||jd<|j|d�|j||jj��|j��|j||jj��|d�~|d|jd<|j||jj��|d�|j||jj��||jd��|j||jjd	d	��|�|j||jj|jj	�d	��|�|j
tj|jjd�dS(
NcSs|S(N((R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�:RRAi
R?iR�iR-i(
RRORBRRR�RGt	DoubleVarR>RDRFRRH(RR3tmaxtnew_maxtmintvar((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_set8s,	

%##,%.(RR�R]R?R@RR.R`RAR-R�(R4R5RcRRZR/R;RRERHRIR/RNRQRW(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR>�s								tProgressbarTestcBsPeZdZeZdZd�Zd
�Zd�Zd�Z	d�Z
d�ZRS(RR]RR@tmodetmaximumtphaseR.R`R-R�RcKstj|j|�S(N(R<tProgressbarR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRfscCs)|j�}|j|dddd�dS(NR@gfffffY@g�����YL@t2i(RRG(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRHisc	Cs2|j�}|j|ddddddt�dS(NRZgfffff�b@g�����lS@ii����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_maximummscCs&|j�}|j|ddd�dS(NRYtdeterminatet
indeterminate(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_modeqscCsdS(N((R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_phaseusc	Cs2|j�}|j|ddddddt�dS(NR-gfffff�b@g�����lS@ii����R3(RRDR�(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR/ys(RR]RR@RYRZR[R.R`R-R�(R4R5RcRRZR/RRHR^RaRbR/(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRX\s					R�s"ttk.Scrollbar is special on MacOSXt
ScrollbarTestcBseZdZdZd�ZRS(	RR�R]RR.R`RcKstj|j|�S(N(R<t	ScrollbarR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(RR�R]RR.R`(R4R5RcR/R(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRcstNotebookTestcBsqeZdZd�Zd�Zd	�Zd
�Zd�Zd�Zd
�Z	d�Z
d�Zd�Zd�Z
RS(RR]R^R!R.R`R7cCs�tt|�j�|jdd�|_tj|j�|_tj|j�|_	|jj
|jdd�|jj
|j	dd�dS(NR!iR8R�R#(R:ReR;RtnbR<R{R>tchild1RR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;�scKstj|j|�S(N(R<tNotebookR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�scCs�|jjd�|jj|j�|jtj|jj|j�|j	|jj
d�d�|jj|j�|j	|jj
d�d�|jj|j�|j
|jjd��|jj|jdd�|jj�|jj�tjdkrd}nd	}|j	|jj|�|jjd��xhtd
dd
�D]G}y*|jjd|dd�dkrtPnWqEtjk
r�qEXqEW|jd
�dS(NiR�iR�R8R�R�s@20,5s@5,5iids@%d, 5sTab with text 'a' not found(RfRthideRRFRGRttabRgRtindexRtselectR�R?R@R�R�trangeRHtfail(Rttb_idxti((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tab_identifiers�s,

	("cCs�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjtj|j	�dd�|jj
�}|jj|j�|jj|j�|j|jj
�|�tj|j	�}|jj|dd�|jj
�}|jj
d�}|jj
|j�}|jj|j�|jj|j�|j|jj
�|�|j|jj
|j�|�|jt|j�|jj
�|�|j|jj
d�|d�dS(	Ni����ROtunknowntoptionR8RR�i(RFRGRRfRiRHRR<R{R>ttabsRgRRkRR�(RRtRtcurrtchild2_index((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_add_and_hidden�s*'&cCs+|jtj|jjd�|jtj|jjd�|jtj|jjd�|jj�}|jj|j�}|jj|j�|j	t
|j�|jj��|jt|�dt|jj���|jj
|j�|j|jj|j�d�|j||jj|j��dS(Ni����ROi(RFRGRRfRRHRtRkRgtassertNotInR�RR�RR((RRttchild1_index((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s")cCs�|jtj|jjd�|jtj|jjd�|j|jjd�t�|j|jj|j	�d�|j|jj|j
�d�|j|jjd�d�dS(Ni����R�iii(RFRGRRfRkRHR R)RRgR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_index�scCs�|jj�}|jjd|d�|j|jj�|d|df�|jj|j|j�|j|jj�|�|jjd|j�|j|jj�|d|df�|jjdd�|j|jj�|�|jtj|jjd|d�|jtj|jjd|d�t	j
|j�}|jjd|�|j|jj�|dt|�|df�|jj
|�|j|jj�|�|jj|j|�|j|jj�t|�f|�|jj
|�|jtj|jjd|�|jtj|jjd|�|jtj|jjdd�|jtj|jjdd�|jtj|jjdd�dS(NiiR�ii����(RfRtR�RRgRRFRGRR<R{R>R�RRH(RRtR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s0''##0&cs�|jj�|jj�g�g�|jjd�fd��|jjd�fd��|j|jj�t|j��|jj|j�|j	��|j|jj�t|j��|jj
�|j	��dS(Ns<Unmap>cs
�jt�S(N(R�RU(R�(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�Rs<<NotebookTabChanged>>cs
�jt�S(N(R�RU(R�(ttab_changed(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�R(RfR?R@RgR�RRlR�RR�R�(R((R�R{s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selects

"
"
cCs|jtj|jjd�|jtj|jjd�|jtj|jjd�|j|jj|j�t�|j	|jj|jdd�d�|j	|jj|jd�d�|jj|jdd�|j	|jj|jdd�d�|j	|jj|jd�d�dS(Ni����tnotabR8R�tabc(
RFRGRRfRjRHR RgR!R(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tab(s%"%cCsb|jt|jj��d�|jj|j�|jj|j�|j|jj�d�dS(Ni((RR�RfRtRRgR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt	test_tabs6scCs�|jj�|jj�|jjd�t|jdd�|jj�|jjd�|j|jj�t|j	��|jj�|jjd�|j|jj�t|j
��|jj�|jjd�|j|jj�t|j	��|jj|j
dddd�|jj�|jj�t|jdd�t
jdkrh|jjd	�n|jjd
�|j|jj�t|j
��dS(Niis
<Control-Tab>s<Shift-Control-Tab>R8R�RgR�s
<Option-a>s<Alt-a>(RfR?R@RlR	tfocus_forceR�RR�RRgRjtenable_traversalR�R�(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_traversal?s*


"
"
"

(RR]R^R!R.R`R7(R4R5RcR;RRqRwRRzRR|RR�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRe�s						
	!				tTreeviewTestcBs�eZd#Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
d�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd �Zd!�Zd"�ZRS($RtcolumnsR]tdisplaycolumnsR^R!t
selectmodeR�R.R`R�tyscrollcommandcCs,tt|�j�|jdd�|_dS(NR!i(R:R�R;Rttv(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR;cscKstj|j|�S(N(R<tTreeviewR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRgscCsa|j�}|j|dddd
�|j|dd�|j|dtdkrVd
nd	�dS(NR�sa b cR"R�R#RiiR(R�R#R(R�R#R(ii((RR,R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_columnsjs
cCs�|j�}d|d<|j|dddd�|j|dd�|j|dddd�|j|dd�|j|ddd
d�|j|ddd
d�|j|ddd
d�dS(NR�R#RR�R�sb a cR"s#alliiiRRsInvalid column index disColumn index 3 out of boundsi����sColumn index -2 out of bounds(R�R#R(R#R�R(R#R�R(s#all(iii(R�R#R(iii(ii����(RR,R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_displaycolumnsqs
c	CsN|j�}|j|ddddddt�|j|ddddt�dS(	NR^idi����it3cR3g�����LY@gfffff�Y@(RRGR�R(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s"cCs)|j�}|j|dddd�dS(NR�R�tbrowsetextended(RRv(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selectmode�scCs�|j�}|j|dddd�|j|dd�|j|dd�|j|dddd	�|j|dddd
�dS(NR�s
tree headingsR"ttreetheadings(R�R�(R�R�(R�R�(R�(R�(RR,(RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��scCsW|jj�|j|jjd�d�|jj�|jj�|jjdd�}|jj�}|j|�|jj|d�}|j	|�dg|jd<|jj
ddd�|jj|dd�}|jj
ddd�}|jst
|�}n|j|d|d|�|jj|d�}|j|jj|�d�dS(	NRR�ittestR�R7i2s#0(R�R?RR�R@R�R�tget_childrenR�R�tcolumnRHRR)(Rtitem_idtchildrenR�tbbox_column0t
root_widthRg((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��s$




	cCs>|j|jj�d�|jjdd�}|j|jj�t�|j|jj�d|�|jjdd�}|jjdd�}|jj|||�|j|jj|�||f�|jtj	|jj||�|jj|�|j|jj|�d�|jjd�|j|jj�d�dS(NRR�i((((
RR�R�R�R ttupletset_childrenRFRGR(RR�RR((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_children�s"cCsi|j|jjd�t�|jrJ|j|jjddd�t�n|jjddd�|j|jjdd�|jr�dnd�|j|jjddd�|jr�dnd�|jt	j
|jjddd�|jt	j
|jjd�idd	6id
d6id
d6id
d6id
d
6g}x-|D]%}|jt	j
|jjd|�q<WdS(Ns#0R7i
t10tidtXR�s
some valuetunknown_optiontwrongtstretchR�tminwidth(R R�R�R!RRHR)RRFRGR(Rtinvalid_kwsRM((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_column�s	%"$
cCs?|jtj|jjd�|jjdd�}|jj|d�}|j|jj�|f�|j|jj|�|f�|jj|�|j|jj��|jtj|jj	|dd�|jjdd�}|jjdd�}|j|jj�||f�|jj||�|j|jj��dS(Ns#0RR�(
RFRGRR�R�R�RR�R�treattach(RR�titem2titem1((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_delete�scCs0|jjdd�}|jj|d�}|jj�}|jj�|j||jj��|j|jj�|f�|j|jj|�|f�|jj|�|j|jj��|jj|dd�|j|jj�|f�|j|jj|�|f�|jj|dd�|j|jj�||f�|j|jj|�d�|jt	j
|jjddd�|jt	j
|jjd�|jt	j
|jj|dd�|jt	j
|jj|dd�|jj||�|j|jj�d�|j|jj|�d�dS(	NRR�tnonexistenttotherparentR�((((R�R�R�tdetachRR�R�tmoveRFRGR(RR�R�tprev((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_detach_reattach�s4
cCst|j|jjd�t�|j|jjd�t�|j|jji�t�|jtj|jjd�dS(Nt	somethingR(	RR�texistsR�RURFRGRRH(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_exists'scCs�|j|jj�d�|jjdd�}|jj|�|j|jj�|�|jj|�|j|jj�d�|jtj|jjd�dS(NRR�RO(RR�R�R�R�RFRGR(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_focus2scCs�|j|jjd�t�|jjddd�|j|jjdd�d�|j|jjddd�d�|jtj|jjddd�|jtj|jjddd�dS(Ns#0R8ROR�R�i(	R R�theadingR!RRHRFRGR(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_headingAs"cs�fd�}g��jj��jj��jjdd�fd���jjddd��jj�|dd��s��jd�ng��jjj}�jjddt	�jjddd����j|�jjj�|dd��s�jd�ndS(	Ncs$t�j||��jj�dS(N(R	R�R�(R�R�(R(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pytsimulate_heading_clickRss#0R�cs
�jt�S(N(R�RU((R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�ZRR7idis>The command associated to the treeview heading wasn't invoked.(R�R?R@R�R�R�RnRt_tclCommandsR�RHR(RR�tcommands((RR�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_heading_callbackQs"



.
cCs�|jtj|jjd�|j|jjd�d�|jjdd�}|jjdd�}|jj|d�}|jj|d�}|j|jj|�d�|j|jj|�d�|j|jj|�d�|j|jj|�d�|jj|dd�|j|jj|�d�|j|jj|�d�|jj|�|j|jj|�d�|jj|�|j|jj|�d�|jj	|�|jtj|jj|�dS(NtwhatRiR�i(
RFRGRR�RkRR�R�R�R�(RR�R�tc1tc2((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRzss&cCs�|jtj|jjdd�|jtj|jjdddd�|jtj|jjdddd�|j|jj|jjdddt���|j|jj|jjdddt���|jtj|jjdd�|jjddd�}|j	|d�|jtj|jjddd�|jtj|jjddt
d��d}|jjddd	|f�}|j	|jj|d	�|jr�|fn|�|j	|jj|d	d�|jr�|fn|�|jj|d	|jj|jj|d	d���|j	|jj|d	d�|jr@|fn|�|j|jj|�t�|jj|d	d�|j|jj|d	d��|jjddd
dd|g�}|j	|jj|d
d�|jr�d
d|fnd|�|jj|d
g�|j|jj|d
d��|jj|d
d�|j	|jj|d
d�|jrodnd�|jjddd	dd||ff�}|j	|jj|d	d�|jr�dd||ffn
d||f�|j	|jj|jjdddd�dd�d�|j	|jj|jjddd|�dd�|�|jjddd�}|j	|d�|jjddd�}|j	|d�|jtj|jjddt�|jtj|jjddd�dS(NR�R�Rtopentpleasetmiddles
first-itemuábaR�ttagsiiRRs1 2 %ss1 2sa b cs%s %ss{a b c} {%s %s}R8s
Label hereiR#gs0.0(ii(RR(RFRGRR�R�R�R�RUR�RRtitemRRHR>t	splitlistR R!(RtitemidR-R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_insert_item�sh..
4$!!"cCs�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jtj|jjd�|jjdd�}|jjdd�}|jj|d�}|jj|d�}|jj|d�}|j	|jj
�d
�|jj||f�|j	|jj
�||f�|jj|�|j	|jj
�|f�|jj||f�|j	|jj
�|||f�|jj|�|j	|jj
�||||f�|jj||f�|j	|jj
�|||f�|jj|�|j	|jj
�||f�|jj||f�|j	|jj
�||f�|jj|�|j	|jj
�|f�|jjdddd�|jjd�|j	|jj
�d�|jjdddd�|jjd�|j	|jj
�d�trl|jjdddtd��|jjtd��|j	|jj
�td�f�n|jjdddd�|jjd�|j	|jj
�tr�td	�ndf�dS(
NR�RR�R�swith spacess{braces
unicode\u20acsbytes€sbytes\u20ac((swith spaces(s{brace(
RFRGRR�t
selection_sett
selection_addtselection_removetselection_toggleR�Rt	selectionRR(RR�R�R�R�tc3((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_selection�sR"%"%cCsPddg|jd<|jjdddddg�}|j|jj|�idd6dd6�|jj|dd�|j|jj|dd�|jr�dnd	�dg|jd<|j|jj|�idd6�|jj|dd�|j|jj|d
d�d�|j|jj|dd�|jr:dnd�|jj|dd�|j|jj|d�|jr~dnd
�|j|jj|dd�|jr�dnd�|j|jj|�|jr�idd6n
id
d6�|jtj	|jj|d�|jtj	|jj|dd�|jtj	|jjd�dS(NtAtBR�RR�R�R�R#sa aR�sb ai{t123s123 atnotme(R�R�(R#R�(i{R�(
R�R�RRR�RHRRFRGR(RR�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyRWs,!*#"$"c	s�g�|jjddddg�}|jjddddg�}|jjdd�fd��|jjdd�fd��|jj�|jj�|jj�t�}t�}xqtd	d
d�D]]}t|�dkr�Pn|jj	|�}|r�||kr�|j
|�|j
|�q�q�W|jt|�d�x!|D]}t|jd	|�qJW|jt��d
�xAt
�ddd��ddd��D]}|j|d�q�WdS(NRR�R�tcalls<ButtonPress-1>cs
�jd�S(Ni(R�(R�(tevents(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�;Rs<ButtonRelease-1>cs
�jd�S(Ni(R�(R�(R�(s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�=Riidi
iii(ii(R�R�ttag_bindR?R@R�RRmR�tidentify_rowRRR	tzip(	RR�R�tpos_ytfoundRpR�R�R�((R�s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt
test_tag_bind6s2


		

0cCs�|jt|jj�|jtj|jjddd�|jjddd�|jt|jjdd��d�|jt|jjddd��d�|j	|jjd�t
�dS(NR�tskytblueR�(RFt	TypeErrorR�t
tag_configureRGRRR�RHR R!(R((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tag_configureXs
!cCs�|jjddddddg�}|jjddddddg�}|jt|jj�|jt|jjdd	�|j|jjd|��|j|jjd|��|j|jjd|��|j|jjd|��|j|jjd
|��|j|jjd
|��|j|jjd�|f�|j|jjd�|f�|j|jjd
�d�dS(NRR�R8sItem 1R�ttag1sItem 2ttag2snon-existingttag3((	R�R�RFR�ttag_hasRR�R�R(RR�R�((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyttest_tag_hasds$$(RR�R]R�R^R!R�R�R.R`R�R�(R4R5RcR;RR�R�R�R�R�R�R�R�R�R�R�R�R�R�RzR�R�RWR�R�R�(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�[s4													*				"		M	6	!	"	t
SeparatorTestcBseZdZdZd�ZRS(RR]RR.R`RcKstj|j|�S(N(R<t	SeparatorR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR|s(RR]RR.R`(R4R5RcR/R(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�tstSizegripTestcBseZdZd�ZRS(RR]R.R`cKstj|j|�S(N(R<tSizegripR>(RRb((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR�s(RR]R.R`(R4R5RcR(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyR��st__main__(5tunittesttTkinterRGRR<ttest.test_supportRRRRR�ttest_functionsRtsupportRRRR	twidget_testsR
RRR
RRRRRtTestCaseR6RYR[RdR~R�R�R�R�R�R
R,R4R>RXtskipIfR�RcReR�R�R�t	tests_guiR4(((s9/usr/lib64/python2.7/lib-tk/test/test_ttk/test_widgets.pyt<module>sr"":
';0�|�3j"
���	PK'/�Z�����
runtktests.pynu�[���"""
Use this module to get and run all tk tests.

Tkinter tests should live in a package inside the directory where this file
lives, like test_tkinter.
Extensions also should live in packages following the same rule as above.
"""

import os
import sys
import unittest
import importlib
import test.test_support

this_dir_path = os.path.abspath(os.path.dirname(__file__))

def is_package(path):
    for name in os.listdir(path):
        if name in ('__init__.py', '__init__.pyc', '__init.pyo'):
            return True
    return False

def get_tests_modules(basepath=this_dir_path, gui=True, packages=None):
    """This will import and yield modules whose names start with test_
    and are inside packages found in the path starting at basepath.

    If packages is specified it should contain package names that want
    their tests collected.
    """
    py_ext = '.py'

    for dirpath, dirnames, filenames in os.walk(basepath):
        for dirname in list(dirnames):
            if dirname[0] == '.':
                dirnames.remove(dirname)

        if is_package(dirpath) and filenames:
            pkg_name = dirpath[len(basepath) + len(os.sep):].replace('/', '.')
            if packages and pkg_name not in packages:
                continue

            filenames = filter(
                    lambda x: x.startswith('test_') and x.endswith(py_ext),
                    filenames)

            for name in filenames:
                try:
                    yield importlib.import_module(
                            ".%s" % name[:-len(py_ext)], pkg_name)
                except test.test_support.ResourceDenied:
                    if gui:
                        raise

def get_tests(text=True, gui=True, packages=None):
    """Yield all the tests in the modules found by get_tests_modules.

    If nogui is True, only tests that do not require a GUI will be
    returned."""
    attrs = []
    if text:
        attrs.append('tests_nogui')
    if gui:
        attrs.append('tests_gui')
    for module in get_tests_modules(gui=gui, packages=packages):
        for attr in attrs:
            for test in getattr(module, attr, ()):
                yield test

if __name__ == "__main__":
    test.test_support.run_unittest(*get_tests())
PK'/�Z�%��� � test_tkinter/test_variables.pynu�[���import unittest
import gc
from Tkinter import (Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl,
                     TclError)


class TestBase(unittest.TestCase):

    def setUp(self):
        self.root = Tcl()

    def tearDown(self):
        del self.root


class TestVariable(TestBase):

    def info_exists(self, *args):
        return self.root.getboolean(self.root.call("info", "exists", *args))

    def test_default(self):
        v = Variable(self.root)
        self.assertEqual("", v.get())
        self.assertRegexpMatches(str(v), r"^PY_VAR(\d+)$")

    def test_name_and_value(self):
        v = Variable(self.root, "sample string", "varname")
        self.assertEqual("sample string", v.get())
        self.assertEqual("varname", str(v))

    def test___del__(self):
        self.assertFalse(self.info_exists("varname"))
        v = Variable(self.root, "sample string", "varname")
        self.assertTrue(self.info_exists("varname"))
        del v
        self.assertFalse(self.info_exists("varname"))

    def test_dont_unset_not_existing(self):
        self.assertFalse(self.info_exists("varname"))
        v1 = Variable(self.root, name="name")
        v2 = Variable(self.root, name="name")
        del v1
        self.assertFalse(self.info_exists("name"))
        # shouldn't raise exception
        del v2
        self.assertFalse(self.info_exists("name"))

    def test___eq__(self):
        # values doesn't matter, only class and name are checked
        v1 = Variable(self.root, name="abc")
        v2 = Variable(self.root, name="abc")
        self.assertEqual(v1, v2)

        v3 = Variable(self.root, name="abc")
        v4 = StringVar(self.root, name="abc")
        self.assertNotEqual(v3, v4)

    def test_invalid_name(self):
        with self.assertRaises(TypeError):
            Variable(self.root, name=123)

    def test_null_in_name(self):
        with self.assertRaises(ValueError):
            Variable(self.root, name='var\x00name')
        with self.assertRaises(ValueError):
            self.root.globalsetvar('var\x00name', "value")
        with self.assertRaises(ValueError):
            self.root.setvar('var\x00name', "value")

    def test_trace(self):
        v = Variable(self.root)
        vname = str(v)
        trace = []
        def read_tracer(*args):
            trace.append(('read',) + args)
        def write_tracer(*args):
            trace.append(('write',) + args)
        cb1 = v.trace_variable('r', read_tracer)
        cb2 = v.trace_variable('wu', write_tracer)
        self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)])
        self.assertEqual(trace, [])

        v.set('spam')
        self.assertEqual(trace, [('write', vname, '', 'w')])

        trace = []
        v.get()
        self.assertEqual(trace, [('read', vname, '', 'r')])

        trace = []
        info = sorted(v.trace_vinfo())
        v.trace_vdelete('w', cb1)  # Wrong mode
        self.assertEqual(sorted(v.trace_vinfo()), info)
        with self.assertRaises(TclError):
            v.trace_vdelete('r', 'spam')  # Wrong command name
        self.assertEqual(sorted(v.trace_vinfo()), info)
        v.trace_vdelete('r', (cb1, 43)) # Wrong arguments
        self.assertEqual(sorted(v.trace_vinfo()), info)
        v.get()
        self.assertEqual(trace, [('read', vname, '', 'r')])

        trace = []
        v.trace_vdelete('r', cb1)
        self.assertEqual(v.trace_vinfo(), [('wu', cb2)])
        v.get()
        self.assertEqual(trace, [])

        trace = []
        del write_tracer
        gc.collect()
        v.set('eggs')
        self.assertEqual(trace, [('write', vname, '', 'w')])

        #trace = []
        #del v
        #gc.collect()
        #self.assertEqual(trace, [('write', vname, '', 'u')])


class TestStringVar(TestBase):

    def test_default(self):
        v = StringVar(self.root)
        self.assertEqual("", v.get())

    def test_get(self):
        v = StringVar(self.root, "abc", "name")
        self.assertEqual("abc", v.get())
        self.root.globalsetvar("name", "value")
        self.assertEqual("value", v.get())

    def test_get_null(self):
        v = StringVar(self.root, "abc\x00def", "name")
        self.assertEqual("abc\x00def", v.get())
        self.root.globalsetvar("name", "val\x00ue")
        self.assertEqual("val\x00ue", v.get())


class TestIntVar(TestBase):

    def test_default(self):
        v = IntVar(self.root)
        self.assertEqual(0, v.get())

    def test_get(self):
        v = IntVar(self.root, 123, "name")
        self.assertEqual(123, v.get())
        self.root.globalsetvar("name", "345")
        self.assertEqual(345, v.get())

    def test_invalid_value(self):
        v = IntVar(self.root, name="name")
        self.root.globalsetvar("name", "value")
        with self.assertRaises(ValueError):
            v.get()
        self.root.globalsetvar("name", "345.0")
        with self.assertRaises(ValueError):
            v.get()


class TestDoubleVar(TestBase):

    def test_default(self):
        v = DoubleVar(self.root)
        self.assertEqual(0.0, v.get())

    def test_get(self):
        v = DoubleVar(self.root, 1.23, "name")
        self.assertAlmostEqual(1.23, v.get())
        self.root.globalsetvar("name", "3.45")
        self.assertAlmostEqual(3.45, v.get())

    def test_get_from_int(self):
        v = DoubleVar(self.root, 1.23, "name")
        self.assertAlmostEqual(1.23, v.get())
        self.root.globalsetvar("name", "3.45")
        self.assertAlmostEqual(3.45, v.get())
        self.root.globalsetvar("name", "456")
        self.assertAlmostEqual(456, v.get())

    def test_invalid_value(self):
        v = DoubleVar(self.root, name="name")
        self.root.globalsetvar("name", "value")
        with self.assertRaises(ValueError):
            v.get()


class TestBooleanVar(TestBase):

    def test_default(self):
        v = BooleanVar(self.root)
        self.assertIs(v.get(), False)

    def test_get(self):
        v = BooleanVar(self.root, True, "name")
        self.assertIs(v.get(), True)
        self.root.globalsetvar("name", "0")
        self.assertIs(v.get(), False)
        self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1)
        self.assertIs(v.get(), True)
        self.root.globalsetvar("name", 0)
        self.assertIs(v.get(), False)
        self.root.globalsetvar("name", 42L if self.root.wantobjects() else 1L)
        self.assertIs(v.get(), True)
        self.root.globalsetvar("name", 0L)
        self.assertIs(v.get(), False)
        self.root.globalsetvar("name", "on")
        self.assertIs(v.get(), True)
        self.root.globalsetvar("name", u"0")
        self.assertIs(v.get(), False)
        self.root.globalsetvar("name", u"on")
        self.assertIs(v.get(), True)

    def test_set(self):
        true = 1 if self.root.wantobjects() else "1"
        false = 0 if self.root.wantobjects() else "0"
        v = BooleanVar(self.root, name="name")
        v.set(True)
        self.assertEqual(self.root.globalgetvar("name"), true)
        v.set("0")
        self.assertEqual(self.root.globalgetvar("name"), false)
        v.set(42)
        self.assertEqual(self.root.globalgetvar("name"), true)
        v.set(0)
        self.assertEqual(self.root.globalgetvar("name"), false)
        v.set(42L)
        self.assertEqual(self.root.globalgetvar("name"), true)
        v.set(0L)
        self.assertEqual(self.root.globalgetvar("name"), false)
        v.set("on")
        self.assertEqual(self.root.globalgetvar("name"), true)
        v.set(u"0")
        self.assertEqual(self.root.globalgetvar("name"), false)
        v.set(u"on")
        self.assertEqual(self.root.globalgetvar("name"), true)

    def test_invalid_value_domain(self):
        false = 0 if self.root.wantobjects() else "0"
        v = BooleanVar(self.root, name="name")
        with self.assertRaises(TclError):
            v.set("value")
        self.assertEqual(self.root.globalgetvar("name"), false)
        self.root.globalsetvar("name", "value")
        with self.assertRaises(TclError):
            v.get()
        self.root.globalsetvar("name", "1.0")
        with self.assertRaises(TclError):
            v.get()


tests_gui = (TestVariable, TestStringVar, TestIntVar,
             TestDoubleVar, TestBooleanVar)


if __name__ == "__main__":
    from test.support import run_unittest
    run_unittest(*tests_gui)
PK(/�Z���*test_tkinter/test_misc.pyonu�[����
zfc@s�ddlZddlZddlmZmZddlmZed�deejfd��YZ	e	fZ
edkr�ee
�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguitMiscTestcBs#eZd�Zd�Zd�ZRS(cs�|j}idd6�dd�fd�}|j|jd��d�d<|jd|�}|j||jjdd��|jj|jjdd|��\}}|j�|j�dd�|j	t
j��|jj|�WdQXd�d<|jd|dd�}|j�|j�dd	�|jd
|�}|j||jjdd��|jj|jjdd|��\}}|j|�|j�dd	�|j	t
j��|jj|�WdQXdS(Nitcountics||�d<dS(NR((tstarttstep(tcbcount(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pytcallbackstaftertinfoi*ii5i�(
troottassertIsNoneR
tassertInttktcallt	splitlisttupdatetassertEqualtassertRaisesttkintertTclErrortafter_cancel(tselfRR	ttimer1tscriptt_((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyt
test_after
s.	

*


*
cs�|j}idd6�dd�fd�}d�d<|j|�}|j||jjdd��|jj|jjdd|��\}}|j�|j�dd�|jt	j
��|jj|�WdQXd�d<|j|dd�}|j�|j�dd	�|j|�}|j||jjdd��|jj|jjdd|��\}}|j|�|j�dd	�|jt	j
��|jj|�WdQXdS(
NiRics||�d<dS(NR((RR(R(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyR	1sR
Ri*ii5(Rt
after_idleRRRRtupdate_idletasksRRRRR(RRR	tidle1RR((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyttest_after_idle-s,	

*


*
cs|j}idd6��fd�}|jd|�}|j|�}|jt��|jd�WdQXd�d<|jj|jj	dd|��\}}|jj	|�|j
�dd�|j|�|jtj��|jj	|�WdQX|j
�dd�|jtj��|jj	dd|�WdQX|j|�d�d<|jj|jj	dd|��\}}|jj	|�|j
�dd�|j|�|jtj��|jj	|�WdQX|j
�dd�|jtj��|jj	dd|�WdQXdS(NiRcs�dcd7<dS(NRi(((R(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyR	Qsi�R
Ri(
RR
RRt
ValueErrorRtNoneRRRRRR(RRR	RRRR((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyttest_after_cancelMs8	

*


*
(t__name__t
__module__RR R#(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyRs	#	 t__main__(tunittesttTkinterRttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR$(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyt<module>s
o	PK(/�Z���	����test_tkinter/test_widgets.pynu�[���import unittest
import Tkinter as tkinter
from Tkinter import TclError
import os
import sys
from test.test_support import requires, run_unittest

from test_ttk.support import (tcl_version, requires_tcl, get_tk_patchlevel,
                              widget_eq)
from widget_tests import (
    add_standard_options, noconv, noconv_meth, int_round, pixels_round,
    AbstractWidgetTest, StandardOptionsTests,
    IntegerSizeTests, PixelSizeTests,
    setUpModule)

requires('gui')


class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests):
    _conv_pad_pixels = noconv_meth

    def test_class(self):
        widget = self.create()
        self.assertEqual(widget['class'],
                         widget.__class__.__name__.title())
        self.checkInvalidParam(widget, 'class', 'Foo',
                errmsg="can't modify -class option after widget is created")
        widget2 = self.create(class_='Foo')
        self.assertEqual(widget2['class'], 'Foo')

    def test_colormap(self):
        widget = self.create()
        self.assertEqual(widget['colormap'], '')
        self.checkInvalidParam(widget, 'colormap', 'new',
                errmsg="can't modify -colormap option after widget is created")
        widget2 = self.create(colormap='new')
        self.assertEqual(widget2['colormap'], 'new')

    def test_container(self):
        widget = self.create()
        self.assertEqual(widget['container'], 0 if self.wantobjects else '0')
        self.checkInvalidParam(widget, 'container', 1,
                errmsg="can't modify -container option after widget is created")
        widget2 = self.create(container=True)
        self.assertEqual(widget2['container'], 1 if self.wantobjects else '1')

    def test_visual(self):
        widget = self.create()
        self.assertEqual(widget['visual'], '')
        self.checkInvalidParam(widget, 'visual', 'default',
                errmsg="can't modify -visual option after widget is created")
        widget2 = self.create(visual='default')
        self.assertEqual(widget2['visual'], 'default')


@add_standard_options(StandardOptionsTests)
class ToplevelTest(AbstractToplevelTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth',
        'class', 'colormap', 'container', 'cursor', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'menu', 'padx', 'pady', 'relief', 'screen',
        'takefocus', 'use', 'visual', 'width',
    )

    def create(self, **kwargs):
        return tkinter.Toplevel(self.root, **kwargs)

    def test_menu(self):
        widget = self.create()
        menu = tkinter.Menu(self.root)
        self.checkParam(widget, 'menu', menu, eq=widget_eq)
        self.checkParam(widget, 'menu', '')

    def test_screen(self):
        widget = self.create()
        self.assertEqual(widget['screen'], '')
        try:
            display = os.environ['DISPLAY']
        except KeyError:
            self.skipTest('No $DISPLAY set.')
        self.checkInvalidParam(widget, 'screen', display,
                errmsg="can't modify -screen option after widget is created")
        widget2 = self.create(screen=display)
        self.assertEqual(widget2['screen'], display)

    def test_use(self):
        widget = self.create()
        self.assertEqual(widget['use'], '')
        parent = self.create(container=True)
        # hex() adds the 'L' suffix for longs
        wid = '%#x' % parent.winfo_id()
        widget2 = self.create(use=wid)
        self.assertEqual(widget2['use'], wid)


@add_standard_options(StandardOptionsTests)
class FrameTest(AbstractToplevelTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth',
        'class', 'colormap', 'container', 'cursor', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'padx', 'pady', 'relief', 'takefocus', 'visual', 'width',
    )

    def create(self, **kwargs):
        return tkinter.Frame(self.root, **kwargs)


@add_standard_options(StandardOptionsTests)
class LabelFrameTest(AbstractToplevelTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth',
        'class', 'colormap', 'container', 'cursor',
        'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'labelanchor', 'labelwidget', 'padx', 'pady', 'relief',
        'takefocus', 'text', 'visual', 'width',
    )

    def create(self, **kwargs):
        return tkinter.LabelFrame(self.root, **kwargs)

    def test_labelanchor(self):
        widget = self.create()
        self.checkEnumParam(widget, 'labelanchor',
                            'e', 'en', 'es', 'n', 'ne', 'nw',
                            's', 'se', 'sw', 'w', 'wn', 'ws')
        self.checkInvalidParam(widget, 'labelanchor', 'center')

    def test_labelwidget(self):
        widget = self.create()
        label = tkinter.Label(self.root, text='Mupp', name='foo')
        self.checkParam(widget, 'labelwidget', label, expected='.foo')
        label.destroy()


class AbstractLabelTest(AbstractWidgetTest, IntegerSizeTests):
    _conv_pixels = noconv_meth

    def test_highlightthickness(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'highlightthickness',
                              0, 1.3, 2.6, 6, -2, '10p')


@add_standard_options(StandardOptionsTests)
class LabelTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth', 'compound', 'cursor',
        'disabledforeground', 'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'justify', 'padx', 'pady', 'relief', 'state',
        'takefocus', 'text', 'textvariable',
        'underline', 'width', 'wraplength',
    )

    def create(self, **kwargs):
        return tkinter.Label(self.root, **kwargs)


@add_standard_options(StandardOptionsTests)
class ButtonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth',
        'command', 'compound', 'cursor', 'default',
        'disabledforeground', 'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'justify', 'overrelief', 'padx', 'pady', 'relief',
        'repeatdelay', 'repeatinterval',
        'state', 'takefocus', 'text', 'textvariable',
        'underline', 'width', 'wraplength')

    def create(self, **kwargs):
        return tkinter.Button(self.root, **kwargs)

    def test_default(self):
        widget = self.create()
        self.checkEnumParam(widget, 'default', 'active', 'disabled', 'normal')


@add_standard_options(StandardOptionsTests)
class CheckbuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth',
        'command', 'compound', 'cursor',
        'disabledforeground', 'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'indicatoron', 'justify',
        'offrelief', 'offvalue', 'onvalue', 'overrelief',
        'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state',
        'takefocus', 'text', 'textvariable',
        'tristateimage', 'tristatevalue',
        'underline', 'variable', 'width', 'wraplength',
    )

    def create(self, **kwargs):
        return tkinter.Checkbutton(self.root, **kwargs)


    def test_offvalue(self):
        widget = self.create()
        self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string')

    def test_onvalue(self):
        widget = self.create()
        self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string')


@add_standard_options(StandardOptionsTests)
class RadiobuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth',
        'command', 'compound', 'cursor',
        'disabledforeground', 'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'indicatoron', 'justify', 'offrelief', 'overrelief',
        'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state',
        'takefocus', 'text', 'textvariable',
        'tristateimage', 'tristatevalue',
        'underline', 'value', 'variable', 'width', 'wraplength',
    )

    def create(self, **kwargs):
        return tkinter.Radiobutton(self.root, **kwargs)

    def test_value(self):
        widget = self.create()
        self.checkParams(widget, 'value', 1, 2.3, '', 'any string')


@add_standard_options(StandardOptionsTests)
class MenubuttonTest(AbstractLabelTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeforeground', 'anchor',
        'background', 'bitmap', 'borderwidth',
        'compound', 'cursor', 'direction',
        'disabledforeground', 'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'image', 'indicatoron', 'justify', 'menu',
        'padx', 'pady', 'relief', 'state',
        'takefocus', 'text', 'textvariable',
        'underline', 'width', 'wraplength',
    )
    _conv_pixels = staticmethod(pixels_round)

    def create(self, **kwargs):
        return tkinter.Menubutton(self.root, **kwargs)

    def test_direction(self):
        widget = self.create()
        self.checkEnumParam(widget, 'direction',
                'above', 'below', 'flush', 'left', 'right')

    def test_height(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'height', 100, -100, 0, conv=str)

    test_highlightthickness = StandardOptionsTests.test_highlightthickness.im_func

    @unittest.skipIf(sys.platform == 'darwin',
                     'crashes with Cocoa Tk (issue19733)')
    def test_image(self):
        widget = self.create()
        image = tkinter.PhotoImage(master=self.root, name='image1')
        self.checkParam(widget, 'image', image, conv=str)
        errmsg = 'image "spam" doesn\'t exist'
        with self.assertRaises(tkinter.TclError) as cm:
            widget['image'] = 'spam'
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)
        with self.assertRaises(tkinter.TclError) as cm:
            widget.configure({'image': 'spam'})
        if errmsg is not None:
            self.assertEqual(str(cm.exception), errmsg)

    def test_menu(self):
        widget = self.create()
        menu = tkinter.Menu(widget, name='menu')
        self.checkParam(widget, 'menu', menu, eq=widget_eq)
        menu.destroy()

    def test_padx(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, '12m')
        self.checkParam(widget, 'padx', -2, expected=0)

    def test_pady(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, '12m')
        self.checkParam(widget, 'pady', -2, expected=0)

    def test_width(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'width', 402, -402, 0, conv=str)


class OptionMenuTest(MenubuttonTest, unittest.TestCase):

    def create(self, default='b', values=('a', 'b', 'c'), **kwargs):
        return tkinter.OptionMenu(self.root, None, default, *values, **kwargs)


@add_standard_options(IntegerSizeTests, StandardOptionsTests)
class EntryTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth', 'cursor',
        'disabledbackground', 'disabledforeground',
        'exportselection', 'font', 'foreground',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'insertbackground', 'insertborderwidth',
        'insertofftime', 'insertontime', 'insertwidth',
        'invalidcommand', 'justify', 'readonlybackground', 'relief',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'show', 'state', 'takefocus', 'textvariable',
        'validate', 'validatecommand', 'width', 'xscrollcommand',
    )

    def create(self, **kwargs):
        return tkinter.Entry(self.root, **kwargs)

    def test_disabledbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'disabledbackground')

    def test_insertborderwidth(self):
        widget = self.create(insertwidth=100)
        self.checkPixelsParam(widget, 'insertborderwidth',
                              0, 1.3, 2.6, 6, -2, '10p')
        # insertborderwidth is bounded above by a half of insertwidth.
        self.checkParam(widget, 'insertborderwidth', 60, expected=100//2)

    def test_insertwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'insertwidth', 1.3, 3.6, '10p')
        self.checkParam(widget, 'insertwidth', 0.1, expected=2)
        self.checkParam(widget, 'insertwidth', -2, expected=2)
        if pixels_round(0.9) <= 0:
            self.checkParam(widget, 'insertwidth', 0.9, expected=2)
        else:
            self.checkParam(widget, 'insertwidth', 0.9, expected=1)

    def test_invalidcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'invalidcommand')
        self.checkCommandParam(widget, 'invcmd')

    def test_readonlybackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'readonlybackground')

    def test_show(self):
        widget = self.create()
        self.checkParam(widget, 'show', '*')
        self.checkParam(widget, 'show', '')
        self.checkParam(widget, 'show', ' ')

    def test_state(self):
        widget = self.create()
        self.checkEnumParam(widget, 'state',
                            'disabled', 'normal', 'readonly')

    def test_validate(self):
        widget = self.create()
        self.checkEnumParam(widget, 'validate',
                'all', 'key', 'focus', 'focusin', 'focusout', 'none')

    def test_validatecommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'validatecommand')
        self.checkCommandParam(widget, 'vcmd')


@add_standard_options(StandardOptionsTests)
class SpinboxTest(EntryTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'background', 'borderwidth',
        'buttonbackground', 'buttoncursor', 'buttondownrelief', 'buttonuprelief',
        'command', 'cursor', 'disabledbackground', 'disabledforeground',
        'exportselection', 'font', 'foreground', 'format', 'from',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'increment',
        'insertbackground', 'insertborderwidth',
        'insertofftime', 'insertontime', 'insertwidth',
        'invalidcommand', 'justify', 'relief', 'readonlybackground',
        'repeatdelay', 'repeatinterval',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'state', 'takefocus', 'textvariable', 'to',
        'validate', 'validatecommand', 'values',
        'width', 'wrap', 'xscrollcommand',
    )

    def create(self, **kwargs):
        return tkinter.Spinbox(self.root, **kwargs)

    test_show = None

    def test_buttonbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'buttonbackground')

    def test_buttoncursor(self):
        widget = self.create()
        self.checkCursorParam(widget, 'buttoncursor')

    def test_buttondownrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'buttondownrelief')

    def test_buttonuprelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'buttonuprelief')

    def test_format(self):
        widget = self.create()
        self.checkParam(widget, 'format', '%2f')
        self.checkParam(widget, 'format', '%2.2f')
        self.checkParam(widget, 'format', '%.2f')
        self.checkParam(widget, 'format', '%2.f')
        self.checkInvalidParam(widget, 'format', '%2e-1f')
        self.checkInvalidParam(widget, 'format', '2.2')
        self.checkInvalidParam(widget, 'format', '%2.-2f')
        self.checkParam(widget, 'format', '%-2.02f')
        self.checkParam(widget, 'format', '% 2.02f')
        self.checkParam(widget, 'format', '% -2.200f')
        self.checkParam(widget, 'format', '%09.200f')
        self.checkInvalidParam(widget, 'format', '%d')

    def test_from(self):
        widget = self.create()
        self.checkParam(widget, 'to', 100.0)
        self.checkFloatParam(widget, 'from', -10, 10.2, 11.7)
        self.checkInvalidParam(widget, 'from', 200,
                errmsg='-to value must be greater than -from value')

    def test_increment(self):
        widget = self.create()
        self.checkFloatParam(widget, 'increment', -1, 1, 10.2, 12.8, 0)

    def test_to(self):
        widget = self.create()
        self.checkParam(widget, 'from', -100.0)
        self.checkFloatParam(widget, 'to', -10, 10.2, 11.7)
        self.checkInvalidParam(widget, 'to', -200,
                errmsg='-to value must be greater than -from value')

    def test_values(self):
        # XXX
        widget = self.create()
        self.assertEqual(widget['values'], '')
        self.checkParam(widget, 'values', 'mon tue wed thur')
        self.checkParam(widget, 'values', ('mon', 'tue', 'wed', 'thur'),
                        expected='mon tue wed thur')
        self.checkParam(widget, 'values', (42, 3.14, '', 'any string'),
                        expected='42 3.14 {} {any string}')
        self.checkParam(widget, 'values', '')

    def test_wrap(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'wrap')

    def test_bbox(self):
        widget = self.create()
        self.assertIsBoundingBox(widget.bbox(0))
        self.assertRaises(tkinter.TclError, widget.bbox, 'noindex')
        self.assertRaises(tkinter.TclError, widget.bbox, None)
        self.assertRaises(TypeError, widget.bbox)
        self.assertRaises(TypeError, widget.bbox, 0, 1)

    def test_selection_element(self):
        widget = self.create()
        self.assertEqual(widget.selection_element(), "none")
        widget.selection_element("buttonup")
        self.assertEqual(widget.selection_element(), "buttonup")
        widget.selection_element("buttondown")
        self.assertEqual(widget.selection_element(), "buttondown")


@add_standard_options(StandardOptionsTests)
class TextTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'autoseparators', 'background', 'blockcursor', 'borderwidth',
        'cursor', 'endline', 'exportselection',
        'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'inactiveselectbackground', 'insertbackground', 'insertborderwidth',
        'insertofftime', 'insertontime', 'insertunfocussed', 'insertwidth',
        'maxundo', 'padx', 'pady', 'relief',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'setgrid', 'spacing1', 'spacing2', 'spacing3', 'startline', 'state',
        'tabs', 'tabstyle', 'takefocus', 'undo', 'width', 'wrap',
        'xscrollcommand', 'yscrollcommand',
    )
    if tcl_version < (8, 5):
        _stringify = True

    def create(self, **kwargs):
        return tkinter.Text(self.root, **kwargs)

    def test_autoseparators(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'autoseparators')

    @requires_tcl(8, 5)
    def test_blockcursor(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'blockcursor')

    @requires_tcl(8, 5)
    def test_endline(self):
        widget = self.create()
        text = '\n'.join('Line %d' for i in range(100))
        widget.insert('end', text)
        self.checkParam(widget, 'endline', 200, expected='')
        self.checkParam(widget, 'endline', -10, expected='')
        self.checkInvalidParam(widget, 'endline', 'spam',
                errmsg='expected integer but got "spam"')
        self.checkParam(widget, 'endline', 50)
        self.checkParam(widget, 'startline', 15)
        self.checkInvalidParam(widget, 'endline', 10,
                errmsg='-startline must be less than or equal to -endline')

    def test_height(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, '3c')
        self.checkParam(widget, 'height', -100, expected=1)
        self.checkParam(widget, 'height', 0, expected=1)

    def test_maxundo(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'maxundo', 0, 5, -1)

    @requires_tcl(8, 5)
    def test_inactiveselectbackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'inactiveselectbackground')

    @requires_tcl(8, 6)
    def test_insertunfocussed(self):
        widget = self.create()
        self.checkEnumParam(widget, 'insertunfocussed',
                            'hollow', 'none', 'solid')

    def test_selectborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'selectborderwidth',
                              1.3, 2.6, -2, '10p', conv=noconv,
                              keep_orig=tcl_version >= (8, 5))

    def test_spacing1(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'spacing1', 20, 21.4, 22.6, '0.5c')
        self.checkParam(widget, 'spacing1', -5, expected=0)

    def test_spacing2(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'spacing2', 5, 6.4, 7.6, '0.1c')
        self.checkParam(widget, 'spacing2', -1, expected=0)

    def test_spacing3(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'spacing3', 20, 21.4, 22.6, '0.5c')
        self.checkParam(widget, 'spacing3', -10, expected=0)

    @requires_tcl(8, 5)
    def test_startline(self):
        widget = self.create()
        text = '\n'.join('Line %d' for i in range(100))
        widget.insert('end', text)
        self.checkParam(widget, 'startline', 200, expected='')
        self.checkParam(widget, 'startline', -10, expected='')
        self.checkInvalidParam(widget, 'startline', 'spam',
                errmsg='expected integer but got "spam"')
        self.checkParam(widget, 'startline', 10)
        self.checkParam(widget, 'endline', 50)
        self.checkInvalidParam(widget, 'startline', 70,
                errmsg='-startline must be less than or equal to -endline')

    def test_state(self):
        widget = self.create()
        if tcl_version < (8, 5):
            self.checkParams(widget, 'state', 'disabled', 'normal')
        else:
            self.checkEnumParam(widget, 'state', 'disabled', 'normal')

    def test_tabs(self):
        widget = self.create()
        if get_tk_patchlevel() < (8, 5, 11):
            self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i'),
                            expected=('10.2', '20.7', '1i', '2i'))
        else:
            self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i'))
        self.checkParam(widget, 'tabs', '10.2 20.7 1i 2i',
                        expected=('10.2', '20.7', '1i', '2i'))
        self.checkParam(widget, 'tabs', '2c left 4c 6c center',
                        expected=('2c', 'left', '4c', '6c', 'center'))
        self.checkInvalidParam(widget, 'tabs', 'spam',
                               errmsg='bad screen distance "spam"',
                               keep_orig=tcl_version >= (8, 5))

    @requires_tcl(8, 5)
    def test_tabstyle(self):
        widget = self.create()
        self.checkEnumParam(widget, 'tabstyle', 'tabular', 'wordprocessor')

    def test_undo(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'undo')

    def test_width(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'width', 402)
        self.checkParam(widget, 'width', -402, expected=1)
        self.checkParam(widget, 'width', 0, expected=1)

    def test_wrap(self):
        widget = self.create()
        if tcl_version < (8, 5):
            self.checkParams(widget, 'wrap', 'char', 'none', 'word')
        else:
            self.checkEnumParam(widget, 'wrap', 'char', 'none', 'word')

    def test_bbox(self):
        widget = self.create()
        self.assertIsBoundingBox(widget.bbox('1.1'))
        self.assertIsNone(widget.bbox('end'))
        self.assertRaises(tkinter.TclError, widget.bbox, 'noindex')
        self.assertRaises(tkinter.TclError, widget.bbox, None)
        self.assertRaises(tkinter.TclError, widget.bbox)
        self.assertRaises(tkinter.TclError, widget.bbox, '1.1', 'end')


@add_standard_options(PixelSizeTests, StandardOptionsTests)
class CanvasTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth',
        'closeenough', 'confine', 'cursor', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'insertbackground', 'insertborderwidth',
        'insertofftime', 'insertontime', 'insertwidth',
        'offset', 'relief', 'scrollregion',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'state', 'takefocus',
        'xscrollcommand', 'xscrollincrement',
        'yscrollcommand', 'yscrollincrement', 'width',
    )

    _conv_pixels = staticmethod(int_round)
    _stringify = True

    def create(self, **kwargs):
        return tkinter.Canvas(self.root, **kwargs)

    def test_closeenough(self):
        widget = self.create()
        self.checkFloatParam(widget, 'closeenough', 24, 2.4, 3.6, -3,
                             conv=float)

    def test_confine(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'confine')

    def test_offset(self):
        widget = self.create()
        self.assertEqual(widget['offset'], '0,0')
        self.checkParams(widget, 'offset',
                'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center')
        self.checkParam(widget, 'offset', '10,20')
        self.checkParam(widget, 'offset', '#5,6')
        self.checkInvalidParam(widget, 'offset', 'spam')

    def test_scrollregion(self):
        widget = self.create()
        self.checkParam(widget, 'scrollregion', '0 0 200 150')
        self.checkParam(widget, 'scrollregion', (0, 0, 200, 150),
                        expected='0 0 200 150')
        self.checkParam(widget, 'scrollregion', '')
        self.checkInvalidParam(widget, 'scrollregion', 'spam',
                               errmsg='bad scrollRegion "spam"')
        self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 'spam'))
        self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200))
        self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 150, 0))

    def test_state(self):
        widget = self.create()
        self.checkEnumParam(widget, 'state', 'disabled', 'normal',
                errmsg='bad state value "{}": must be normal or disabled')

    def test_xscrollincrement(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'xscrollincrement',
                              40, 0, 41.2, 43.6, -40, '0.5i')

    def test_yscrollincrement(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'yscrollincrement',
                              10, 0, 11.2, 13.6, -10, '0.1i')


@add_standard_options(IntegerSizeTests, StandardOptionsTests)
class ListboxTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'activestyle', 'background', 'borderwidth', 'cursor',
        'disabledforeground', 'exportselection',
        'font', 'foreground', 'height',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'justify', 'listvariable', 'relief',
        'selectbackground', 'selectborderwidth', 'selectforeground',
        'selectmode', 'setgrid', 'state',
        'takefocus', 'width', 'xscrollcommand', 'yscrollcommand',
    )

    def create(self, **kwargs):
        return tkinter.Listbox(self.root, **kwargs)

    def test_activestyle(self):
        widget = self.create()
        self.checkEnumParam(widget, 'activestyle',
                            'dotbox', 'none', 'underline')

    test_justify = requires_tcl(8, 6, 5)(StandardOptionsTests.test_justify.im_func)

    def test_listvariable(self):
        widget = self.create()
        var = tkinter.DoubleVar(self.root)
        self.checkVariableParam(widget, 'listvariable', var)

    def test_selectmode(self):
        widget = self.create()
        self.checkParam(widget, 'selectmode', 'single')
        self.checkParam(widget, 'selectmode', 'browse')
        self.checkParam(widget, 'selectmode', 'multiple')
        self.checkParam(widget, 'selectmode', 'extended')

    def test_state(self):
        widget = self.create()
        self.checkEnumParam(widget, 'state', 'disabled', 'normal')

    def test_itemconfigure(self):
        widget = self.create()
        with self.assertRaisesRegexp(TclError, 'item number "0" out of range'):
            widget.itemconfigure(0)
        colors = 'red orange yellow green blue white violet'.split()
        widget.insert('end', *colors)
        for i, color in enumerate(colors):
            widget.itemconfigure(i, background=color)
        with self.assertRaises(TypeError):
            widget.itemconfigure()
        with self.assertRaisesRegexp(TclError, 'bad listbox index "red"'):
            widget.itemconfigure('red')
        self.assertEqual(widget.itemconfigure(0, 'background'),
                         ('background', 'background', 'Background', '', 'red'))
        self.assertEqual(widget.itemconfigure('end', 'background'),
                         ('background', 'background', 'Background', '', 'violet'))
        self.assertEqual(widget.itemconfigure('@0,0', 'background'),
                         ('background', 'background', 'Background', '', 'red'))

        d = widget.itemconfigure(0)
        self.assertIsInstance(d, dict)
        for k, v in d.items():
            self.assertIn(len(v), (2, 5))
            if len(v) == 5:
                self.assertEqual(v, widget.itemconfigure(0, k))
                self.assertEqual(v[4], widget.itemcget(0, k))

    def check_itemconfigure(self, name, value):
        widget = self.create()
        widget.insert('end', 'a', 'b', 'c', 'd')
        widget.itemconfigure(0, **{name: value})
        self.assertEqual(widget.itemconfigure(0, name)[4], value)
        self.assertEqual(widget.itemcget(0, name), value)
        with self.assertRaisesRegexp(TclError, 'unknown color name "spam"'):
            widget.itemconfigure(0, **{name: 'spam'})

    def test_itemconfigure_background(self):
        self.check_itemconfigure('background', '#ff0000')

    def test_itemconfigure_bg(self):
        self.check_itemconfigure('bg', '#ff0000')

    def test_itemconfigure_fg(self):
        self.check_itemconfigure('fg', '#110022')

    def test_itemconfigure_foreground(self):
        self.check_itemconfigure('foreground', '#110022')

    def test_itemconfigure_selectbackground(self):
        self.check_itemconfigure('selectbackground', '#110022')

    def test_itemconfigure_selectforeground(self):
        self.check_itemconfigure('selectforeground', '#654321')

    def test_box(self):
        lb = self.create()
        lb.insert(0, *('el%d' % i for i in range(8)))
        lb.pack()
        self.assertIsBoundingBox(lb.bbox(0))
        self.assertIsNone(lb.bbox(-1))
        self.assertIsNone(lb.bbox(10))
        self.assertRaises(TclError, lb.bbox, 'noindex')
        self.assertRaises(TclError, lb.bbox, None)
        self.assertRaises(TypeError, lb.bbox)
        self.assertRaises(TypeError, lb.bbox, 0, 1)

    def test_curselection(self):
        lb = self.create()
        lb.insert(0, *('el%d' % i for i in range(8)))
        lb.selection_clear(0, tkinter.END)
        lb.selection_set(2, 4)
        lb.selection_set(6)
        self.assertEqual(lb.curselection(), (2, 3, 4, 6))
        self.assertRaises(TypeError, lb.curselection, 0)

    def test_get(self):
        lb = self.create()
        lb.insert(0, *('el%d' % i for i in range(8)))
        self.assertEqual(lb.get(0), 'el0')
        self.assertEqual(lb.get(3), 'el3')
        self.assertEqual(lb.get('end'), 'el7')
        self.assertEqual(lb.get(8), '')
        self.assertEqual(lb.get(-1), '')
        self.assertEqual(lb.get(3, 5), ('el3', 'el4', 'el5'))
        self.assertEqual(lb.get(5, 'end'), ('el5', 'el6', 'el7'))
        self.assertEqual(lb.get(5, 0), ())
        self.assertEqual(lb.get(0, 0), ('el0',))
        self.assertRaises(TclError, lb.get, 'noindex')
        self.assertRaises(TclError, lb.get, None)
        self.assertRaises(TypeError, lb.get)
        self.assertRaises(TclError, lb.get, 'end', 'noindex')
        self.assertRaises(TypeError, lb.get, 1, 2, 3)
        self.assertRaises(TclError, lb.get, 2.4)


@add_standard_options(PixelSizeTests, StandardOptionsTests)
class ScaleTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'background', 'bigincrement', 'borderwidth',
        'command', 'cursor', 'digits', 'font', 'foreground', 'from',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'label', 'length', 'orient', 'relief',
        'repeatdelay', 'repeatinterval',
        'resolution', 'showvalue', 'sliderlength', 'sliderrelief', 'state',
        'takefocus', 'tickinterval', 'to', 'troughcolor', 'variable', 'width',
    )
    default_orient = 'vertical'

    def create(self, **kwargs):
        return tkinter.Scale(self.root, **kwargs)

    def test_bigincrement(self):
        widget = self.create()
        self.checkFloatParam(widget, 'bigincrement', 12.4, 23.6, -5)

    def test_digits(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'digits', 5, 0)

    def test_from(self):
        widget = self.create()
        self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=round)

    def test_label(self):
        widget = self.create()
        self.checkParam(widget, 'label', 'any string')
        self.checkParam(widget, 'label', '')

    def test_length(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i')

    def test_resolution(self):
        widget = self.create()
        self.checkFloatParam(widget, 'resolution', 4.2, 0, 6.7, -2)

    def test_showvalue(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'showvalue')

    def test_sliderlength(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'sliderlength',
                              10, 11.2, 15.6, -3, '3m')

    def test_sliderrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'sliderrelief')

    def test_tickinterval(self):
        widget = self.create()
        self.checkFloatParam(widget, 'tickinterval', 1, 4.3, 7.6, 0,
                             conv=round)
        self.checkParam(widget, 'tickinterval', -2, expected=2,
                        conv=round)

    def test_to(self):
        widget = self.create()
        self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10,
                             conv=round)


@add_standard_options(PixelSizeTests, StandardOptionsTests)
class ScrollbarTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activerelief',
        'background', 'borderwidth',
        'command', 'cursor', 'elementborderwidth',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'jump', 'orient', 'relief',
        'repeatdelay', 'repeatinterval',
        'takefocus', 'troughcolor', 'width',
    )
    _conv_pixels = staticmethod(int_round)
    _stringify = True
    default_orient = 'vertical'

    def create(self, **kwargs):
        return tkinter.Scrollbar(self.root, **kwargs)

    def test_activerelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'activerelief')

    def test_elementborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'elementborderwidth', 4.3, 5.6, -2, '1m')

    def test_orient(self):
        widget = self.create()
        self.checkEnumParam(widget, 'orient', 'vertical', 'horizontal',
                errmsg='bad orientation "{}": must be vertical or horizontal')

    def test_activate(self):
        sb = self.create()
        for e in ('arrow1', 'slider', 'arrow2'):
            sb.activate(e)
        sb.activate('')
        self.assertRaises(TypeError, sb.activate)
        self.assertRaises(TypeError, sb.activate, 'arrow1', 'arrow2')

    def test_set(self):
        sb = self.create()
        sb.set(0.2, 0.4)
        self.assertEqual(sb.get(), (0.2, 0.4))
        self.assertRaises(TclError, sb.set, 'abc', 'def')
        self.assertRaises(TclError, sb.set, 0.6, 'def')
        self.assertRaises(TclError, sb.set, 0.6, None)
        self.assertRaises(TclError, sb.set, 0.6)
        self.assertRaises(TclError, sb.set, 0.6, 0.7, 0.8)


@add_standard_options(StandardOptionsTests)
class PanedWindowTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'background', 'borderwidth', 'cursor',
        'handlepad', 'handlesize', 'height',
        'opaqueresize', 'orient',
        'proxybackground', 'proxyborderwidth', 'proxyrelief',
        'relief',
        'sashcursor', 'sashpad', 'sashrelief', 'sashwidth',
        'showhandle', 'width',
    )
    default_orient = 'horizontal'

    def create(self, **kwargs):
        return tkinter.PanedWindow(self.root, **kwargs)

    def test_handlepad(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'handlepad', 5, 6.4, 7.6, -3, '1m')

    def test_handlesize(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'handlesize', 8, 9.4, 10.6, -3, '2m',
                              conv=noconv)

    def test_height(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i',
                              conv=noconv)

    def test_opaqueresize(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'opaqueresize')

    @requires_tcl(8, 6, 5)
    def test_proxybackground(self):
        widget = self.create()
        self.checkColorParam(widget, 'proxybackground')

    @requires_tcl(8, 6, 5)
    def test_proxyborderwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'proxyborderwidth',
                              0, 1.3, 2.9, 6, -2, '10p',
                              conv=noconv)

    @requires_tcl(8, 6, 5)
    def test_proxyrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'proxyrelief')

    def test_sashcursor(self):
        widget = self.create()
        self.checkCursorParam(widget, 'sashcursor')

    def test_sashpad(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'sashpad', 8, 1.3, 2.6, -2, '2m')

    def test_sashrelief(self):
        widget = self.create()
        self.checkReliefParam(widget, 'sashrelief')

    def test_sashwidth(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'sashwidth', 10, 11.1, 15.6, -3, '1m',
                              conv=noconv)

    def test_showhandle(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'showhandle')

    def test_width(self):
        widget = self.create()
        self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i',
                              conv=noconv)

    def create2(self):
        p = self.create()
        b = tkinter.Button(p)
        c = tkinter.Button(p)
        p.add(b)
        p.add(c)
        return p, b, c

    def test_paneconfigure(self):
        p, b, c = self.create2()
        self.assertRaises(TypeError, p.paneconfigure)
        d = p.paneconfigure(b)
        self.assertIsInstance(d, dict)
        for k, v in d.items():
            self.assertEqual(len(v), 5)
            self.assertEqual(v, p.paneconfigure(b, k))
            self.assertEqual(v[4], p.panecget(b, k))

    def check_paneconfigure(self, p, b, name, value, expected, stringify=False):
        conv = lambda x: x
        if not self.wantobjects or stringify:
            expected = str(expected)
        if self.wantobjects and stringify:
            conv = str
        p.paneconfigure(b, **{name: value})
        self.assertEqual(conv(p.paneconfigure(b, name)[4]), expected)
        self.assertEqual(conv(p.panecget(b, name)), expected)

    def check_paneconfigure_bad(self, p, b, name, msg):
        with self.assertRaisesRegexp(TclError, msg):
            p.paneconfigure(b, **{name: 'badValue'})

    def test_paneconfigure_after(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'after', c, str(c))
        self.check_paneconfigure_bad(p, b, 'after',
                                     'bad window path name "badValue"')

    def test_paneconfigure_before(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'before', c, str(c))
        self.check_paneconfigure_bad(p, b, 'before',
                                     'bad window path name "badValue"')

    def test_paneconfigure_height(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'height', 10, 10,
                                 stringify=get_tk_patchlevel() < (8, 5, 11))
        self.check_paneconfigure_bad(p, b, 'height',
                                     'bad screen distance "badValue"')

    @requires_tcl(8, 5)
    def test_paneconfigure_hide(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'hide', False, 0)
        self.check_paneconfigure_bad(p, b, 'hide',
                                     'expected boolean value but got "badValue"')

    def test_paneconfigure_minsize(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'minsize', 10, 10)
        self.check_paneconfigure_bad(p, b, 'minsize',
                                     'bad screen distance "badValue"')

    def test_paneconfigure_padx(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'padx', 1.3, 1)
        self.check_paneconfigure_bad(p, b, 'padx',
                                     'bad screen distance "badValue"')

    def test_paneconfigure_pady(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'pady', 1.3, 1)
        self.check_paneconfigure_bad(p, b, 'pady',
                                     'bad screen distance "badValue"')

    def test_paneconfigure_sticky(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'sticky', 'nsew', 'nesw')
        self.check_paneconfigure_bad(p, b, 'sticky',
                                     'bad stickyness value "badValue": must '
                                     'be a string containing zero or more of '
                                     'n, e, s, and w')

    @requires_tcl(8, 5)
    def test_paneconfigure_stretch(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'stretch', 'alw', 'always')
        self.check_paneconfigure_bad(p, b, 'stretch',
                                     'bad stretch "badValue": must be '
                                     'always, first, last, middle, or never')

    def test_paneconfigure_width(self):
        p, b, c = self.create2()
        self.check_paneconfigure(p, b, 'width', 10, 10,
                                 stringify=get_tk_patchlevel() < (8, 5, 11))
        self.check_paneconfigure_bad(p, b, 'width',
                                     'bad screen distance "badValue"')


@add_standard_options(StandardOptionsTests)
class MenuTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'activebackground', 'activeborderwidth', 'activeforeground',
        'background', 'borderwidth', 'cursor',
        'disabledforeground', 'font', 'foreground',
        'postcommand', 'relief', 'selectcolor', 'takefocus',
        'tearoff', 'tearoffcommand', 'title', 'type',
    )
    _conv_pixels = noconv_meth

    def create(self, **kwargs):
        return tkinter.Menu(self.root, **kwargs)

    def test_postcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'postcommand')

    def test_tearoff(self):
        widget = self.create()
        self.checkBooleanParam(widget, 'tearoff')

    def test_tearoffcommand(self):
        widget = self.create()
        self.checkCommandParam(widget, 'tearoffcommand')

    def test_title(self):
        widget = self.create()
        self.checkParam(widget, 'title', 'any string')

    def test_type(self):
        widget = self.create()
        self.checkEnumParam(widget, 'type',
                'normal', 'tearoff', 'menubar')

    def test_entryconfigure(self):
        m1 = self.create()
        m1.add_command(label='test')
        self.assertRaises(TypeError, m1.entryconfigure)
        with self.assertRaisesRegexp(TclError, 'bad menu entry index "foo"'):
            m1.entryconfigure('foo')
        d = m1.entryconfigure(1)
        self.assertIsInstance(d, dict)
        for k, v in d.items():
            self.assertIsInstance(k, str)
            self.assertIsInstance(v, tuple)
            self.assertEqual(len(v), 5)
            self.assertEqual(v[0], k)
            self.assertEqual(m1.entrycget(1, k), v[4])
        m1.destroy()

    def test_entryconfigure_label(self):
        m1 = self.create()
        m1.add_command(label='test')
        self.assertEqual(m1.entrycget(1, 'label'), 'test')
        m1.entryconfigure(1, label='changed')
        self.assertEqual(m1.entrycget(1, 'label'), 'changed')

    def test_entryconfigure_variable(self):
        m1 = self.create()
        v1 = tkinter.BooleanVar(self.root)
        v2 = tkinter.BooleanVar(self.root)
        m1.add_checkbutton(variable=v1, onvalue=True, offvalue=False,
                           label='Nonsense')
        self.assertEqual(str(m1.entrycget(1, 'variable')), str(v1))
        m1.entryconfigure(1, variable=v2)
        self.assertEqual(str(m1.entrycget(1, 'variable')), str(v2))


@add_standard_options(PixelSizeTests, StandardOptionsTests)
class MessageTest(AbstractWidgetTest, unittest.TestCase):
    OPTIONS = (
        'anchor', 'aspect', 'background', 'borderwidth',
        'cursor', 'font', 'foreground',
        'highlightbackground', 'highlightcolor', 'highlightthickness',
        'justify', 'padx', 'pady', 'relief',
        'takefocus', 'text', 'textvariable', 'width',
    )
    _conv_pad_pixels = noconv_meth

    def create(self, **kwargs):
        return tkinter.Message(self.root, **kwargs)

    def test_aspect(self):
        widget = self.create()
        self.checkIntegerParam(widget, 'aspect', 250, 0, -300)


tests_gui = [
        ButtonTest, CanvasTest, CheckbuttonTest, EntryTest,
        FrameTest, LabelFrameTest,LabelTest, ListboxTest,
        MenubuttonTest, MenuTest, MessageTest, OptionMenuTest,
        PanedWindowTest, RadiobuttonTest, ScaleTest, ScrollbarTest,
        SpinboxTest, TextTest, ToplevelTest,
]

if __name__ == '__main__':
    run_unittest(*tests_gui)
PK(/�Ztest_tkinter/__init__.pynu�[���PK(/�Z0<477test_tkinter/test_text.pycnu�[����
zfc@s�ddlZddlZddlmZmZddlmZed�deejfd��YZ	e	fZ
edkr�ee
�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguitTextTestcBs#eZd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(tsuperRtsetUpttkintertTexttrootttext(tself((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyR
scCs�|j}|j�}zJ|jd�|j|j�d�|jd�|j|j�d�Wd|j|�|j|j�|�XdS(Nii(R
tdebugtassertEqual(RR
tolddebug((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyt
test_debugs	


cCs�|j}|jtj|jdd�|jtj|jdd�|jtj|jdd�|jtj|jdd�|jdd�|j|jddd�d�|j|jd	dd�d
�dS(Ns1.0tatishi-tests-testtends1.2ttests1.3(R
tassertRaisesRtTclErrortsearchtNonetinsertR
(RR
((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyttest_searchs	(t__name__t
__module__RRR(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyRs		t__main__(tunittesttTkinterRttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyt<module>s
$	PK(/�Z3��(4(4test_tkinter/test_images.pynu�[���import unittest
import Tkinter as tkinter
import ttk
import test.test_support as support
from test_ttk.support import AbstractTkTest, requires_tcl

support.requires('gui')


class MiscTest(AbstractTkTest, unittest.TestCase):

    def test_image_types(self):
        image_types = self.root.image_types()
        self.assertIsInstance(image_types, tuple)
        self.assertIn('photo', image_types)
        self.assertIn('bitmap', image_types)

    def test_image_names(self):
        image_names = self.root.image_names()
        self.assertIsInstance(image_names, tuple)


class BitmapImageTest(AbstractTkTest, unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        AbstractTkTest.setUpClass.__func__(cls)
        cls.testfile = support.findfile('python.xbm', subdir='imghdrdata')

    def test_create_from_file(self):
        image = tkinter.BitmapImage('::img::test', master=self.root,
                                    foreground='yellow', background='blue',
                                    file=self.testfile)
        self.assertEqual(str(image), '::img::test')
        self.assertEqual(image.type(), 'bitmap')
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)
        self.assertIn('::img::test', self.root.image_names())
        del image
        self.assertNotIn('::img::test', self.root.image_names())

    def test_create_from_data(self):
        with open(self.testfile, 'rb') as f:
            data = f.read()
        image = tkinter.BitmapImage('::img::test', master=self.root,
                                    foreground='yellow', background='blue',
                                    data=data)
        self.assertEqual(str(image), '::img::test')
        self.assertEqual(image.type(), 'bitmap')
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)
        self.assertIn('::img::test', self.root.image_names())
        del image
        self.assertNotIn('::img::test', self.root.image_names())

    def assertEqualStrList(self, actual, expected):
        self.assertIsInstance(actual, str)
        self.assertEqual(self.root.splitlist(actual), expected)

    def test_configure_data(self):
        image = tkinter.BitmapImage('::img::test', master=self.root)
        self.assertEqual(image['data'], '-data {} {} {} {}')
        with open(self.testfile, 'rb') as f:
            data = f.read()
        image.configure(data=data)
        self.assertEqualStrList(image['data'],
                                ('-data', '', '', '', data))
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)

        self.assertEqual(image['maskdata'], '-maskdata {} {} {} {}')
        image.configure(maskdata=data)
        self.assertEqualStrList(image['maskdata'],
                                ('-maskdata', '', '', '', data))

    def test_configure_file(self):
        image = tkinter.BitmapImage('::img::test', master=self.root)
        self.assertEqual(image['file'], '-file {} {} {} {}')
        image.configure(file=self.testfile)
        self.assertEqualStrList(image['file'],
                                ('-file', '', '', '',self.testfile))
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)

        self.assertEqual(image['maskfile'], '-maskfile {} {} {} {}')
        image.configure(maskfile=self.testfile)
        self.assertEqualStrList(image['maskfile'],
                                ('-maskfile', '', '', '', self.testfile))

    def test_configure_background(self):
        image = tkinter.BitmapImage('::img::test', master=self.root)
        self.assertEqual(image['background'], '-background {} {} {} {}')
        image.configure(background='blue')
        self.assertEqual(image['background'], '-background {} {} {} blue')

    def test_configure_foreground(self):
        image = tkinter.BitmapImage('::img::test', master=self.root)
        self.assertEqual(image['foreground'],
                         '-foreground {} {} #000000 #000000')
        image.configure(foreground='yellow')
        self.assertEqual(image['foreground'],
                         '-foreground {} {} #000000 yellow')


class PhotoImageTest(AbstractTkTest, unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        AbstractTkTest.setUpClass.__func__(cls)
        cls.testfile = support.findfile('python.gif', subdir='imghdrdata')

    def create(self):
        return tkinter.PhotoImage('::img::test', master=self.root,
                                  file=self.testfile)

    def colorlist(self, *args):
        if tkinter.TkVersion >= 8.6 and self.wantobjects:
            return args
        else:
            return tkinter._join(args)

    def check_create_from_file(self, ext):
        testfile = support.findfile('python.' + ext, subdir='imghdrdata')
        image = tkinter.PhotoImage('::img::test', master=self.root,
                                   file=testfile)
        self.assertEqual(str(image), '::img::test')
        self.assertEqual(image.type(), 'photo')
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)
        self.assertEqual(image['data'], '')
        self.assertEqual(image['file'], testfile)
        self.assertIn('::img::test', self.root.image_names())
        del image
        self.assertNotIn('::img::test', self.root.image_names())

    def check_create_from_data(self, ext):
        testfile = support.findfile('python.' + ext, subdir='imghdrdata')
        with open(testfile, 'rb') as f:
            data = f.read()
        image = tkinter.PhotoImage('::img::test', master=self.root,
                                   data=data)
        self.assertEqual(str(image), '::img::test')
        self.assertEqual(image.type(), 'photo')
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)
        self.assertEqual(image['data'], data if self.wantobjects
                                        else data.decode('latin1'))
        self.assertEqual(image['file'], '')
        self.assertIn('::img::test', self.root.image_names())
        del image
        self.assertNotIn('::img::test', self.root.image_names())

    def test_create_from_ppm_file(self):
        self.check_create_from_file('ppm')

    def test_create_from_ppm_data(self):
        self.check_create_from_data('ppm')

    def test_create_from_pgm_file(self):
        self.check_create_from_file('pgm')

    def test_create_from_pgm_data(self):
        self.check_create_from_data('pgm')

    def test_create_from_gif_file(self):
        self.check_create_from_file('gif')

    def test_create_from_gif_data(self):
        self.check_create_from_data('gif')

    @requires_tcl(8, 6)
    def test_create_from_png_file(self):
        self.check_create_from_file('png')

    @requires_tcl(8, 6)
    def test_create_from_png_data(self):
        self.check_create_from_data('png')

    def test_configure_data(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['data'], '')
        with open(self.testfile, 'rb') as f:
            data = f.read()
        image.configure(data=data)
        self.assertEqual(image['data'], data if self.wantobjects
                                        else data.decode('latin1'))
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)

    def test_configure_format(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['format'], '')
        image.configure(file=self.testfile, format='gif')
        self.assertEqual(image['format'], ('gif',) if self.wantobjects
                                          else 'gif')
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)

    def test_configure_file(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['file'], '')
        image.configure(file=self.testfile)
        self.assertEqual(image['file'], self.testfile)
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)

    def test_configure_gamma(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['gamma'], '1.0')
        image.configure(gamma=2.0)
        self.assertEqual(image['gamma'], '2.0')

    def test_configure_width_height(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['width'], '0')
        self.assertEqual(image['height'], '0')
        image.configure(width=20)
        image.configure(height=10)
        self.assertEqual(image['width'], '20')
        self.assertEqual(image['height'], '10')
        self.assertEqual(image.width(), 20)
        self.assertEqual(image.height(), 10)

    def test_configure_palette(self):
        image = tkinter.PhotoImage('::img::test', master=self.root)
        self.assertEqual(image['palette'], '')
        image.configure(palette=256)
        self.assertEqual(image['palette'], '256')
        image.configure(palette='3/4/2')
        self.assertEqual(image['palette'], '3/4/2')

    def test_blank(self):
        image = self.create()
        image.blank()
        self.assertEqual(image.width(), 16)
        self.assertEqual(image.height(), 16)
        self.assertEqual(image.get(4, 6), self.colorlist(0, 0, 0))

    def test_copy(self):
        image = self.create()
        image2 = image.copy()
        self.assertEqual(image2.width(), 16)
        self.assertEqual(image2.height(), 16)
        self.assertEqual(image.get(4, 6), image.get(4, 6))

    def test_subsample(self):
        image = self.create()
        image2 = image.subsample(2, 3)
        self.assertEqual(image2.width(), 8)
        self.assertEqual(image2.height(), 6)
        self.assertEqual(image2.get(2, 2), image.get(4, 6))

        image2 = image.subsample(2)
        self.assertEqual(image2.width(), 8)
        self.assertEqual(image2.height(), 8)
        self.assertEqual(image2.get(2, 3), image.get(4, 6))

    def test_zoom(self):
        image = self.create()
        image2 = image.zoom(2, 3)
        self.assertEqual(image2.width(), 32)
        self.assertEqual(image2.height(), 48)
        self.assertEqual(image2.get(8, 18), image.get(4, 6))
        self.assertEqual(image2.get(9, 20), image.get(4, 6))

        image2 = image.zoom(2)
        self.assertEqual(image2.width(), 32)
        self.assertEqual(image2.height(), 32)
        self.assertEqual(image2.get(8, 12), image.get(4, 6))
        self.assertEqual(image2.get(9, 13), image.get(4, 6))

    def test_put(self):
        image = self.create()
        image.put('{red green} {blue yellow}', to=(4, 6))
        self.assertEqual(image.get(4, 6), self.colorlist(255, 0, 0))
        self.assertEqual(image.get(5, 6),
                         self.colorlist(0, 128 if tkinter.TkVersion >= 8.6
                                           else 255, 0))
        self.assertEqual(image.get(4, 7), self.colorlist(0, 0, 255))
        self.assertEqual(image.get(5, 7), self.colorlist(255, 255, 0))

        image.put((('#f00', '#00ff00'), ('#000000fff', '#ffffffff0000')))
        self.assertEqual(image.get(0, 0), self.colorlist(255, 0, 0))
        self.assertEqual(image.get(1, 0), self.colorlist(0, 255, 0))
        self.assertEqual(image.get(0, 1), self.colorlist(0, 0, 255))
        self.assertEqual(image.get(1, 1), self.colorlist(255, 255, 0))

    def test_get(self):
        image = self.create()
        self.assertEqual(image.get(4, 6), self.colorlist(62, 116, 162))
        self.assertEqual(image.get(0, 0), self.colorlist(0, 0, 0))
        self.assertEqual(image.get(15, 15), self.colorlist(0, 0, 0))
        self.assertRaises(tkinter.TclError, image.get, -1, 0)
        self.assertRaises(tkinter.TclError, image.get, 0, -1)
        self.assertRaises(tkinter.TclError, image.get, 16, 15)
        self.assertRaises(tkinter.TclError, image.get, 15, 16)

    def test_write(self):
        image = self.create()
        self.addCleanup(support.unlink, support.TESTFN)

        image.write(support.TESTFN)
        image2 = tkinter.PhotoImage('::img::test2', master=self.root,
                                    format='ppm',
                                    file=support.TESTFN)
        self.assertEqual(str(image2), '::img::test2')
        self.assertEqual(image2.type(), 'photo')
        self.assertEqual(image2.width(), 16)
        self.assertEqual(image2.height(), 16)
        self.assertEqual(image2.get(0, 0), image.get(0, 0))
        self.assertEqual(image2.get(15, 8), image.get(15, 8))

        image.write(support.TESTFN, format='gif', from_coords=(4, 6, 6, 9))
        image3 = tkinter.PhotoImage('::img::test3', master=self.root,
                                    format='gif',
                                    file=support.TESTFN)
        self.assertEqual(str(image3), '::img::test3')
        self.assertEqual(image3.type(), 'photo')
        self.assertEqual(image3.width(), 2)
        self.assertEqual(image3.height(), 3)
        self.assertEqual(image3.get(0, 0), image.get(4, 6))
        self.assertEqual(image3.get(1, 2), image.get(5, 8))


tests_gui = (MiscTest, BitmapImageTest, PhotoImageTest,)

if __name__ == "__main__":
    support.run_unittest(*tests_gui)
PK(/�ZT�D���test_tkinter/__init__.pyonu�[����
zfc@sdS(N((((s9/usr/lib64/python2.7/lib-tk/test/test_tkinter/__init__.pyt<module>tPK(/�Z=���,�,test_tkinter/test_variables.pyonu�[����
zfc@sddlZddlZddlmZmZmZmZmZmZm	Z	dej
fd��YZdefd��YZdefd��YZ
d	efd
��YZdefd��YZd
efd��YZee
eeefZedkrddlmZee�ndS(i����N(tVariablet	StringVartIntVart	DoubleVart
BooleanVartTcltTclErrortTestBasecBseZd�Zd�ZRS(cCst�|_dS(N(Rtroot(tself((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytsetUp	scCs
|`dS(N(R(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttearDowns(t__name__t
__module__R
R(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRs	tTestVariablecBsYeZd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
RS(	cGs"|jj|jjdd|��S(Ntinfotexists(Rt
getbooleantcall(R	targs((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytinfo_existsscCs?t|j�}|jd|j��|jt|�d�dS(Nts
^PY_VAR(\d+)$(RRtassertEqualtgettassertRegexpMatcheststr(R	tv((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_defaultscCsEt|jdd�}|jd|j��|jdt|��dS(Ns
sample stringtvarname(RRRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_name_and_valuescCs^|j|jd��t|jdd�}|j|jd��~|j|jd��dS(NRs
sample string(tassertFalseRRRt
assertTrue(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest___del__s
cCsv|j|jd��t|jdd�}t|jdd�}~|j|jd��~|j|jd��dS(NRtname(RRRR(R	tv1tv2((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_dont_unset_not_existing&scCsxt|jdd�}t|jdd�}|j||�t|jdd�}t|jdd�}|j||�dS(NR!tabc(RRRRtassertNotEqual(R	R"R#tv3tv4((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest___eq__0scCs-|jt��t|jdd�WdQXdS(NR!i{(tassertRaisest	TypeErrorRR(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_name:sc	Cs|jt��t|jdd�WdQX|jt��|jjdd�WdQX|jt��|jjdd�WdQXdS(NR!svarnametvalue(R*t
ValueErrorRRtglobalsetvartsetvar(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_null_in_name>scsot|j�}t|�}g��fd�}�fd�}|jd|�}|jd|�}|jt|j��d|fd|fg�|j�g�|jd�|j�d|ddfg�g�|j�|j�d	|ddfg�g�t|j��}|j	d|�|jt|j��|�|j
t��|j	dd�WdQX|jt|j��|�|j	d|d
f�|jt|j��|�|j�|j�d	|ddfg�g�|j	d|�|j|j�d|fg�|j�|j�g�g�~tj
�|jd�|j�d|ddfg�dS(Ncs�jd|�dS(Ntread(R2(tappend(R(ttrace(s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytread_tracerJscs�jd|�dS(Ntwrite(R6(R3(R(R4(s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytwrite_tracerLstrtwutspamR6RtwR2i+teggs(RRRttrace_variableRtsortedttrace_vinfotsetRt
trace_vdeleteR*Rtgctcollect(R	RtvnameR5R7tcb1tcb2R((R4s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt
test_traceFsF.





(RR
RRRR R$R)R,R1RG(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRs					
	
		t
TestStringVarcBs#eZd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(NR(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRzscCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(NR%R!R-(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_get~scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(NsabcdefR!svalue(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt
test_get_null�s(RR
RRIRJ(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRHxs		t
TestIntVarcBs#eZd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(Ni(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(Ni{R!t345iY(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�scCst|jdd�}|jjdd�|jt��|j�WdQX|jjdd�|jt��|j�WdQXdS(NR!R-s345.0(RRR/R*R.R(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_value�s(RR
RRIRM(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRK�s		t
TestDoubleVarcBs,eZd�Zd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(Ng(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(Ng�G�z��?R!s3.45g������@(RRtassertAlmostEqualRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�scCs�t|jdd�}|jd|j��|jjdd�|jd|j��|jjdd�|jd|j��dS(Ng�G�z��?R!s3.45g������@t456i�(RRRORR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_get_from_int�scCsLt|jdd�}|jjdd�|jt��|j�WdQXdS(NR!R-(RRR/R*R.R(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRM�s(RR
RRIRQRM(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRN�s			tTestBooleanVarcBs,eZd�Zd�Zd�Zd�ZRS(cCs)t|j�}|j|j�t�dS(N(RRtassertIsRtFalse(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCs�t|jtd�}|j|j�t�|jjdd�|j|j�t�|jjd|jj�rudnd�|j|j�t�|jjdd�|j|j�t�|jjd|jj�r�dnd�|j|j�t�|jjdd�|j|j�t�|jjdd	�|j|j�t�|jjdd
�|j|j�t�|jjdd�|j|j�t�dS(NR!t0i*iil*lltonu0uon(RRtTrueRSRR/RTtwantobjects(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�s$((cCs�|jj�rdnd}|jj�r0dnd}t|jdd�}|jt�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd	�|j|jjd�|�|jd
�|j|jjd�|�|jd�|j|jjd�|�dS(Nit1iRUR!i*l*lRVu0uon(RRXRR@RWRtglobalgetvar(R	ttruetfalseR((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_set�s*








cCs�|jj�rdnd}t|jdd�}|jt��|jd�WdQX|j|jjd�|�|jjdd�|jt��|j	�WdQX|jjdd�|jt��|j	�WdQXdS(NiRUR!R-s1.0(
RRXRR*RR@RRZR/R(R	R\R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_value_domain�s(RR
RRIR]R^(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRR�s			t__main__(trun_unittest(tunittestRBtTkinterRRRRRRRtTestCaseRRRHRKRNRRt	tests_guiRttest.supportR`(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt<module>s4	h?	PK(/�ZV�I��test_tkinter/test_font.pyonu�[����
zfc@s�ddlZddlZddlZddlmZmZmZddl	m
Z
ed�dZde
ejfd��YZ
e
fZedkr�ee�ndS(	i����N(trequirestrun_unittestt
gc_collect(tAbstractTkTesttguit
TkDefaultFonttFontTestcBsheZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd	�ZRS(
cCswtjj|�y(tjd|jdtdt�|_Wn8tj	k
rrtjd|jdtdt
�|_nXdS(Ntroottnametexists(Rt
setUpClasst__func__tfonttFontRtfontnametTruettkintertTclErrortFalse(tcls((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyR

s
(cCsL|jj�}|jt|�ddddddh�xI|D]A}|j|jj|�||�|j|j|||�q>WxUdD]M}|j||t�|j|jj|�t�|j|j|t�q�W|jr�t	nt}xUdD]M}|j|||�|j|jj|�|�|j|j||�q�WdS(	Ntfamilytsizetweighttslantt	underlinet
overstrike(RRR(RRR(
Rt	configuretassertGreaterEqualtsettassertEqualtcgettassertIsInstancetstrtwantobjectstint(tselftoptionstkeytsizetype((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_configures
 

cCs�d}y%tjd|jd|dt�}Wn5tjk
rbtjd|jd|dt�}nX|j|jd�|�~t	�dS(NuMS ゴシックRRR	(
RR
RRRRRRRR(R#Rtf((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_unicode_family&s%%cCs|jj�}|jt|�ddddddh�x.|D]&}|j|jj|�||�q>Wx>dD]6}|j||t�|j|jj|�t�qoW|jr�tnt}x>dD]6}|j|||�|j|jj|�|�q�WdS(	NRRRRRR(RRR(RRR(	RtactualRRRRR R!R"(R#R$R%R&((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_actual0s
$
 
cCs3|j|jjt�|jt|j�t�dS(N(RRRRR (R#((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt	test_name>scCs�tjd|jdtdt�}tjd|jdtdt�}|j||�|j||�|j||j��|j|d�|j	|dg�dS(NRRR	i(
RR
RRRtassertIsNotRtassertNotEqualtcopytassertNotIn(R#tfont1tfont2((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_eqBs!!cCs |j|jjd�t�dS(Ntabc(RRtmeasureR"(R#((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_measureKscCs�|jj�}|jt|�ddddh�x^|D]V}|j|jj|�||�|j||t�|j|jj|�t�q8WdS(Ntascenttdescentt	linespacetfixed(RtmetricsRRRRR"(R#R;R%((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_metricsNs
 cCsgtj|j�}|j|t�|j|�x1|D])}|j|ttf�|j|�q6WdS(N(RtfamiliesRRttuplet
assertTrueR tunicode(R#R=R((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt
test_familiesWs

cCswtj|j�}|j|t�|j|�x1|D])}|j|ttf�|j|�q6W|jt	|�dS(N(
RtnamesRRR>R?R R@tassertInR(R#RBR((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt
test_names_s

(
t__name__t
__module__tclassmethodR
R'R)R+R,R3R6R<RARD(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyRs		
								t__main__(tunittesttTkinterRttkFontRttest.test_supportRRRttest_ttk.supportRRtTestCaseRt	tests_guiRE(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt<module>s
]	PK(/�ZV�I��test_tkinter/test_font.pycnu�[����
zfc@s�ddlZddlZddlZddlmZmZmZddl	m
Z
ed�dZde
ejfd��YZ
e
fZedkr�ee�ndS(	i����N(trequirestrun_unittestt
gc_collect(tAbstractTkTesttguit
TkDefaultFonttFontTestcBsheZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd	�ZRS(
cCswtjj|�y(tjd|jdtdt�|_Wn8tj	k
rrtjd|jdtdt
�|_nXdS(Ntroottnametexists(Rt
setUpClasst__func__tfonttFontRtfontnametTruettkintertTclErrortFalse(tcls((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyR

s
(cCsL|jj�}|jt|�ddddddh�xI|D]A}|j|jj|�||�|j|j|||�q>WxUdD]M}|j||t�|j|jj|�t�|j|j|t�q�W|jr�t	nt}xUdD]M}|j|||�|j|jj|�|�|j|j||�q�WdS(	Ntfamilytsizetweighttslantt	underlinet
overstrike(RRR(RRR(
Rt	configuretassertGreaterEqualtsettassertEqualtcgettassertIsInstancetstrtwantobjectstint(tselftoptionstkeytsizetype((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_configures
 

cCs�d}y%tjd|jd|dt�}Wn5tjk
rbtjd|jd|dt�}nX|j|jd�|�~t	�dS(NuMS ゴシックRRR	(
RR
RRRRRRRR(R#Rtf((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_unicode_family&s%%cCs|jj�}|jt|�ddddddh�x.|D]&}|j|jj|�||�q>Wx>dD]6}|j||t�|j|jj|�t�qoW|jr�tnt}x>dD]6}|j|||�|j|jj|�|�q�WdS(	NRRRRRR(RRR(RRR(	RtactualRRRRR R!R"(R#R$R%R&((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_actual0s
$
 
cCs3|j|jjt�|jt|j�t�dS(N(RRRRR (R#((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt	test_name>scCs�tjd|jdtdt�}tjd|jdtdt�}|j||�|j||�|j||j��|j|d�|j	|dg�dS(NRRR	i(
RR
RRRtassertIsNotRtassertNotEqualtcopytassertNotIn(R#tfont1tfont2((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_eqBs!!cCs |j|jjd�t�dS(Ntabc(RRtmeasureR"(R#((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_measureKscCs�|jj�}|jt|�ddddh�x^|D]V}|j|jj|�||�|j||t�|j|jj|�t�q8WdS(Ntascenttdescentt	linespacetfixed(RtmetricsRRRRR"(R#R;R%((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyttest_metricsNs
 cCsgtj|j�}|j|t�|j|�x1|D])}|j|ttf�|j|�q6WdS(N(RtfamiliesRRttuplet
assertTrueR tunicode(R#R=R((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt
test_familiesWs

cCswtj|j�}|j|t�|j|�x1|D])}|j|ttf�|j|�q6W|jt	|�dS(N(
RtnamesRRR>R?R R@tassertInR(R#RBR((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt
test_names_s

(
t__name__t
__module__tclassmethodR
R'R)R+R,R3R6R<RARD(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyRs		
								t__main__(tunittesttTkinterRttkFontRttest.test_supportRRRttest_ttk.supportRRtTestCaseRt	tests_guiRE(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_font.pyt<module>s
]	PK(/�Z!=�޼�test_tkinter/test_text.pynu�[���import unittest
import Tkinter as tkinter
from test.test_support import requires, run_unittest
from test_ttk.support import AbstractTkTest

requires('gui')

class TextTest(AbstractTkTest, unittest.TestCase):

    def setUp(self):
        super(TextTest, self).setUp()
        self.text = tkinter.Text(self.root)

    def test_debug(self):
        text = self.text
        olddebug = text.debug()
        try:
            text.debug(0)
            self.assertEqual(text.debug(), 0)
            text.debug(1)
            self.assertEqual(text.debug(), 1)
        finally:
            text.debug(olddebug)
            self.assertEqual(text.debug(), olddebug)

    def test_search(self):
        text = self.text

        # pattern and index are obligatory arguments.
        self.assertRaises(tkinter.TclError, text.search, None, '1.0')
        self.assertRaises(tkinter.TclError, text.search, 'a', None)
        self.assertRaises(tkinter.TclError, text.search, None, None)

        # Invalid text index.
        self.assertRaises(tkinter.TclError, text.search, '', 0)

        # Check if we are getting the indices as strings -- you are likely
        # to get Tcl_Obj under Tk 8.5 if Tkinter doesn't convert it.
        text.insert('1.0', 'hi-test')
        self.assertEqual(text.search('-test', '1.0', 'end'), '1.2')
        self.assertEqual(text.search('test', '1.0', 'end'), '1.3')


tests_gui = (TextTest, )

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK(/�Z=���,�,test_tkinter/test_variables.pycnu�[����
zfc@sddlZddlZddlmZmZmZmZmZmZm	Z	dej
fd��YZdefd��YZdefd��YZ
d	efd
��YZdefd��YZd
efd��YZee
eeefZedkrddlmZee�ndS(i����N(tVariablet	StringVartIntVart	DoubleVart
BooleanVartTcltTclErrortTestBasecBseZd�Zd�ZRS(cCst�|_dS(N(Rtroot(tself((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytsetUp	scCs
|`dS(N(R(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttearDowns(t__name__t
__module__R
R(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRs	tTestVariablecBsYeZd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
RS(	cGs"|jj|jjdd|��S(Ntinfotexists(Rt
getbooleantcall(R	targs((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytinfo_existsscCs?t|j�}|jd|j��|jt|�d�dS(Nts
^PY_VAR(\d+)$(RRtassertEqualtgettassertRegexpMatcheststr(R	tv((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_defaultscCsEt|jdd�}|jd|j��|jdt|��dS(Ns
sample stringtvarname(RRRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_name_and_valuescCs^|j|jd��t|jdd�}|j|jd��~|j|jd��dS(NRs
sample string(tassertFalseRRRt
assertTrue(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest___del__s
cCsv|j|jd��t|jdd�}t|jdd�}~|j|jd��~|j|jd��dS(NRtname(RRRR(R	tv1tv2((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_dont_unset_not_existing&scCsxt|jdd�}t|jdd�}|j||�t|jdd�}t|jdd�}|j||�dS(NR!tabc(RRRRtassertNotEqual(R	R"R#tv3tv4((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest___eq__0scCs-|jt��t|jdd�WdQXdS(NR!i{(tassertRaisest	TypeErrorRR(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_name:sc	Cs|jt��t|jdd�WdQX|jt��|jjdd�WdQX|jt��|jjdd�WdQXdS(NR!svarnametvalue(R*t
ValueErrorRRtglobalsetvartsetvar(R	((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_null_in_name>scsot|j�}t|�}g��fd�}�fd�}|jd|�}|jd|�}|jt|j��d|fd|fg�|j�g�|jd�|j�d|ddfg�g�|j�|j�d	|ddfg�g�t|j��}|j	d|�|jt|j��|�|j
t��|j	dd�WdQX|jt|j��|�|j	d|d
f�|jt|j��|�|j�|j�d	|ddfg�g�|j	d|�|j|j�d|fg�|j�|j�g�g�~tj
�|jd�|j�d|ddfg�dS(Ncs�jd|�dS(Ntread(R2(tappend(R(ttrace(s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytread_tracerJscs�jd|�dS(Ntwrite(R6(R3(R(R4(s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pytwrite_tracerLstrtwutspamR6RtwR2i+teggs(RRRttrace_variableRtsortedttrace_vinfotsetRt
trace_vdeleteR*Rtgctcollect(R	RtvnameR5R7tcb1tcb2R((R4s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt
test_traceFsF.





(RR
RRRR R$R)R,R1RG(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRs					
	
		t
TestStringVarcBs#eZd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(NR(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRzscCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(NR%R!R-(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_get~scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(NsabcdefR!svalue(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt
test_get_null�s(RR
RRIRJ(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRHxs		t
TestIntVarcBs#eZd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(Ni(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(Ni{R!t345iY(RRRRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�scCst|jdd�}|jjdd�|jt��|j�WdQX|jjdd�|jt��|j�WdQXdS(NR!R-s345.0(RRR/R*R.R(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_value�s(RR
RRIRM(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRK�s		t
TestDoubleVarcBs,eZd�Zd�Zd�Zd�ZRS(cCs)t|j�}|jd|j��dS(Ng(RRRR(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCsXt|jdd�}|jd|j��|jjdd�|jd|j��dS(Ng�G�z��?R!s3.45g������@(RRtassertAlmostEqualRR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�scCs�t|jdd�}|jd|j��|jjdd�|jd|j��|jjdd�|jd|j��dS(Ng�G�z��?R!s3.45g������@t456i�(RRRORR/(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_get_from_int�scCsLt|jdd�}|jjdd�|jt��|j�WdQXdS(NR!R-(RRR/R*R.R(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRM�s(RR
RRIRQRM(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRN�s			tTestBooleanVarcBs,eZd�Zd�Zd�Zd�ZRS(cCs)t|j�}|j|j�t�dS(N(RRtassertIsRtFalse(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyR�scCs�t|jtd�}|j|j�t�|jjdd�|j|j�t�|jjd|jj�rudnd�|j|j�t�|jjdd�|j|j�t�|jjd|jj�r�dnd�|j|j�t�|jjdd�|j|j�t�|jjdd	�|j|j�t�|jjdd
�|j|j�t�|jjdd�|j|j�t�dS(NR!t0i*iil*lltonu0uon(RRtTrueRSRR/RTtwantobjects(R	R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRI�s$((cCs�|jj�rdnd}|jj�r0dnd}t|jdd�}|jt�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd�|j|jjd�|�|jd	�|j|jjd�|�|jd
�|j|jjd�|�|jd�|j|jjd�|�dS(Nit1iRUR!i*l*lRVu0uon(RRXRR@RWRtglobalgetvar(R	ttruetfalseR((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_set�s*








cCs�|jj�rdnd}t|jdd�}|jt��|jd�WdQX|j|jjd�|�|jjdd�|jt��|j	�WdQX|jjdd�|jt��|j	�WdQXdS(NiRUR!R-s1.0(
RRXRR*RR@RRZR/R(R	R\R((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyttest_invalid_value_domain�s(RR
RRIR]R^(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyRR�s			t__main__(trun_unittest(tunittestRBtTkinterRRRRRRRtTestCaseRRRHRKRNRRt	tests_guiRttest.supportR`(((s?/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_variables.pyt<module>s4	h?	PK(/�Z�K�w�w�&test_tkinter/test_geometry_managers.pynu�[���import unittest
import re
import Tkinter as tkinter
from Tkinter import TclError
from test.test_support import requires, run_unittest

from test_ttk.support import pixels_conv, tcl_version, requires_tcl
from widget_tests import AbstractWidgetTest, int_round

requires('gui')


class PackTest(AbstractWidgetTest, unittest.TestCase):

    test_keys = None

    def create2(self):
        pack = tkinter.Toplevel(self.root, name='pack')
        pack.wm_geometry('300x200+0+0')
        pack.wm_minsize(1, 1)
        a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red')
        b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue')
        c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green')
        d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow')
        return pack, a, b, c, d

    def test_pack_configure_after(self):
        pack, a, b, c, d = self.create2()
        with self.assertRaisesRegexp(TclError, 'window "%s" isn\'t packed' % b):
            a.pack_configure(after=b)
        with self.assertRaisesRegexp(TclError, 'bad window path name ".foo"'):
            a.pack_configure(after='.foo')
        a.pack_configure(side='top')
        b.pack_configure(side='top')
        c.pack_configure(side='top')
        d.pack_configure(side='top')
        self.assertEqual(pack.pack_slaves(), [a, b, c, d])
        a.pack_configure(after=b)
        self.assertEqual(pack.pack_slaves(), [b, a, c, d])
        a.pack_configure(after=a)
        self.assertEqual(pack.pack_slaves(), [b, a, c, d])

    def test_pack_configure_anchor(self):
        pack, a, b, c, d = self.create2()
        def check(anchor, geom):
            a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20,
                             expand=True, anchor=anchor)
            self.root.update()
            self.assertEqual(a.winfo_geometry(), geom)
        check('n', '30x70+135+20')
        check('ne', '30x70+260+20')
        check('e', '30x70+260+65')
        check('se', '30x70+260+110')
        check('s', '30x70+135+110')
        check('sw', '30x70+10+110')
        check('w', '30x70+10+65')
        check('nw', '30x70+10+20')
        check('center', '30x70+135+65')

    def test_pack_configure_before(self):
        pack, a, b, c, d = self.create2()
        with self.assertRaisesRegexp(TclError, 'window "%s" isn\'t packed' % b):
            a.pack_configure(before=b)
        with self.assertRaisesRegexp(TclError, 'bad window path name ".foo"'):
            a.pack_configure(before='.foo')
        a.pack_configure(side='top')
        b.pack_configure(side='top')
        c.pack_configure(side='top')
        d.pack_configure(side='top')
        self.assertEqual(pack.pack_slaves(), [a, b, c, d])
        a.pack_configure(before=d)
        self.assertEqual(pack.pack_slaves(), [b, c, a, d])
        a.pack_configure(before=a)
        self.assertEqual(pack.pack_slaves(), [b, c, a, d])

    def test_pack_configure_expand(self):
        pack, a, b, c, d = self.create2()
        def check(*geoms):
            self.root.update()
            self.assertEqual(a.winfo_geometry(), geoms[0])
            self.assertEqual(b.winfo_geometry(), geoms[1])
            self.assertEqual(c.winfo_geometry(), geoms[2])
            self.assertEqual(d.winfo_geometry(), geoms[3])
        a.pack_configure(side='left')
        b.pack_configure(side='top')
        c.pack_configure(side='right')
        d.pack_configure(side='bottom')
        check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170')
        a.pack_configure(side='left', expand='yes')
        b.pack_configure(side='top', expand='on')
        c.pack_configure(side='right', expand=True)
        d.pack_configure(side='bottom', expand=1)
        check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135')
        a.pack_configure(side='left', expand='yes', fill='both')
        b.pack_configure(side='top', expand='on', fill='both')
        c.pack_configure(side='right', expand=True, fill='both')
        d.pack_configure(side='bottom', expand=1, fill='both')
        check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100')

    def test_pack_configure_in(self):
        pack, a, b, c, d = self.create2()
        a.pack_configure(side='top')
        b.pack_configure(side='top')
        c.pack_configure(side='top')
        d.pack_configure(side='top')
        a.pack_configure(in_=pack)
        self.assertEqual(pack.pack_slaves(), [b, c, d, a])
        a.pack_configure(in_=c)
        self.assertEqual(pack.pack_slaves(), [b, c, d])
        self.assertEqual(c.pack_slaves(), [a])
        with self.assertRaisesRegexp(TclError,
                                     'can\'t pack %s inside itself' % (a,)):
            a.pack_configure(in_=a)
        with self.assertRaisesRegexp(TclError, 'bad window path name ".foo"'):
            a.pack_configure(in_='.foo')

    def test_pack_configure_padx_ipadx_fill(self):
        pack, a, b, c, d = self.create2()
        def check(geom1, geom2, **kwargs):
            a.pack_forget()
            b.pack_forget()
            a.pack_configure(**kwargs)
            b.pack_configure(expand=True, fill='both')
            self.root.update()
            self.assertEqual(a.winfo_geometry(), geom1)
            self.assertEqual(b.winfo_geometry(), geom2)
        check('20x40+260+80', '240x200+0+0', side='right', padx=20)
        check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30))
        check('60x40+240+80', '240x200+0+0', side='right', ipadx=20)
        check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10)
        check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x')
        check('20x40+249+80', '240x200+0+0',
              side='right', padx=(9, 31), fill='x')
        check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x')
        check('30x40+260+80', '250x200+0+0',
              side='right', ipadx=5, padx=10, fill='x')
        check('30x40+255+80', '250x200+0+0',
              side='right', ipadx=5, padx=(5, 15), fill='x')
        check('20x40+140+0', '300x160+0+40', side='top', padx=20)
        check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40))
        check('60x40+120+0', '300x160+0+40', side='top', ipadx=20)
        check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10)
        check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15))
        check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x')
        check('260x40+25+0', '300x160+0+40',
              side='top', padx=(25, 15), fill='x')
        check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x')
        check('280x40+10+0', '300x160+0+40',
              side='top', ipadx=5, padx=10, fill='x')
        check('280x40+5+0', '300x160+0+40',
              side='top', ipadx=5, padx=(5, 15), fill='x')
        a.pack_configure(padx='1c')
        self.assertEqual(a.pack_info()['padx'],
                         self._str(pack.winfo_pixels('1c')))
        a.pack_configure(ipadx='1c')
        self.assertEqual(a.pack_info()['ipadx'],
                         self._str(pack.winfo_pixels('1c')))

    def test_pack_configure_pady_ipady_fill(self):
        pack, a, b, c, d = self.create2()
        def check(geom1, geom2, **kwargs):
            a.pack_forget()
            b.pack_forget()
            a.pack_configure(**kwargs)
            b.pack_configure(expand=True, fill='both')
            self.root.update()
            self.assertEqual(a.winfo_geometry(), geom1)
            self.assertEqual(b.winfo_geometry(), geom2)
        check('20x40+280+80', '280x200+0+0', side='right', pady=20)
        check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30))
        check('20x80+280+60', '280x200+0+0', side='right', ipady=20)
        check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10)
        check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x')
        check('20x40+280+69', '280x200+0+0',
              side='right', pady=(9, 31), fill='x')
        check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x')
        check('20x50+280+75', '280x200+0+0',
              side='right', ipady=5, pady=10, fill='x')
        check('20x50+280+70', '280x200+0+0',
              side='right', ipady=5, pady=(5, 15), fill='x')
        check('20x40+140+20', '300x120+0+80', side='top', pady=20)
        check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40))
        check('20x80+140+0', '300x120+0+80', side='top', ipady=20)
        check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10)
        check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15))
        check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x')
        check('300x40+0+25', '300x120+0+80',
              side='top', pady=(25, 15), fill='x')
        check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x')
        check('300x50+0+10', '300x130+0+70',
              side='top', ipady=5, pady=10, fill='x')
        check('300x50+0+5', '300x130+0+70',
              side='top', ipady=5, pady=(5, 15), fill='x')
        a.pack_configure(pady='1c')
        self.assertEqual(a.pack_info()['pady'],
                         self._str(pack.winfo_pixels('1c')))
        a.pack_configure(ipady='1c')
        self.assertEqual(a.pack_info()['ipady'],
                         self._str(pack.winfo_pixels('1c')))

    def test_pack_configure_side(self):
        pack, a, b, c, d = self.create2()
        def check(side, geom1, geom2):
            a.pack_configure(side=side)
            self.assertEqual(a.pack_info()['side'], side)
            b.pack_configure(expand=True, fill='both')
            self.root.update()
            self.assertEqual(a.winfo_geometry(), geom1)
            self.assertEqual(b.winfo_geometry(), geom2)
        check('top', '20x40+140+0', '300x160+0+40')
        check('bottom', '20x40+140+160', '300x160+0+0')
        check('left', '20x40+0+80', '280x200+20+0')
        check('right', '20x40+280+80', '280x200+0+0')

    def test_pack_forget(self):
        pack, a, b, c, d = self.create2()
        a.pack_configure()
        b.pack_configure()
        c.pack_configure()
        self.assertEqual(pack.pack_slaves(), [a, b, c])
        b.pack_forget()
        self.assertEqual(pack.pack_slaves(), [a, c])
        b.pack_forget()
        self.assertEqual(pack.pack_slaves(), [a, c])
        d.pack_forget()

    def test_pack_info(self):
        pack, a, b, c, d = self.create2()
        with self.assertRaisesRegexp(TclError, 'window "%s" isn\'t packed' % a):
            a.pack_info()
        a.pack_configure()
        b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x',
                         ipadx=5, padx=10, ipady=2, pady=(5, 15))
        info = a.pack_info()
        self.assertIsInstance(info, dict)
        self.assertEqual(info['anchor'], 'center')
        self.assertEqual(info['expand'], self._str(0))
        self.assertEqual(info['fill'], 'none')
        self.assertEqual(info['in'], pack)
        self.assertEqual(info['ipadx'], self._str(0))
        self.assertEqual(info['ipady'], self._str(0))
        self.assertEqual(info['padx'], self._str(0))
        self.assertEqual(info['pady'], self._str(0))
        self.assertEqual(info['side'], 'top')
        info = b.pack_info()
        self.assertIsInstance(info, dict)
        self.assertEqual(info['anchor'], 's')
        self.assertEqual(info['expand'], self._str(1))
        self.assertEqual(info['fill'], 'x')
        self.assertEqual(info['in'], a)
        self.assertEqual(info['ipadx'], self._str(5))
        self.assertEqual(info['ipady'], self._str(2))
        self.assertEqual(info['padx'], self._str(10))
        self.assertEqual(info['pady'], self._str((5, 15)))
        self.assertEqual(info['side'], 'right')

    def test_pack_propagate(self):
        pack, a, b, c, d = self.create2()
        pack.configure(width=300, height=200)
        a.pack_configure()
        pack.pack_propagate(False)
        self.root.update()
        self.assertEqual(pack.winfo_reqwidth(), 300)
        self.assertEqual(pack.winfo_reqheight(), 200)
        pack.pack_propagate(True)
        self.root.update()
        self.assertEqual(pack.winfo_reqwidth(), 20)
        self.assertEqual(pack.winfo_reqheight(), 40)

    def test_pack_slaves(self):
        pack, a, b, c, d = self.create2()
        self.assertEqual(pack.pack_slaves(), [])
        a.pack_configure()
        self.assertEqual(pack.pack_slaves(), [a])
        b.pack_configure()
        self.assertEqual(pack.pack_slaves(), [a, b])


class PlaceTest(AbstractWidgetTest, unittest.TestCase):

    test_keys = None

    def create2(self):
        t = tkinter.Toplevel(self.root, width=300, height=200, bd=0)
        t.wm_geometry('300x200+0+0')
        f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised')
        f.place_configure(x=48, y=38)
        f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised')
        self.root.update()
        return t, f, f2

    def test_place_configure_in(self):
        t, f, f2 = self.create2()
        self.assertEqual(f2.winfo_manager(), '')
        with self.assertRaisesRegexp(TclError, "can't place %s relative to "
                                     "itself" % re.escape(str(f2))):
            f2.place_configure(in_=f2)
        if tcl_version >= (8, 5):
            self.assertEqual(f2.winfo_manager(), '')
        with self.assertRaisesRegexp(TclError, 'bad window path name'):
            f2.place_configure(in_='spam')
        f2.place_configure(in_=f)
        self.assertEqual(f2.winfo_manager(), 'place')

    def test_place_configure_x(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f)
        self.assertEqual(f2.place_info()['x'], '0')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 50)
        f2.place_configure(x=100)
        self.assertEqual(f2.place_info()['x'], '100')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 150)
        f2.place_configure(x=-10, relx=1)
        self.assertEqual(f2.place_info()['x'], '-10')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 190)
        with self.assertRaisesRegexp(TclError, 'bad screen distance "spam"'):
            f2.place_configure(in_=f, x='spam')

    def test_place_configure_y(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f)
        self.assertEqual(f2.place_info()['y'], '0')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 40)
        f2.place_configure(y=50)
        self.assertEqual(f2.place_info()['y'], '50')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 90)
        f2.place_configure(y=-10, rely=1)
        self.assertEqual(f2.place_info()['y'], '-10')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 110)
        with self.assertRaisesRegexp(TclError, 'bad screen distance "spam"'):
            f2.place_configure(in_=f, y='spam')

    def test_place_configure_relx(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f)
        self.assertEqual(f2.place_info()['relx'], '0')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 50)
        f2.place_configure(relx=0.5)
        self.assertEqual(f2.place_info()['relx'], '0.5')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 125)
        f2.place_configure(relx=1)
        self.assertEqual(f2.place_info()['relx'], '1')
        self.root.update()
        self.assertEqual(f2.winfo_x(), 200)
        with self.assertRaisesRegexp(TclError, 'expected floating-point number '
                                     'but got "spam"'):
            f2.place_configure(in_=f, relx='spam')

    def test_place_configure_rely(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f)
        self.assertEqual(f2.place_info()['rely'], '0')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 40)
        f2.place_configure(rely=0.5)
        self.assertEqual(f2.place_info()['rely'], '0.5')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 80)
        f2.place_configure(rely=1)
        self.assertEqual(f2.place_info()['rely'], '1')
        self.root.update()
        self.assertEqual(f2.winfo_y(), 120)
        with self.assertRaisesRegexp(TclError, 'expected floating-point number '
                                     'but got "spam"'):
            f2.place_configure(in_=f, rely='spam')

    def test_place_configure_anchor(self):
        f = tkinter.Frame(self.root)
        with self.assertRaisesRegexp(TclError, 'bad anchor "j"'):
            f.place_configure(anchor='j')
        with self.assertRaisesRegexp(TclError, 'ambiguous anchor ""'):
            f.place_configure(anchor='')
        for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center':
            f.place_configure(anchor=value)
            self.assertEqual(f.place_info()['anchor'], value)

    def test_place_configure_width(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f, width=120)
        self.root.update()
        self.assertEqual(f2.winfo_width(), 120)
        f2.place_configure(width='')
        self.root.update()
        self.assertEqual(f2.winfo_width(), 30)
        with self.assertRaisesRegexp(TclError, 'bad screen distance "abcd"'):
            f2.place_configure(width='abcd')

    def test_place_configure_height(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f, height=120)
        self.root.update()
        self.assertEqual(f2.winfo_height(), 120)
        f2.place_configure(height='')
        self.root.update()
        self.assertEqual(f2.winfo_height(), 60)
        with self.assertRaisesRegexp(TclError, 'bad screen distance "abcd"'):
            f2.place_configure(height='abcd')

    def test_place_configure_relwidth(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f, relwidth=0.5)
        self.root.update()
        self.assertEqual(f2.winfo_width(), 75)
        f2.place_configure(relwidth='')
        self.root.update()
        self.assertEqual(f2.winfo_width(), 30)
        with self.assertRaisesRegexp(TclError, 'expected floating-point number '
                                     'but got "abcd"'):
            f2.place_configure(relwidth='abcd')

    def test_place_configure_relheight(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f, relheight=0.5)
        self.root.update()
        self.assertEqual(f2.winfo_height(), 40)
        f2.place_configure(relheight='')
        self.root.update()
        self.assertEqual(f2.winfo_height(), 60)
        with self.assertRaisesRegexp(TclError, 'expected floating-point number '
                                     'but got "abcd"'):
            f2.place_configure(relheight='abcd')

    def test_place_configure_bordermode(self):
        f = tkinter.Frame(self.root)
        with self.assertRaisesRegexp(TclError, 'bad bordermode "j"'):
            f.place_configure(bordermode='j')
        with self.assertRaisesRegexp(TclError, 'ambiguous bordermode ""'):
            f.place_configure(bordermode='')
        for value in 'inside', 'outside', 'ignore':
            f.place_configure(bordermode=value)
            self.assertEqual(f.place_info()['bordermode'], value)

    def test_place_forget(self):
        foo = tkinter.Frame(self.root)
        foo.place_configure(width=50, height=50)
        self.root.update()
        foo.place_forget()
        self.root.update()
        self.assertFalse(foo.winfo_ismapped())
        with self.assertRaises(TypeError):
            foo.place_forget(0)

    def test_place_info(self):
        t, f, f2 = self.create2()
        f2.place_configure(in_=f, x=1, y=2, width=3, height=4,
                           relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4,
                           anchor='se', bordermode='outside')
        info = f2.place_info()
        self.assertIsInstance(info, dict)
        self.assertEqual(info['x'], '1')
        self.assertEqual(info['y'], '2')
        self.assertEqual(info['width'], '3')
        self.assertEqual(info['height'], '4')
        self.assertEqual(info['relx'], '0.1')
        self.assertEqual(info['rely'], '0.2')
        self.assertEqual(info['relwidth'], '0.3')
        self.assertEqual(info['relheight'], '0.4')
        self.assertEqual(info['anchor'], 'se')
        self.assertEqual(info['bordermode'], 'outside')
        self.assertEqual(info['x'], '1')
        self.assertEqual(info['x'], '1')
        with self.assertRaises(TypeError):
            f2.place_info(0)

    def test_place_slaves(self):
        foo = tkinter.Frame(self.root)
        bar = tkinter.Frame(self.root)
        self.assertEqual(foo.place_slaves(), [])
        bar.place_configure(in_=foo)
        self.assertEqual(foo.place_slaves(), [bar])
        with self.assertRaises(TypeError):
            foo.place_slaves(0)


class GridTest(AbstractWidgetTest, unittest.TestCase):

    test_keys = None

    def tearDown(self):
        cols, rows = self.root.grid_size()
        for i in range(cols + 1):
            self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='')
        for i in range(rows + 1):
            self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='')
        self.root.grid_propagate(1)
        super(GridTest, self).tearDown()

    def test_grid_configure(self):
        b = tkinter.Button(self.root)
        self.assertEqual(b.grid_info(), {})
        b.grid_configure()
        self.assertEqual(b.grid_info()['in'], self.root)
        self.assertEqual(b.grid_info()['column'], self._str(0))
        self.assertEqual(b.grid_info()['row'], self._str(0))
        b.grid_configure({'column': 1}, row=2)
        self.assertEqual(b.grid_info()['column'], self._str(1))
        self.assertEqual(b.grid_info()['row'], self._str(2))

    def test_grid_configure_column(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad column value "-1": '
                                     'must be a non-negative integer'):
            b.grid_configure(column=-1)
        b.grid_configure(column=2)
        self.assertEqual(b.grid_info()['column'], self._str(2))

    def test_grid_configure_columnspan(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad columnspan value "0": '
                                     'must be a positive integer'):
            b.grid_configure(columnspan=0)
        b.grid_configure(columnspan=2)
        self.assertEqual(b.grid_info()['columnspan'], self._str(2))

    def test_grid_configure_in(self):
        f = tkinter.Frame(self.root)
        b = tkinter.Button(self.root)
        self.assertEqual(b.grid_info(), {})
        b.grid_configure()
        self.assertEqual(b.grid_info()['in'], self.root)
        b.grid_configure(in_=f)
        self.assertEqual(b.grid_info()['in'], f)
        b.grid_configure({'in': self.root})
        self.assertEqual(b.grid_info()['in'], self.root)

    def test_grid_configure_ipadx(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad ipadx value "-1": '
                                     'must be positive screen distance'):
            b.grid_configure(ipadx=-1)
        b.grid_configure(ipadx=1)
        self.assertEqual(b.grid_info()['ipadx'], self._str(1))
        b.grid_configure(ipadx='.5c')
        self.assertEqual(b.grid_info()['ipadx'],
                self._str(int_round(pixels_conv('.5c') * self.scaling)))

    def test_grid_configure_ipady(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad ipady value "-1": '
                                     'must be positive screen distance'):
            b.grid_configure(ipady=-1)
        b.grid_configure(ipady=1)
        self.assertEqual(b.grid_info()['ipady'], self._str(1))
        b.grid_configure(ipady='.5c')
        self.assertEqual(b.grid_info()['ipady'],
                self._str(int_round(pixels_conv('.5c') * self.scaling)))

    def test_grid_configure_padx(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad pad value "-1": '
                                     'must be positive screen distance'):
            b.grid_configure(padx=-1)
        b.grid_configure(padx=1)
        self.assertEqual(b.grid_info()['padx'], self._str(1))
        b.grid_configure(padx=(10, 5))
        self.assertEqual(b.grid_info()['padx'], self._str((10, 5)))
        b.grid_configure(padx='.5c')
        self.assertEqual(b.grid_info()['padx'],
                self._str(int_round(pixels_conv('.5c') * self.scaling)))

    def test_grid_configure_pady(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad pad value "-1": '
                                     'must be positive screen distance'):
            b.grid_configure(pady=-1)
        b.grid_configure(pady=1)
        self.assertEqual(b.grid_info()['pady'], self._str(1))
        b.grid_configure(pady=(10, 5))
        self.assertEqual(b.grid_info()['pady'], self._str((10, 5)))
        b.grid_configure(pady='.5c')
        self.assertEqual(b.grid_info()['pady'],
                self._str(int_round(pixels_conv('.5c') * self.scaling)))

    def test_grid_configure_row(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad (row|grid) value "-1": '
                                     'must be a non-negative integer'):
            b.grid_configure(row=-1)
        b.grid_configure(row=2)
        self.assertEqual(b.grid_info()['row'], self._str(2))

    def test_grid_configure_rownspan(self):
        b = tkinter.Button(self.root)
        with self.assertRaisesRegexp(TclError, 'bad rowspan value "0": '
                                     'must be a positive integer'):
            b.grid_configure(rowspan=0)
        b.grid_configure(rowspan=2)
        self.assertEqual(b.grid_info()['rowspan'], self._str(2))

    def test_grid_configure_sticky(self):
        f = tkinter.Frame(self.root, bg='red')
        with self.assertRaisesRegexp(TclError, 'bad stickyness value "glue"'):
            f.grid_configure(sticky='glue')
        f.grid_configure(sticky='ne')
        self.assertEqual(f.grid_info()['sticky'], 'ne')
        f.grid_configure(sticky='n,s,e,w')
        self.assertEqual(f.grid_info()['sticky'], 'nesw')

    def test_grid_columnconfigure(self):
        with self.assertRaises(TypeError):
            self.root.grid_columnconfigure()
        self.assertEqual(self.root.grid_columnconfigure(0),
                         {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
        with self.assertRaisesRegexp(TclError, 'bad option "-foo"'):
            self.root.grid_columnconfigure(0, 'foo')
        self.root.grid_columnconfigure((0, 3), weight=2)
        with self.assertRaisesRegexp(TclError,
                                     'must specify a single element on retrieval'):
            self.root.grid_columnconfigure((0, 3))
        b = tkinter.Button(self.root)
        b.grid_configure(column=0, row=0)
        if tcl_version >= (8, 5):
            self.root.grid_columnconfigure('all', weight=3)
            with self.assertRaisesRegexp(TclError, 'expected integer but got "all"'):
                self.root.grid_columnconfigure('all')
            self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
        self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2)
        self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0)
        if tcl_version >= (8, 5):
            self.root.grid_columnconfigure(b, weight=4)
            self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4)

    def test_grid_columnconfigure_minsize(self):
        with self.assertRaisesRegexp(TclError, 'bad screen distance "foo"'):
            self.root.grid_columnconfigure(0, minsize='foo')
        self.root.grid_columnconfigure(0, minsize=10)
        self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10)
        self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10)

    def test_grid_columnconfigure_weight(self):
        with self.assertRaisesRegexp(TclError, 'expected integer but got "bad"'):
            self.root.grid_columnconfigure(0, weight='bad')
        with self.assertRaisesRegexp(TclError, 'invalid arg "-weight": '
                                     'should be non-negative'):
            self.root.grid_columnconfigure(0, weight=-3)
        self.root.grid_columnconfigure(0, weight=3)
        self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3)
        self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3)

    def test_grid_columnconfigure_pad(self):
        with self.assertRaisesRegexp(TclError, 'bad screen distance "foo"'):
            self.root.grid_columnconfigure(0, pad='foo')
        with self.assertRaisesRegexp(TclError, 'invalid arg "-pad": '
                                     'should be non-negative'):
            self.root.grid_columnconfigure(0, pad=-3)
        self.root.grid_columnconfigure(0, pad=3)
        self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3)
        self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3)

    def test_grid_columnconfigure_uniform(self):
        self.root.grid_columnconfigure(0, uniform='foo')
        self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo')
        self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo')

    def test_grid_rowconfigure(self):
        with self.assertRaises(TypeError):
            self.root.grid_rowconfigure()
        self.assertEqual(self.root.grid_rowconfigure(0),
                         {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0})
        with self.assertRaisesRegexp(TclError, 'bad option "-foo"'):
            self.root.grid_rowconfigure(0, 'foo')
        self.root.grid_rowconfigure((0, 3), weight=2)
        with self.assertRaisesRegexp(TclError,
                                     'must specify a single element on retrieval'):
            self.root.grid_rowconfigure((0, 3))
        b = tkinter.Button(self.root)
        b.grid_configure(column=0, row=0)
        if tcl_version >= (8, 5):
            self.root.grid_rowconfigure('all', weight=3)
            with self.assertRaisesRegexp(TclError, 'expected integer but got "all"'):
                self.root.grid_rowconfigure('all')
            self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
        self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2)
        self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0)
        if tcl_version >= (8, 5):
            self.root.grid_rowconfigure(b, weight=4)
            self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4)

    def test_grid_rowconfigure_minsize(self):
        with self.assertRaisesRegexp(TclError, 'bad screen distance "foo"'):
            self.root.grid_rowconfigure(0, minsize='foo')
        self.root.grid_rowconfigure(0, minsize=10)
        self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10)
        self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10)

    def test_grid_rowconfigure_weight(self):
        with self.assertRaisesRegexp(TclError, 'expected integer but got "bad"'):
            self.root.grid_rowconfigure(0, weight='bad')
        with self.assertRaisesRegexp(TclError, 'invalid arg "-weight": '
                                     'should be non-negative'):
            self.root.grid_rowconfigure(0, weight=-3)
        self.root.grid_rowconfigure(0, weight=3)
        self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3)
        self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3)

    def test_grid_rowconfigure_pad(self):
        with self.assertRaisesRegexp(TclError, 'bad screen distance "foo"'):
            self.root.grid_rowconfigure(0, pad='foo')
        with self.assertRaisesRegexp(TclError, 'invalid arg "-pad": '
                                     'should be non-negative'):
            self.root.grid_rowconfigure(0, pad=-3)
        self.root.grid_rowconfigure(0, pad=3)
        self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3)
        self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3)

    def test_grid_rowconfigure_uniform(self):
        self.root.grid_rowconfigure(0, uniform='foo')
        self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo')
        self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo')

    def test_grid_forget(self):
        b = tkinter.Button(self.root)
        c = tkinter.Button(self.root)
        b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
                         padx=3, pady=4, sticky='ns')
        self.assertEqual(self.root.grid_slaves(), [b])
        b.grid_forget()
        c.grid_forget()
        self.assertEqual(self.root.grid_slaves(), [])
        self.assertEqual(b.grid_info(), {})
        b.grid_configure(row=0, column=0)
        info = b.grid_info()
        self.assertEqual(info['row'], self._str(0))
        self.assertEqual(info['column'], self._str(0))
        self.assertEqual(info['rowspan'], self._str(1))
        self.assertEqual(info['columnspan'], self._str(1))
        self.assertEqual(info['padx'], self._str(0))
        self.assertEqual(info['pady'], self._str(0))
        self.assertEqual(info['sticky'], '')

    def test_grid_remove(self):
        b = tkinter.Button(self.root)
        c = tkinter.Button(self.root)
        b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
                         padx=3, pady=4, sticky='ns')
        self.assertEqual(self.root.grid_slaves(), [b])
        b.grid_remove()
        c.grid_remove()
        self.assertEqual(self.root.grid_slaves(), [])
        self.assertEqual(b.grid_info(), {})
        b.grid_configure(row=0, column=0)
        info = b.grid_info()
        self.assertEqual(info['row'], self._str(0))
        self.assertEqual(info['column'], self._str(0))
        self.assertEqual(info['rowspan'], self._str(2))
        self.assertEqual(info['columnspan'], self._str(2))
        self.assertEqual(info['padx'], self._str(3))
        self.assertEqual(info['pady'], self._str(4))
        self.assertEqual(info['sticky'], 'ns')

    def test_grid_info(self):
        b = tkinter.Button(self.root)
        self.assertEqual(b.grid_info(), {})
        b.grid_configure(row=2, column=2, rowspan=2, columnspan=2,
                         padx=3, pady=4, sticky='ns')
        info = b.grid_info()
        self.assertIsInstance(info, dict)
        self.assertEqual(info['in'], self.root)
        self.assertEqual(info['row'], self._str(2))
        self.assertEqual(info['column'], self._str(2))
        self.assertEqual(info['rowspan'], self._str(2))
        self.assertEqual(info['columnspan'], self._str(2))
        self.assertEqual(info['padx'], self._str(3))
        self.assertEqual(info['pady'], self._str(4))
        self.assertEqual(info['sticky'], 'ns')

    def test_grid_bbox(self):
        self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0))
        self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0))
        self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0))
        with self.assertRaisesRegexp(TclError, 'expected integer but got "x"'):
            self.root.grid_bbox('x', 0)
        with self.assertRaisesRegexp(TclError, 'expected integer but got "x"'):
            self.root.grid_bbox(0, 'x')
        with self.assertRaisesRegexp(TclError, 'expected integer but got "x"'):
            self.root.grid_bbox(0, 0, 'x', 0)
        with self.assertRaisesRegexp(TclError, 'expected integer but got "x"'):
            self.root.grid_bbox(0, 0, 0, 'x')
        with self.assertRaises(TypeError):
            self.root.grid_bbox(0, 0, 0, 0, 0)
        t = self.root
        # de-maximize
        t.wm_geometry('1x1+0+0')
        t.wm_geometry('')
        f1 = tkinter.Frame(t, width=75, height=75, bg='red')
        f2 = tkinter.Frame(t, width=90, height=90, bg='blue')
        f1.grid_configure(row=0, column=0)
        f2.grid_configure(row=1, column=1)
        self.root.update()
        self.assertEqual(t.grid_bbox(), (0, 0, 165, 165))
        self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75))
        self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165))
        self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90))
        self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165))
        self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0))
        self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0))

    def test_grid_location(self):
        with self.assertRaises(TypeError):
            self.root.grid_location()
        with self.assertRaises(TypeError):
            self.root.grid_location(0)
        with self.assertRaises(TypeError):
            self.root.grid_location(0, 0, 0)
        with self.assertRaisesRegexp(TclError, 'bad screen distance "x"'):
            self.root.grid_location('x', 'y')
        with self.assertRaisesRegexp(TclError, 'bad screen distance "y"'):
            self.root.grid_location('1c', 'y')
        t = self.root
        # de-maximize
        t.wm_geometry('1x1+0+0')
        t.wm_geometry('')
        f = tkinter.Frame(t, width=200, height=100,
                          highlightthickness=0, bg='red')
        self.assertEqual(f.grid_location(10, 10), (-1, -1))
        f.grid_configure()
        self.root.update()
        self.assertEqual(t.grid_location(-10, -10), (-1, -1))
        self.assertEqual(t.grid_location(-10, 0), (-1, 0))
        self.assertEqual(t.grid_location(-1, 0), (-1, 0))
        self.assertEqual(t.grid_location(0, -10), (0, -1))
        self.assertEqual(t.grid_location(0, -1), (0, -1))
        self.assertEqual(t.grid_location(0, 0), (0, 0))
        self.assertEqual(t.grid_location(200, 0), (0, 0))
        self.assertEqual(t.grid_location(201, 0), (1, 0))
        self.assertEqual(t.grid_location(0, 100), (0, 0))
        self.assertEqual(t.grid_location(0, 101), (0, 1))
        self.assertEqual(t.grid_location(201, 101), (1, 1))

    def test_grid_propagate(self):
        self.assertEqual(self.root.grid_propagate(), True)
        with self.assertRaises(TypeError):
            self.root.grid_propagate(False, False)
        self.root.grid_propagate(False)
        self.assertFalse(self.root.grid_propagate())
        f = tkinter.Frame(self.root, width=100, height=100, bg='red')
        f.grid_configure(row=0, column=0)
        self.root.update()
        self.assertEqual(f.winfo_width(), 100)
        self.assertEqual(f.winfo_height(), 100)
        f.grid_propagate(False)
        g = tkinter.Frame(self.root, width=75, height=85, bg='green')
        g.grid_configure(in_=f, row=0, column=0)
        self.root.update()
        self.assertEqual(f.winfo_width(), 100)
        self.assertEqual(f.winfo_height(), 100)
        f.grid_propagate(True)
        self.root.update()
        self.assertEqual(f.winfo_width(), 75)
        self.assertEqual(f.winfo_height(), 85)

    def test_grid_size(self):
        with self.assertRaises(TypeError):
            self.root.grid_size(0)
        self.assertEqual(self.root.grid_size(), (0, 0))
        f = tkinter.Scale(self.root)
        f.grid_configure(row=0, column=0)
        self.assertEqual(self.root.grid_size(), (1, 1))
        f.grid_configure(row=4, column=5)
        self.assertEqual(self.root.grid_size(), (6, 5))

    def test_grid_slaves(self):
        self.assertEqual(self.root.grid_slaves(), [])
        a = tkinter.Label(self.root)
        a.grid_configure(row=0, column=1)
        b = tkinter.Label(self.root)
        b.grid_configure(row=1, column=0)
        c = tkinter.Label(self.root)
        c.grid_configure(row=1, column=1)
        d = tkinter.Label(self.root)
        d.grid_configure(row=1, column=1)
        self.assertEqual(self.root.grid_slaves(), [d, c, b, a])
        self.assertEqual(self.root.grid_slaves(row=0), [a])
        self.assertEqual(self.root.grid_slaves(row=1), [d, c, b])
        self.assertEqual(self.root.grid_slaves(column=0), [b])
        self.assertEqual(self.root.grid_slaves(column=1), [d, c, a])
        self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c])


tests_gui = (
    PackTest, PlaceTest, GridTest,
)

if __name__ == '__main__':
    run_unittest(*tests_gui)
PK(/�Z�����test_tkinter/test_loadtk.pyonu�[����
zfc@s�ddlZddlZddlZddlmZddlmZmZejd�dej	fd��YZ
e
fZedkr�ej
e�ndS(i����N(ttest_support(tTcltTclErrortguit
TkLoadTestcBs5eZejdejkd�d��Zd�ZRS(tDISPLAYsNo $DISPLAY set.cCsJt�}|jt|j�|j�|jd|j��|j�dS(Ns1x1+0+0(RtassertRaisesRtwinfo_geometrytloadtktassertEqualtdestroy(tselfttcl((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyt
testLoadTks
	
cCs�d}tjjd�rdStj��t}dtjkri|d=tjd�j	�j
�}|ridSnt�}|jt
|j�|jt
|j�WdQXdS(NtwintdarwintcygwinRs
echo $DISPLAY(RRR(tNonetsystplatformt
startswithRtEnvironmentVarGuardtostenvirontpopentreadtstripRRRRR(Rtold_displaytenvtdisplayR((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyttestLoadTkFailures	(t__name__t
__module__tunittesttskipIfRRR
R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyR	s$t__main__(RRR!ttestRtTkinterRRtrequirestTestCaseRt	tests_guiRtrun_unittest(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyt<module>s
!	PK(/�Z6��test_tkinter/test_loadtk.pynu�[���import os
import sys
import unittest
from test import test_support
from Tkinter import Tcl, TclError

test_support.requires('gui')

class TkLoadTest(unittest.TestCase):

    @unittest.skipIf('DISPLAY' not in os.environ, 'No $DISPLAY set.')
    def testLoadTk(self):
        tcl = Tcl()
        self.assertRaises(TclError,tcl.winfo_geometry)
        tcl.loadtk()
        self.assertEqual('1x1+0+0', tcl.winfo_geometry())
        tcl.destroy()

    def testLoadTkFailure(self):
        old_display = None
        if sys.platform.startswith(('win', 'darwin', 'cygwin')):
            # no failure possible on windows?

            # XXX Maybe on tk older than 8.4.13 it would be possible,
            # see tkinter.h.
            return
        with test_support.EnvironmentVarGuard() as env:
            if 'DISPLAY' in os.environ:
                del env['DISPLAY']
                # on some platforms, deleting environment variables
                # doesn't actually carry through to the process level
                # because they don't support unsetenv
                # If that's the case, abort.
                display = os.popen('echo $DISPLAY').read().strip()
                if display:
                    return

            tcl = Tcl()
            self.assertRaises(TclError, tcl.winfo_geometry)
            self.assertRaises(TclError, tcl.loadtk)

tests_gui = (TkLoadTest, )

if __name__ == "__main__":
    test_support.run_unittest(*tests_gui)
PK(/�Z�-�ԠԠ'test_tkinter/test_geometry_managers.pycnu�[����
zfc@sddlZddlZddlZddlmZddlmZmZddlm	Z	m
Z
mZddlm
Z
mZed�de
ejfd��YZd	e
ejfd
��YZde
ejfd��YZeeefZed
kree�ndS(i����N(tTclError(trequirestrun_unittest(tpixels_convttcl_versiontrequires_tcl(tAbstractWidgetTestt	int_roundtguitPackTestcBs�eZd
Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�ZRS(c
Cs�tj|jdd�}|jd�|jdd�tj|dddddd	d
d�}tj|dddd
ddd
d�}tj|ddddddd
d�}tj|dddd	ddd
d�}|||||fS(Ntnametpacks300x200+0+0itatwidthitheighti(tbgtredtbi2itbluetciPtgreentdtyellow(ttkintertTopleveltroottwm_geometryt
wm_minsizetFrame(tselfRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pytcreate2s
''''cCs;|j�\}}}}}|jtd|��|jd|�WdQX|jtd��|jdd�WdQX|jdd�|jdd�|jdd�|jdd�|j|j�||||g�|jd|�|j|j�||||g�|jd|�|j|j�||||g�dS(Nswindow "%s" isn't packedtaftersbad window path name ".foo"s.footsidettop(RtassertRaisesRegexpRtpack_configuretassertEqualtpack_slaves(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_afters""cs��j�\}�}}}��fd�}|dd�|dd�|dd�|dd	�|d
d�|dd
�|dd�|dd�|dd�dS(Ncs[�jddddddddd	d
dtd|��jj��j�j�|�dS(
NR R!tipadxitpadxi
tipadyitpadyitexpandtanchor(R#tTrueRtupdateR$twinfo_geometry(R,tgeom(RR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pytcheck-s'

tns30x70+135+20tnes30x70+260+20tes30x70+260+65tses
30x70+260+110tss
30x70+135+110tsws30x70+10+110tws30x70+10+65tnws30x70+10+20tcenters30x70+135+65(R(RRRRRR1((RRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_anchor+s







cCs;|j�\}}}}}|jtd|��|jd|�WdQX|jtd��|jdd�WdQX|jdd�|jdd�|jdd�|jdd�|j|j�||||g�|jd|�|j|j�||||g�|jd|�|j|j�||||g�dS(Nswindow "%s" isn't packedtbeforesbad window path name ".foo"s.fooR R!(RR"RR#R$R%(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_before<s""cs{�j�\}���������fd�}�jdd��jdd��jdd��jdd�|ddd	d
��jdddd��jdddd
��jdddt��jdddd�|dddd��jdddddd��jdddd
dd��jdddtdd��jdddddd�|dddd�dS(Ncsy�jj��j�j�|d��j�j�|d��j�j�|d��j�j�|d�dS(Niiii(RR.R$R/(tgeoms(RRRRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1Ns

R tleftR!trighttbottoms
20x40+0+80s50x30+135+0s80x80+220+75s
40x30+100+170R+tyestonis20x40+40+80s50x30+175+35s
80x80+180+110s
40x30+100+135tfilltboths100x200+0+0s
200x100+100+0s160x100+140+100s40x100+100+100(RR#R-(RRR1((RRRRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_expandLs"cCs2|j�\}}}}}|jdd�|jdd�|jdd�|jdd�|jd|�|j|j�||||g�|jd|�|j|j�|||g�|j|j�|g�|jtd|f��|jd|�WdQX|jtd��|jdd�WdQXdS(NR R!tin_scan't pack %s inside itselfsbad window path name ".foo"s.foo(RR#R$R%R"R(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_inds"	cs��j�\}��}}���fd�}|dddddd�|dddddd'�|dddddd�|d
ddddddd	�|dddddddd�|dddddd(dd�|dddddddd�|d
ddddddd	dd�|dddddddd)dd�|dddddd�|dddddd*�|dddddd�|dddddddd	�|dddddddd+�|d ddddddd�|d!ddddd,dd�|d#ddddddd�|d$ddddddd	dd�|d%ddddddd-dd��jdd&��j�j�d�j|jd&����jdd&��j�j�d�j|jd&���dS(.Ncst�j��j��j|��jdtdd��jj��j�j�|��j�j�|�dS(NR+RDRE(tpack_forgetR#R-RR.R$R/(tgeom1tgeom2tkwargs(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1ws



s20x40+260+80s240x200+0+0R R@R(is20x40+250+80i
is60x40+240+80R's30x40+260+80s250x200+0+0iRDtxs20x40+249+80i	is30x40+255+80is20x40+140+0s300x160+0+40R!s20x40+120+0ii(s60x40+120+0s30x40+135+0s30x40+130+0s260x40+20+0s260x40+25+0is
300x40+0+0s280x40+10+0s
280x40+5+0t1c(i
i(i	i(ii(ii((ii(ii(ii(RR#R$t	pack_infot_strtwinfo_pixels(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt#test_pack_configure_padx_ipadx_fillusBcs��j�\}��}}���fd�}|dddddd�|dddddd'�|dddddd�|d
ddddddd	�|dddddddd�|dddddd(dd�|dddddddd�|d
ddddddd	dd�|dddddddd)dd�|dddddd�|dddddd*�|dddddd�|dddddddd	�|dddddddd+�|d ddddddd�|d!ddddd,dd�|d#ddddddd�|d$ddddddd	dd�|d%ddddddd-dd��jdd&��j�j�d�j|jd&����jdd&��j�j�d�j|jd&���dS(.Ncst�j��j��j|��jdtdd��jj��j�j�|��j�j�|�dS(NR+RDRE(RIR#R-RR.R$R/(RJRKRL(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1�s



s20x40+280+80s280x200+0+0R R@R*is20x40+280+70i
is20x80+280+60R)s20x50+280+75iRDRMs20x40+280+69i	is20x50+280+70is20x40+140+20s300x120+0+80R!s20x40+140+0ii(s20x80+140+0s20x50+140+10s300x130+0+70s20x50+140+5s300x40+0+20s300x40+0+25is
300x80+0+0s300x50+0+10s
300x50+0+5RN(i
i(i	i(ii(ii((ii(ii(ii(RR#R$RORPRQ(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt#test_pack_configure_pady_ipady_fill�sBcst�j�\}��}}���fd�}|ddd�|ddd�|dd	d
�|ddd
�dS(Ncs}�jd|��j�j�d|��jdtdd��jj��j�j�|��j�j�|�dS(NR R+RDRE(R#R$ROR-RR.R/(R RJRK(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1�s
R!s20x40+140+0s300x160+0+40RAs
20x40+140+160s300x160+0+0R?s
20x40+0+80s280x200+20+0R@s20x40+280+80s280x200+0+0(R(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_side�scCs�|j�\}}}}}|j�|j�|j�|j|j�|||g�|j�|j|j�||g�|j�|j|j�||g�|j�dS(N(RR#R$R%RI(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_forget�s




cCs�|j�\}}}}}|jtd|��|j�WdQX|j�|jddd|dddtdd	d
ddd
dddd�	|j�}|j|t�|j|dd�|j|d|j	d��|j|dd�|j|d|�|j|d
|j	d��|j|d|j	d��|j|d|j	d��|j|d|j	d��|j|dd�|j�}|j|t�|j|dd�|j|d|j	d��|j|dd	�|j|d|�|j|d
|j	d��|j|d|j	d��|j|d|j	d
��|j|d|j	d��|j|dd�dS(Nswindow "%s" isn't packedR R@RGR,R6R+RDRMR'iR(i
R)iR*iR:itnonetinR!i(ii(ii(
RR"RROR#R-tassertIsInstancetdictR$RP(RRRRRRtinfo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_info�s8
'cCs�|j�\}}}}}|jdddd�|j�|jt�|jj�|j|j�d�|j|j	�d�|jt
�|jj�|j|j�d�|j|j	�d�dS(NR
i,Ri�ii((Rt	configureR#tpack_propagatetFalseRR.R$twinfo_reqwidthtwinfo_reqheightR-(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_propagates




cCs~|j�\}}}}}|j|j�g�|j�|j|j�|g�|j�|j|j�||g�dS(N(RR$R%R#(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_slavess

N(t__name__t
__module__tNonet	test_keysRR&R;R=RFRHRRRSRTRUR[RaRb(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR	
s	
						*	*				
t	PlaceTestcBs�eZdZd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�Zd
�Zd�ZRS(c
Cs�tj|jdddddd�}|jd�tj|dddd	dd
dd�}|jd
ddd�tj|dddddd
dd�}|jj�|||fS(NR
i,Ri�tbdis300x200+0+0i�iTitrelieftraisedRMi0tyi&ii<(RRRRRtplace_configureR.(Rtttftf2((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyRs$
''
cCs�|j�\}}}|j|j�d�|jtdtjt|����|jd|�WdQXt	d	kr�|j|j�d�n|jtd��|jdd�WdQX|jd|�|j|j�d�dS(
Nts!can't place %s relative to itselfRGiisbad window path nametspamtplace(ii(
RR$t
winfo_managerR"RtretescapetstrRlR(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_in$sc	Cs5|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jddd	d
�|j|j�dd�|jj�|j|j�d�|jtd
��|jd|dd�WdQXdS(NRGRMt0i2idt100i�i����trelxis-10i�sbad screen distance "spam"Rq(	RRlR$t
place_infoRR.twinfo_xR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_x1s


c	Cs5|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jddd	d
�|j|j�dd�|jj�|j|j�d�|jtd
��|jd|dd�WdQXdS(NRGRkRxi(i2t50iZi����trelyis-10insbad screen distance "spam"Rq(	RRlR$R{RR.twinfo_yR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_yBs


c	Cs/|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd	�|jj�|j|j�d
�|jtd��|jd|dd�WdQXdS(
NRGRzRxi2g�?s0.5i}it1i�s-expected floating-point number but got "spam"Rq(	RRlR$R{RR.R|R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relxSs


c	Cs/|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd	�|jj�|j|j�d
�|jtd��|jd|dd�WdQXdS(
NRGRRxi(g�?s0.5iPiR�ixs-expected floating-point number but got "spam"Rq(	RRlR$R{RR.R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relyes


cCs�tj|j�}|jtd��|jdd�WdQX|jtd��|jdd�WdQXx8dD]0}|jd|�|j|j�d|�qkWdS(Nsbad anchor "j"R,tjsambiguous anchor ""RpR2R3R4R5R6R7R8R9R:(	R2R3R4R5R6R7R8R9R:(RRRR"RRlR$R{(RRntvalue((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_anchorws
cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(NRGR
ixRpisbad screen distance "abcd"tabcd(RRlRR.R$twinfo_widthR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_width�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(NRGRixRpi<sbad screen distance "abcd"R�(RRlRR.R$twinfo_heightR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_height�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(	NRGtrelwidthg�?iKRpis-expected floating-point number but got "abcd"R�(RRlRR.R$R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relwidth�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(	NRGt	relheightg�?i(Rpi<s-expected floating-point number but got "abcd"R�(RRlRR.R$R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relheight�s

cCs�tj|j�}|jtd��|jdd�WdQX|jtd��|jdd�WdQXx8d	D]0}|jd|�|j|j�d|�qkWdS(
Nsbad bordermode "j"t
bordermodeR�sambiguous bordermode ""Rptinsidetoutsidetignore(R�R�R�(RRRR"RRlR$R{(RRnR�((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_bordermode�s
cCs�tj|j�}|jdddd�|jj�|j�|jj�|j|j��|jt	��|jd�WdQXdS(NR
i2Ri(
RRRRlR.tplace_forgettassertFalsetwinfo_ismappedtassertRaisest	TypeError(Rtfoo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_forget�s


cCs�|j�\}}}|jd|dddddddd	d
ddd
dddddddd�|j�}|j|t�|j|dd�|j|dd�|j|dd�|j|dd�|j|d
d�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|jt��|jd�WdQXdS(NRGRMiRkiR
iRiRzg�������?Rg�������?R�g333333�?R�g�������?R,R5R�R�R�t2t3t4s0.1s0.2s0.3s0.4i(RRlR{RXRYR$R�R�(RRmRnRoRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_info�s('
cCs�tj|j�}tj|j�}|j|j�g�|jd|�|j|j�|g�|jt��|jd�WdQXdS(NRGi(RRRR$tplace_slavesRlR�R�(RR�tbar((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_slaves�sN(RcRdReRfRRwR}R�R�R�R�R�R�R�R�R�R�R�R�(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyRgs 			
					
					
	
	tGridTestcBseZdZd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z d�Z!RS(cCs�|jj�\}}x@t|d�D].}|jj|dddddddd�q&Wx@t|d�D].}|jj|dddddddd�qiW|jjd�tt|�j�dS(NitweightitminsizetpadtuniformRp(	Rt	grid_sizetrangetgrid_columnconfiguretgrid_rowconfiguretgrid_propagatetsuperR�ttearDown(Rtcolstrowsti((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR��s,,cCs�tj|j�}|j|j�i�|j�|j|j�d|j�|j|j�d|jd��|j|j�d|jd��|jidd6dd�|j|j�d|jd��|j|j�d|jd��dS(NRWtcolumnitrowii(RtButtonRR$t	grid_infotgrid_configureRP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure�s
###cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns5bad column value "-1": must be a non-negative integerR�i����i(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_column�s
cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns4bad columnspan value "0": must be a positive integert
columnspanii(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_columnspans
cCs�tj|j�}tj|j�}|j|j�i�|j�|j|j�d|j�|jd|�|j|j�d|�|ji|jd6�|j|j�d|j�dS(NRWRG(RRRR�R$R�R�(RRnR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ins
cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jt	t
d�|j���dS(Ns6bad ipadx value "-1": must be positive screen distanceR'i����is.5c(RR�RR"RR�R$R�RPRRtscaling(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ipadxs#cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jt	t
d�|j���dS(Ns6bad ipady value "-1": must be positive screen distanceR)i����is.5c(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ipady!s#cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jd	��|jdd�|j|j�d|jt	t
d�|j���dS(
Ns4bad pad value "-1": must be positive screen distanceR(i����ii
is.5c(i
i(i
i(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_padx,s##cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jd	��|jdd�|j|j�d|jt	t
d�|j���dS(
Ns4bad pad value "-1": must be positive screen distanceR*i����ii
is.5c(i
i(i
i(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_pady9s##cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns9bad (row|grid) value "-1": must be a non-negative integerR�i����i(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_rowFs
cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns1bad rowspan value "0": must be a positive integertrowspanii(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_rownspanNs
cCs�tj|jdd�}|jtd��|jdd�WdQX|jdd�|j|j�dd�|jdd�|j|j�dd�dS(	NRRsbad stickyness value "glue"tstickytglueR3sn,s,e,wtnesw(RRRR"RR�R$R�(RRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_stickyVsc	Cs�|jt��|jj�WdQX|j|jjd�idd6dd6dd6dd6�|jtd��|jjdd�WdQX|jjddd	�|jtd
��|jjd�WdQXtj	|j�}|j
dddd�tdkr[|jjddd�|jtd��|jjd�WdQX|j|jjdd�d�n|j|jjdd�d	�|j|jjdd�d�tdkr�|jj|dd�|j|jjdd�d�ndS(NiR�R�R�R�sbad option "-foo"R�iis*must specify a single element on retrievalR�R�iitallsexpected integer but got "all"i	i(ii(ii(ii(ii(R�R�RR�R$ReR"RRR�R�R(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_columnconfigure_s,#	
"cCs�|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�i
(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt!test_grid_columnconfigure_minsizews
c	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsexpected integer but got "bad"iR�tbads-invalid arg "-weight": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt test_grid_columnconfigure_weight~sc	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�s*invalid arg "-pad": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_columnconfigure_pad�scCsY|jjddd�|j|jjdd�d�|j|jjd�dd�dS(NiR�R�(RR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt!test_grid_columnconfigure_uniform�sc	Cs�|jt��|jj�WdQX|j|jjd�idd6dd6dd6dd6�|jtd��|jjdd�WdQX|jjddd	�|jtd
��|jjd�WdQXtj	|j�}|j
dddd�tdkr[|jjddd�|jtd��|jjd�WdQX|j|jjdd�d�n|j|jjdd�d	�|j|jjdd�d�tdkr�|jj|dd�|j|jjdd�d�ndS(NiR�R�R�R�sbad option "-foo"R�iis*must specify a single element on retrievalR�R�iiR�sexpected integer but got "all"i	i(ii(ii(ii(ii(R�R�RR�R$ReR"RRR�R�R(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure�s,#	
"cCs�|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�i
(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_minsize�s
c	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsexpected integer but got "bad"iR�R�s-invalid arg "-weight": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_weight�sc	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�s*invalid arg "-pad": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_pad�scCsY|jjddd�|j|jjdd�d�|j|jjd�dd�dS(NiR�R�(RR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_uniform�scCs�tj|j�}tj|j�}|jdddddddddddd	d
d�|j|jj�|g�|j�|j�|j|jj�g�|j|j�i�|jdddd�|j�}|j|d|jd��|j|d|jd��|j|d|jd
��|j|d|jd
��|j|d|jd��|j|d|jd��|j|d
d�dS(NR�iR�R�R�R(iR*iR�tnsiiRp(	RR�RR�R$tgrid_slavestgrid_forgetR�RP(RRRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_forget�s$!

cCs�tj|j�}tj|j�}|jdddddddddddd	d
d�|j|jj�|g�|j�|j�|j|jj�g�|j|j�i�|jdddd�|j�}|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd	��|j|d
d�dS(
NR�iR�R�R�R(iR*iR�R�i(	RR�RR�R$R�tgrid_removeR�RP(RRRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_remove�s$!

cCsUtj|j�}|j|j�i�|jdddddddddddd	d
d�|j�}|j|t�|j|d|j�|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd	��|j|d
d�dS(
NR�iR�R�R�R(iR*iR�R�RW(	RR�RR$R�R�RXRYRP(RRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_info�s!cCs�|j|jj�d�|j|jjdd�d�|j|jjdddd�d�|jtd��|jjdd�WdQX|jtd��|jjdd�WdQX|jtd��|jjdddd�WdQX|jtd��|jjdddd�WdQX|jt��!|jjddddd�WdQX|j}|jd�|jd�tj	|ddd	dd
d�}tj	|ddd	dd
d
�}|j
dddd�|j
dddd�|jj�|j|j�d�|j|jdd�d�|j|jdddd�d�|j|jdd�d�|j|jdddd�d�|j|jdddd�d�|j|jdddd�d�dS(Niisexpected integer but got "x"RMs1x1+0+0RpR
iKRRRiZRR�R�i�i
i����i����i(iiii(iiii(iiii(iii�i�(iiiKiK(iii�i�(iKiKiZiZ(iii�i�(iiii(i�i�ii(R$Rt	grid_bboxR"RR�R�RRRR�R.(RRmtf1Ro((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_bboxs8%"	

!!
"""cCs�|jt��|jj�WdQX|jt��|jjd�WdQX|jt��|jjddd�WdQX|jtd��|jjdd�WdQX|jtd��|jjdd�WdQX|j}|jd�|jd�tj|d	d
ddd
ddd�}|j	|jdd�d�|j
�|jj�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jd
d�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d �|j	|jdd�d!�dS("Nisbad screen distance "x"RMRksbad screen distance "y"RNs1x1+0+0RpR
i�RidthighlightthicknessRRi
i����i����i�iie(i����i����(i����i����(i����i(i����i(ii����(ii����(ii(ii(ii(ii(ii(ii(R�R�Rt
grid_locationR"RRRRR$R�R.(RRmRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_location&s:	



c	Cs�|j|jj�t�|jt��|jjtt�WdQX|jjt�|j|jj��tj	|jdddddd�}|j
dddd�|jj�|j|j�d�|j|j
�d�|jt�tj	|jdd	dd
dd�}|j
d|dddd�|jj�|j|j�d�|j|j
�d�|jt�|jj�|j|j�d	�|j|j
�d
�dS(
NR
idRRRR�iR�iKiURRG(R$RR�R-R�R�R^R�RRR�R.R�R�(RRntg((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_propagateFs($

$


cCs�|jt��|jjd�WdQX|j|jj�d�tj|j�}|jdddd�|j|jj�d	�|jdddd�|j|jj�d
�dS(NiR�R�iiii(ii(ii(ii(R�R�RR�R$RtScaleR�(RRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_size\scCs�|j|jj�g�tj|j�}|jdddd�tj|j�}|jdddd�tj|j�}|jdddd�tj|j�}|jdddd�|j|jj�||||g�|j|jjdd�|g�|j|jjdd�|||g�|j|jjdd�|g�|j|jjdd�|||g�|j|jjdddd�||g�dS(NR�iR�i(R$RR�RtLabelR�(RRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_slavesfs%"("(N("RcRdReRfR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR��s>									
	
							
	
				
	
						 		
t__main__(tunittestRttTkinterRRttest.test_supportRRttest_ttk.supportRRRtwidget_testsRRtTestCaseR	RgR�t	tests_guiRc(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt<module>s
����PK(/�Zpr����test_tkinter/test_font.pynu�[���import unittest
import Tkinter as tkinter
import tkFont as font
from test.test_support import requires, run_unittest, gc_collect
from test_ttk.support import AbstractTkTest

requires('gui')

fontname = "TkDefaultFont"

class FontTest(AbstractTkTest, unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        AbstractTkTest.setUpClass.__func__(cls)
        try:
            cls.font = font.Font(root=cls.root, name=fontname, exists=True)
        except tkinter.TclError:
            cls.font = font.Font(root=cls.root, name=fontname, exists=False)

    def test_configure(self):
        options = self.font.configure()
        self.assertGreaterEqual(set(options),
            {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'})
        for key in options:
            self.assertEqual(self.font.cget(key), options[key])
            self.assertEqual(self.font[key], options[key])
        for key in 'family', 'weight', 'slant':
            self.assertIsInstance(options[key], str)
            self.assertIsInstance(self.font.cget(key), str)
            self.assertIsInstance(self.font[key], str)
        sizetype = int if self.wantobjects else str
        for key in 'size', 'underline', 'overstrike':
            self.assertIsInstance(options[key], sizetype)
            self.assertIsInstance(self.font.cget(key), sizetype)
            self.assertIsInstance(self.font[key], sizetype)

    def test_unicode_family(self):
        family = u'MS \u30b4\u30b7\u30c3\u30af'
        try:
            f = font.Font(root=self.root, family=family, exists=True)
        except tkinter.TclError:
            f = font.Font(root=self.root, family=family, exists=False)
        self.assertEqual(f.cget('family'), family)
        del f
        gc_collect()

    def test_actual(self):
        options = self.font.actual()
        self.assertGreaterEqual(set(options),
            {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'})
        for key in options:
            self.assertEqual(self.font.actual(key), options[key])
        for key in 'family', 'weight', 'slant':
            self.assertIsInstance(options[key], str)
            self.assertIsInstance(self.font.actual(key), str)
        sizetype = int if self.wantobjects else str
        for key in 'size', 'underline', 'overstrike':
            self.assertIsInstance(options[key], sizetype)
            self.assertIsInstance(self.font.actual(key), sizetype)

    def test_name(self):
        self.assertEqual(self.font.name, fontname)
        self.assertEqual(str(self.font), fontname)

    def test_eq(self):
        font1 = font.Font(root=self.root, name=fontname, exists=True)
        font2 = font.Font(root=self.root, name=fontname, exists=True)
        self.assertIsNot(font1, font2)
        self.assertEqual(font1, font2)
        self.assertNotEqual(font1, font1.copy())
        self.assertNotEqual(font1, 0)
        self.assertNotIn(font1, [0])

    def test_measure(self):
        self.assertIsInstance(self.font.measure('abc'), int)

    def test_metrics(self):
        metrics = self.font.metrics()
        self.assertGreaterEqual(set(metrics),
            {'ascent', 'descent', 'linespace', 'fixed'})
        for key in metrics:
            self.assertEqual(self.font.metrics(key), metrics[key])
            self.assertIsInstance(metrics[key], int)
            self.assertIsInstance(self.font.metrics(key), int)

    def test_families(self):
        families = font.families(self.root)
        self.assertIsInstance(families, tuple)
        self.assertTrue(families)
        for family in families:
            self.assertIsInstance(family, (str, unicode))
            self.assertTrue(family)

    def test_names(self):
        names = font.names(self.root)
        self.assertIsInstance(names, tuple)
        self.assertTrue(names)
        for name in names:
            self.assertIsInstance(name, (str, unicode))
            self.assertTrue(name)
        self.assertIn(fontname, names)

tests_gui = (FontTest, )

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK(/�Z�3,O'>'>test_tkinter/test_images.pyonu�[����
zfc@s�ddlZddlZddlZddljZddlmZm	Z	ej
d�deejfd��YZdeejfd��YZ
deejfd	��YZee
efZed
kr�eje�ndS(i����N(tAbstractTkTesttrequires_tcltguitMiscTestcBseZd�Zd�ZRS(cCsC|jj�}|j|t�|jd|�|jd|�dS(Ntphototbitmap(troottimage_typestassertIsInstancettupletassertIn(tselfR((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_image_typesscCs#|jj�}|j|t�dS(N(Rtimage_namesRR	(RR
((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_image_namess(t__name__t
__module__RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR
s	tBitmapImageTestcBsVeZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
RS(cCs,tjj|�tjddd�|_dS(Ns
python.xbmtsubdirt
imghdrdata(Rt
setUpClasst__func__tsupporttfindfilettestfile(tcls((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRsc
Cs�tjdd|jddddd|j�}|jt|�d�|j|j�d�|j|j�d	�|j|j�d	�|j	d|jj
��~|jd|jj
��dS(
Ns::img::testtmastert
foregroundtyellowt
backgroundtbluetfileRi(ttkintertBitmapImageRRtassertEqualtstrttypetwidththeightR
R
tassertNotIn(Rtimage((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_filescCs�t|jd��}|j�}WdQXtjdd|jddddd|�}|jt|�d�|j|j�d	�|j|j	�d
�|j|j
�d
�|jd|jj��~|j
d|jj��dS(Ntrbs::img::testRRRRRtdataRi(topenRtreadR R!RR"R#R$R%R&R
R
R'(RtfR+R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_data*s	cCs0|j|t�|j|jj|�|�dS(N(RR#R"Rt	splitlist(Rtactualtexpected((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytassertEqualStrList8scCs�tjdd|j�}|j|dd�t|jd��}|j�}WdQX|jd|�|j|ddddd|f�|j|j	�d�|j|j
�d�|j|d	d
�|jd	|�|j|d	dddd|f�dS(Ns::img::testRR+s-data {} {} {} {}R*s-datatitmaskdatas-maskdata {} {} {} {}s	-maskdata(R R!RR"R,RR-t	configureR3R%R&(RR(R.R+((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_data<s

cCs�tjdd|j�}|j|dd�|jd|j�|j|ddddd|jf�|j|j�d�|j|j�d�|j|dd	�|jd|j�|j|dd
ddd|jf�dS(Ns::img::testRRs-file {} {} {} {}s-fileR4itmaskfiles-maskfile {} {} {} {}s	-maskfile(	R R!RR"R6RR3R%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_fileLs

cCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRRs-background {} {} {} {}Rs-background {} {} {} blue(R R!RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_backgroundZscCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRRs!-foreground {} {} #000000 #000000Rs -foreground {} {} #000000 yellow(R R!RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_foreground`s

(RRtclassmethodRR)R/R3R7R9R:R;(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRs						tPhotoImageTestcBseZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd	�Zd
�Z
edd�d
��Zedd�d��Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tjj|�tjddd�|_dS(Ns
python.gifRR(RRRRRR(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRkscCstjdd|jd|j�S(Ns::img::testRR(R t
PhotoImageRR(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcreatepscGs-tjdkr|jr|Stj|�SdS(Ng333333!@(R t	TkVersiontwantobjectst_join(Rtargs((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	colorlisttscCs�tjd|dd�}tjdd|jd|�}|jt|�d�|j|j�d�|j|j�d�|j|j	�d�|j|d	d
�|j|d|�|j
d|jj��~|jd|jj��dS(Nspython.RRs::img::testRRRiR+R4(
RRR R>RR"R#R$R%R&R
R
R'(RtextRR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcheck_create_from_filezs	cCs,tjd|dd�}t|d��}|j�}WdQXtjdd|jd|�}|jt|�d�|j|j	�d�|j|j
�d	�|j|j�d	�|j|d|jr�|n|j
d
��|j|dd�|jd|jj��~|jd|jj��dS(
Nspython.RRR*s::img::testRR+Ritlatin1RR4(RRR,R-R R>RR"R#R$R%R&RAtdecodeR
R
R'(RRERR.R+R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcheck_create_from_data�s	cCs|jd�dS(Ntppm(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_ppm_file�scCs|jd�dS(NRJ(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_ppm_data�scCs|jd�dS(Ntpgm(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_pgm_file�scCs|jd�dS(NRM(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_pgm_data�scCs|jd�dS(Ntgif(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_gif_file�scCs|jd�dS(NRP(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_gif_data�siicCs|jd�dS(Ntpng(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_png_file�scCs|jd�dS(NRS(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_png_data�scCs�tjdd|j�}|j|dd�t|jd��}|j�}WdQX|jd|�|j|d|jr|n|j	d��|j|j
�d�|j|j�d�dS(Ns::img::testRR+R4R*RGi(R R>RR"R,RR-R6RARHR%R&(RR(R.R+((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR7�scCs�tjdd|j�}|j|dd�|jd|jdd�|j|d|jradnd�|j|j�d�|j|j�d�dS(	Ns::img::testRtformatR4RRPi(RP(	R R>RR"R6RRAR%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_format�scCs�tjdd|j�}|j|dd�|jd|j�|j|d|j�|j|j�d�|j|j�d�dS(Ns::img::testRRR4i(R R>RR"R6RR%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR9�scCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRtgammas1.0g@s2.0(R R>RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_gamma�scCs�tjdd|j�}|j|dd�|j|dd�|jdd�|jdd�|j|dd�|j|dd	�|j|j�d�|j|j�d�dS(
Ns::img::testRR%t0R&ii
t20t10(R R>RR"R6R%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_width_height�scCsxtjdd|j�}|j|dd�|jdd�|j|dd�|jdd�|j|dd�dS(Ns::img::testRtpaletteR4it256s3/4/2(R R>RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_palette�scCsq|j�}|j�|j|j�d�|j|j�d�|j|jdd�|jddd��dS(Niiii(R?tblankR"R%R&tgetRD(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt
test_blank�s

cCsp|j�}|j�}|j|j�d�|j|j�d�|j|jdd�|jdd��dS(Niii(R?tcopyR"R%R&Rb(RR(timage2((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	test_copy�s
cCs�|j�}|jdd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|jd�}|j|j�d�|j|j�d�|j|jdd�|jdd��dS(Niiiii(R?t	subsampleR"R%R&Rb(RR(Re((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_subsample�s(cCs)|j�}|jdd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|j|jd	d
�|jdd��|jd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|j|jd	d�|jdd��dS(
Niii i0iiiii	iii
(R?tzoomR"R%R&Rb(RR(Re((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	test_zooms(((cCs�|j�}|jddd�|j|jdd�|jddd��|j|jdd�|jdtjdkr}d	ndd��|j|jdd
�|jddd��|j|jdd
�|jddd��|jddf�|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��dS(Ns{red green} {blue yellow}ttoiii�iig333333!@i�is#f00s#00ff00s
#000000fffs
#ffffffff0000i(ii(s#f00s#00ff00(s
#000000fffs
#ffffffff0000(R?tputR"RbRDR R@(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_puts+
+++++cCs|j�}|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��|jtj|jdd�|jtj|jdd�|jtj|jd	d�|jtj|jdd	�dS(
Niii>iti�iii����i(R?R"RbRDtassertRaisesR tTclError(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_get s+++c	Cs�|j�}|jtjtj�|jtj�tjdd|jdddtj�}|j	t
|�d�|j	|j�d�|j	|j�d�|j	|j
�d�|j	|jdd�|jdd��|j	|jd	d
�|jd	d
��|jtjdddd�tjdd|jdddtj�}|j	t
|�d�|j	|j�d�|j	|j�d�|j	|j
�d�|j	|jdd�|jd
d��|j	|jdd�|jdd
��dS(Ns::img::test2RRVRJRRiiiiRPtfrom_coordsiii	s::img::test3iiii(iiii	(R?t
addCleanupRtunlinktTESTFNtwriteR R>RR"R#R$R%R&Rb(RR(Retimage3((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt
test_write*s,((((RRR<RR?RDRFRIRKRLRNRORQRRRRTRUR7RWR9RYR]R`RcRfRhRjRmRpRw(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR=is4																							
t__main__(tunittesttTkinterR tttkttest.test_supportttest_supportRttest_ttk.supportRRtrequirestTestCaseRRR=t	tests_guiRtrun_unittest(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt<module>s

R�PK(/�Z�l��test_tkinter/test_widgets.pyonu�[����
zfc@sTddlZddlZddlmZddlZddlZddlmZmZddl	m
Z
mZmZm
Z
ddlmZmZmZmZmZmZmZmZmZmZed�deefd��YZee�d	eejfd
��Y�Zee�deejfd��Y�Zee�d
eejfd��Y�Zdeefd��YZee�deejfd��Y�Zee�deejfd��Y�Z ee�deejfd��Y�Z!ee�deejfd��Y�Z"ee�deejfd��Y�Z#de#ejfd��YZ$eee�deejfd��Y�Z%ee�de%ejfd ��Y�Z&ee�d!eejfd"��Y�Z'eee�d#eejfd$��Y�Z(eee�d%eejfd&��Y�Z)eee�d'eejfd(��Y�Z*eee�d)eejfd*��Y�Z+ee�d+eejfd,��Y�Z,ee�d-eejfd.��Y�Z-eee�d/eejfd0��Y�Z.e e(e!e%eeee)e#e-e.e$e,e"e*e+e&e'egZ/e0d1krPee/�ndS(2i����N(tTclError(trequirestrun_unittest(ttcl_versiontrequires_tcltget_tk_patchlevelt	widget_eq(
tadd_standard_optionstnoconvtnoconv_metht	int_roundtpixels_roundtAbstractWidgetTesttStandardOptionsTeststIntegerSizeTeststPixelSizeTeststsetUpModuletguitAbstractToplevelTestcBs2eZeZd�Zd�Zd�Zd�ZRS(cCso|j�}|j|d|jjj��|j|dddd�|jdd�}|j|dd�dS(NtclasstFooterrmsgs2can't modify -class option after widget is createdtclass_(tcreatetassertEqualt	__class__t__name__ttitletcheckInvalidParam(tselftwidgettwidget2((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_classs
cCsc|j�}|j|dd�|j|dddd�|jdd�}|j|dd�dS(NtcolormapttnewRs5can't modify -colormap option after widget is created(RRR(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_colormapscCs�|j�}|j|d|jr(dnd�|j|dddd�|jdt�}|j|d|jrvdnd�dS(Nt	containerit0iRs6can't modify -container option after widget is createdt1(RRtwantobjectsRtTrue(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_container's#cCsc|j�}|j|dd�|j|dddd�|jdd�}|j|dd�dS(NtvisualR"tdefaultRs3can't modify -visual option after widget is created(RRR(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_visual/s(Rt
__module__R	t_conv_pad_pixelsR R$R*R-(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRs
				tToplevelTestcBs2eZdZd�Zd�Zd�Zd�ZRS(t
backgroundtborderwidthRR!R%tcursortheightthighlightbackgroundthighlightcolorthighlightthicknesstmenutpadxtpadytrelieftscreent	takefocustuseR+twidthcKstj|j|�S(N(ttkintertTopleveltroot(Rtkwargs((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRBscCsN|j�}tj|j�}|j|d|dt�|j|dd�dS(NR8teqR"(RR@tMenuRBt
checkParamR(RRR8((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_menuEscCs�|j�}|j|dd�ytjd}Wntk
rQ|jd�nX|j|d|dd�|jd|�}|j|d|�dS(NR<R"tDISPLAYsNo $DISPLAY set.Rs3can't modify -screen option after widget is created(RRtostenvirontKeyErrortskipTestR(RRtdisplayR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_screenKs
cCsl|j�}|j|dd�|jdt�}d|j�}|jd|�}|j|d|�dS(NR>R"R%s%#x(RRR)twinfo_id(RRtparenttwidR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_useWs(R1R2RR!R%R3R4R5R6R7R8R9R:R;R<R=R>R+R?(RR.tOPTIONSRRGRNRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR08s			t	FrameTestcBseZdZd�ZRS(R1R2RR!R%R3R4R5R6R7R9R:R;R=R+R?cKstj|j|�S(N(R@tFrameRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRjs(R1R2RR!R%R3R4R5R6R7R9R:R;R=R+R?(RR.RSR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRTas
tLabelFrameTestcBs)eZdZd�Zd�Zd�ZRS(R1R2RR!R%R3tfontt
foregroundR4R5R6R7tlabelanchortlabelwidgetR9R:R;R=ttextR+R?cKstj|j|�S(N(R@t
LabelFrameRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRyscCsW|j�}|j|ddddddddd	d
ddd
�|j|dd�dS(NRYtetentestntnetnwtstsetswtwtwntwstcenter(RtcheckEnumParamR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_labelanchor|s
cCsQ|j�}tj|jdddd�}|j|d|dd�|j�dS(NR[tMupptnametfooRZtexpecteds.foo(RR@tLabelRBRFtdestroy(RRtlabel((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_labelwidget�s(R1R2RR!R%R3RWRXR4R5R6R7RYRZR9R:R;R=R[R+R?(RR.RSRRkRs(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRVns		tAbstractLabelTestcBseZeZd�ZRS(c	Cs2|j�}|j|ddddddd�dS(NR7ig�������?g������@ii����t10p(RtcheckPixelsParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_highlightthickness�s(RR.R	t_conv_pixelsRw(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRt�st	LabelTestcBseZdZd�ZRS(tactivebackgroundtactiveforegroundtanchorR1tbitmapR2tcompoundR3tdisabledforegroundRWRXR4R5R6R7timagetjustifyR9R:R;tstateR=R[ttextvariablet	underlineR?t
wraplengthcKstj|j|�S(N(R@RpRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s(RzR{R|R1R}R2R~R3RRWRXR4R5R6R7R�R�R9R:R;R�R=R[R�R�R?R�(RR.RSR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRy�st
ButtonTestc Bs eZd"Zd �Zd!�ZRS(#RzR{R|R1R}R2tcommandR~R3R,RRWRXR4R5R6R7R�R�t
overreliefR9R:R;trepeatdelaytrepeatintervalR�R=R[R�R�R?R�cKstj|j|�S(N(R@tButtonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR,tactivetdisabledtnormal(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_default�s( RzR{R|R1R}R2R�R~R3R,RRWRXR4R5R6R7R�R�R�R9R:R;R�R�R�R=R[R�R�R?R�(RR.RSRR�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s	tCheckbuttonTestc&Bs)eZd)Zd&�Zd'�Zd(�ZRS(*RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�tindicatoronR�t	offrelieftoffvaluetonvalueR�R9R:R;tselectcolortselectimageR�R=R[R�t
tristateimaget
tristatevalueR�tvariableR?R�cKstj|j|�S(N(R@tCheckbuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RtcheckParams(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_offvalue�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_onvalue�s(&RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�R�R?R�(RR.RSRR�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s		tRadiobuttonTestc%Bs eZd'Zd%�Zd&�ZRS((RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�tvalueR�R?R�cKstj|j|�S(N(R@tRadiobuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_value�s(%RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�R�R�R?R�(RR.RSRR�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s	tMenubuttonTestcBs�eZd(Zee�Zd�Zd�Zd �Ze	j
jZ
ej
ejd!kd"�d#��Zd$�Zd%�Zd&�Zd'�ZRS()RzR{R|R1R}R2R~R3t	directionRRWRXR4R5R6R7R�R�R�R8R9R:R;R�R=R[R�R�R?R�cKstj|j|�S(N(R@t
MenubuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR�tabovetbelowtflushtlefttright(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_direction�scCs/|j�}|j|dddddt�dS(NR4idi����itconv(RtcheckIntegerParamtstr(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_heightstdarwins"crashes with Cocoa Tk (issue19733)c	Cs�|j�}tjd|jdd�}|j|d|dt�d}|jtj��}d|d<WdQX|dk	r�|j	t|j
�|�n|jtj��}|jidd6�WdQX|dk	r�|j	t|j
�|�ndS(NtmasterRmtimage1R�R�simage "spam" doesn't existtspam(RR@t
PhotoImageRBRFR�tassertRaisesRtNoneRt	exceptiont	configure(RRR�Rtcm((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_image	scCsH|j�}tj|dd�}|j|d|dt�|j�dS(NRmR8RD(RR@RERFRRq(RRR8((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRGscCsE|j�}|j|ddddd�|j|dddd�dS(	NR9ig������@gffffff@t12mi����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_padxscCsE|j�}|j|ddddd�|j|dddd�dS(	NR:ig������@gffffff@R�i����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_pady$scCs/|j�}|j|dddddt�dS(NR?i�in���iR�(RR�R�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_width)s(RzR{R|R1R}R2R~R3R�RRWRXR4R5R6R7R�R�R�R8R9R:R;R�R=R[R�R�R?R�(RR.RStstaticmethodRRxRR�R�R
Rwtim_functunittesttskipIftsystplatformR�RGR�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s(						tOptionMenuTestcBseZddd�ZRS(tbtatccKstj|jd|||�S(N(R@t
OptionMenuRBR�(RR,tvaluesRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR0s(R�R�R�(RR.R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�.st	EntryTestcBsheZd)Zd�Zd �Zd!�Zd"�Zd#�Zd$�Zd%�Z	d&�Z
d'�Zd(�ZRS(*R1R2R3tdisabledbackgroundRtexportselectionRWRXR5R6R7tinsertbackgroundtinsertborderwidtht
insertofftimetinsertontimetinsertwidthtinvalidcommandR�treadonlybackgroundR;tselectbackgroundtselectborderwidthtselectforegroundtshowR�R=R�tvalidatetvalidatecommandR?txscrollcommandcKstj|j|�S(N(R@tEntryRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRCscCs |j�}|j|d�dS(NR�(RtcheckColorParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_disabledbackgroundFsc	CsQ|jdd�}|j|ddddddd	�|j|dd
dd
�dS(NR�idR�ig�������?g������@ii����Rui<Roii2(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertborderwidthJscCs�|j�}|j|dddd�|j|dddd�|j|dddd�td	�d
kr�|j|dd	dd�n|j|dd	dd�dS(NR�g�������?g������@Rug�������?Roii����g�������?ii(RRvRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertwidthQscCs0|j�}|j|d�|j|d�dS(NR�tinvcmd(RtcheckCommandParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_invalidcommand[scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_readonlybackground`scCsI|j�}|j|dd�|j|dd�|j|dd�dS(NR�t*R"t (RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_showdscCs)|j�}|j|dddd�dS(NR�R�R�treadonly(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_statejsc	Cs2|j�}|j|ddddddd�dS(NR�talltkeytfocustfocusintfocusouttnone(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_validateoscCs0|j�}|j|d�|j|d�dS(NR�tvcmd(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_validatecommandts(R1R2R3R�RR�RWRXR5R6R7R�R�R�R�R�R�R�R�R;R�R�R�R�R�R=R�R�R�R?R�(
RR.RSRR�R�R�R�R�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�4s(				
					tSpinboxTestc,Bs�eZd9Zd,�Zd:Zd-�Zd.�Zd/�Zd0�Z	d1�Z
d2�Zd3�Zd4�Z
d5�Zd6�Zd7�Zd8�ZRS(;RzR1R2tbuttonbackgroundtbuttoncursortbuttondownrelieftbuttonupreliefR�R3R�RR�RWRXtformattfromR5R6R7t	incrementR�R�R�R�R�R�R�R;R�R�R�R�R�R�R�R=R�ttoR�R�R�R?twrapR�cKstj|j|�S(N(R@tSpinboxRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttonbackground�scCs |j�}|j|d�dS(NR�(RtcheckCursorParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttoncursor�scCs |j�}|j|d�dS(NR�(RtcheckReliefParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttondownrelief�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttonuprelief�scCs�|j�}|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd	�|j|dd
�|j|dd�|j|dd�|j|dd
�dS(NR�s%2fs%2.2fs%.2fs%2.fs%2e-1fs2.2s%2.-2fs%-2.02fs% 2.02fs	% -2.200fs%09.200fs%d(RRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_format�scCsU|j�}|j|dd�|j|dddd�|j|dddd	�dS(
NR�gY@R�i����gffffff$@gffffff'@i�Rs*-to value must be greater than -from value(RRFtcheckFloatParamR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_from�s
cCs/|j�}|j|dddddd�dS(NR�i����igffffff$@g������)@i(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_increment�scCsU|j�}|j|dd�|j|dddd�|j|dddd	�dS(
NR�gY�R�i����gffffff$@gffffff'@i8���Rs*-to value must be greater than -from value(RRFRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_to�s
cCs||j�}|j|dd�|j|dd�|j|dd
dd�|j|dddd�|j|dd�dS(NR�R"smon tue wed thurtmonttuetwedtthurRoi*g��Q�	@s
any strings42 3.14 {} {any string}(RR	R
R(i*g��Q�	@R"s
any string(RRRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_values�scCs |j�}|j|d�dS(NR�(RtcheckBooleanParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_wrap�scCs�|j�}|j|jd��|jtj|jd�|jtj|jd�|jt|j�|jt|jdd�dS(Nitnoindexi(RtassertIsBoundingBoxtbboxR�R@RR�t	TypeError(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_bbox�scCsl|j�}|j|j�d�|jd�|j|j�d�|jd�|j|j�d�dS(NR�tbuttonupt
buttondown(RRtselection_element(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selection_element�s

(,RzR1R2R�R�R�R�R�R3R�RR�RWRXR�R�R5R6R7R�R�R�R�R�R�R�R�R;R�R�R�R�R�R�R�R=R�R�R�R�R�R?R�R�N(RR.RSRR�R�R�R�RRRRRRRRRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�zs8												tTextTestc)Bs1eZd@ZedAkr!eZnd+�Zd,�Zed)d*�d-��Z	ed)d*�d.��Z
d/�Zd0�Zed)d*�d1��Z
ed)d2�d3��Zd4�Zd5�Zd6�Zd7�Zed)d*�d8��Zd9�Zd:�Zed)d*�d;��Zd<�Zd=�Zd>�Zd?�ZRS(BtautoseparatorsR1tblockcursorR2R3tendlineR�RWRXR4R5R6R7tinactiveselectbackgroundR�R�R�R�tinsertunfocussedR�tmaxundoR9R:R;R�R�R�tsetgridtspacing1tspacing2tspacing3t	startlineR�ttabsttabstyleR=tundoR?R�R�tyscrollcommandiicKstj|j|�S(N(R@tTextRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_autoseparators�scCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_blockcursor�scCs�|j�}djd�td�D��}|jd|�|j|dddd�|j|dd	dd�|j|dd
dd�|j|dd
�|j|dd�|j|dddd�dS(Ns
css|]}dVqdS(sLine %dN((t.0ti((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>sidtendRi�RoR"i����R�Rsexpected integer but got "spam"i2R#ii
s1-startline must be less than or equal to -endline(RtjointrangetinsertRFR(RRR[((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_endlinescCs^|j�}|j|ddddd�|j|dddd�|j|dd	dd�dS(
NR4idg�����LY@gfffff�Y@t3ci����Roii(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NRiii����(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_maxundoscCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_inactiveselectbackgroundsicCs)|j�}|j|dddd�dS(NRthollowR�tsolid(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertunfocussedsc
Cs>|j�}|j|ddddddtdtd
k�dS(NR�g�������?g������@i����RuR�t	keep_origii(ii(RRvRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selectborderwidth$scCsE|j�}|j|ddddd�|j|dddd�dS(	NR igffffff5@g������6@s0.5ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing1*scCsE|j�}|j|ddddd�|j|dddd�dS(	NR!ig������@gffffff@s0.1ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing2/scCsE|j�}|j|ddddd�|j|dddd�dS(	NR"igffffff5@g������6@s0.5ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing34scCs�|j�}djd�td�D��}|jd|�|j|dddd�|j|dd	dd�|j|dd
dd�|j|dd
�|j|dd�|j|dddd�dS(Ns
css|]}dVqdS(sLine %dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr><sidR-R#i�RoR"i����R�Rsexpected integer but got "spam"i
Ri2iFs1-startline must be less than or equal to -endline(RR.R/R0RFR(RRR[((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_startline9scCsK|j�}tdkr1|j|ddd�n|j|ddd�dS(NiiR�R�R�(ii(RRR�Rj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�Gsc
Cs�|j�}t�dkr7|j|ddd	d�n|j|dd�|j|ddd	d�|j|dd
d	d�|j|dddddtdk�dS(NiiiR$gffffff$@g33333�4@t1it2iRos10.2s20.7s10.2 20.7 1i 2is2c left 4c 6c centert2cR�t4ct6cRiR�Rsbad screen distance "spam"R8(iii(gffffff$@g33333�4@R>R?(s10.2s20.7R>R?(gffffff$@g33333�4@R>R?(s10.2s20.7R>R?(R@R�RARBRi(ii(RRRFRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_tabsNs
cCs&|j�}|j|ddd�dS(NR%ttabulart
wordprocessor(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_tabstyle]scCs |j�}|j|d�dS(NR&(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_undobscCsU|j�}|j|dd�|j|dddd�|j|dddd�dS(NR?i�in���Roii(RR�RF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�fscCsQ|j�}tdkr4|j|dddd�n|j|dddd�dS(NiiR�tcharR�tword(ii(RRR�Rj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRlscCs�|j�}|j|jd��|j|jd��|jtj|jd�|jtj|jd�|jtj|j�|jtj|jdd�dS(Ns1.1R-R(RRRtassertIsNoneR�R@RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRss()RR1RR2R3RR�RWRXR4R5R6R7RR�R�R�R�RR�RR9R:R;R�R�R�RR R!R"R#R�R$R%R=R&R?R�R�R'(ii(RR.RSRR)t
_stringifyRR)RR*R1R�R3R4R7R9R:R;R<R=R�RCRFRGR�RR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�sB														t
CanvasTestcBsheZd#Zee�ZeZd�Zd�Z	d�Z
d�Zd�Zd �Z
d!�Zd"�ZRS($R1R2tcloseenoughtconfineR3R4R5R6R7R�R�R�R�R�toffsetR;tscrollregionR�R�R�R�R=R�txscrollincrementR'tyscrollincrementR?cKstj|j|�S(N(R@tCanvasRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�sc	Cs2|j�}|j|ddddddt�dS(NRMig333333@g������@i����R�(RRtfloat(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_closeenough�scCs |j�}|j|d�dS(NRN(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_confine�scCs�|j�}|j|dd�|j|dddddddd	d
d�|j|dd�|j|dd
�|j|dd�dS(NROs0,0R`RaR]RdRcReRfRbRis10,20s#5,6R�(RRR�RFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_offset�scCs�|j�}|j|dd�|j|dddd�|j|dd�|j|ddd	d
�|j|dd�|j|dd
�|j|dd�dS(NRPs0 0 200 150ii�i�RoR"R�Rsbad scrollRegion "spam"(iii�i�(iii�R�(iii�(iii�i�i(RRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_scrollregion�scCs,|j�}|j|ddddd�dS(NR�R�R�Rs0bad state value "{}": must be normal or disabled(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sc	Cs2|j�}|j|ddddddd�dS(NRQi(ig������D@g������E@i���s0.5i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_xscrollincrement�sc	Cs2|j�}|j|ddddddd�dS(NRRi
igffffff&@g333333+@i����s0.1i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_yscrollincrement�s(R1R2RMRNR3R4R5R6R7R�R�R�R�R�ROR;RPR�R�R�R�R=R�RQR'RRR?(RR.RSR�R
RxR)RKRRURVRWRXR�RYRZ(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRL}s(								tListboxTestcBs�eZd,Zd�Zd�Zeddd�ejj�Zd�Z	d�Z
d �Zd!�Zd"�Z
d#�Zd$�Zd%�Zd&�Zd'�Zd(�Zd)�Zd*�Zd+�ZRS(-tactivestyleR1R2R3RR�RWRXR4R5R6R7R�tlistvariableR;R�R�R�t
selectmodeRR�R=R?R�R'cKstj|j|�S(N(R@tListboxRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR\tdotboxR�R�(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_activestyle�siiicCs5|j�}tj|j�}|j|d|�dS(NR](RR@t	DoubleVarRBtcheckVariableParam(RRtvar((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_listvariable�scCs\|j�}|j|dd�|j|dd�|j|dd�|j|dd�dS(NR^tsingletbrowsetmultipletextended(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selectmode�s
cCs&|j�}|j|ddd�dS(NR�R�R�(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sc
Cs�|j�}|jtd��|jd�WdQXdj�}|jd|�x-t|�D]\}}|j|d|�q[W|jt��|j�WdQX|jtd��|jd�WdQX|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|jd�}|j
|t�x�|j�D]s\}}|j
t|�d�t|�d
krD|j	||jd|��|j	|d|jd|��qDqDWdS(Nsitem number "0" out of rangeis)red orange yellow green blue white violetR-R1sbad listbox index "red"tredt
BackgroundR"tviolets@0,0iii(R1R1RlR"Rk(R1R1RlR"Rm(R1R1RlR"Rk(ii(RtassertRaisesRegexpRt
itemconfiguretsplitR0t	enumerateR�RRtassertIsInstancetdicttitemstassertIntlentitemcget(RRtcolorsR,tcolortdtktv((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure�s0c	Cs�|j�}|jddddd�|jdi||6�|j|jd|�d|�|j|jd|�|�|jtd��|jdid	|6�WdQXdS(
NR-R�R�R�Rziisunknown color name "spam"R�(RR0RoRRwRnR(RRmR�R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_itemconfigures cCs|jdd�dS(NR1s#ff0000(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_backgroundscCs|jdd�dS(Ntbgs#ff0000(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_bgscCs|jdd�dS(Ntfgs#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_fgscCs|jdd�dS(NRXs#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_foregroundscCs|jdd�dS(NR�s#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt#test_itemconfigure_selectbackgroundscCs|jdd�dS(NR�s#654321(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt#test_itemconfigure_selectforegroundscCs�|j�}|jdd�td�D��|j�|j|jd��|j|jd��|j|jd��|jt|jd�|jt|jd�|jt
|j�|jt
|jdd�dS(Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>sii����i
Ri(RR0R/tpackRRRJR�RR�R(Rtlb((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_boxs 
cCs�|j�}|jdd�td�D��|jdtj�|jdd�|jd�|j|j�d�|j	t
|jd�dS(	Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>+siiiii(iiii(RR0R/tselection_clearR@tENDt
selection_setRtcurselectionR�R(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_curselection)s 
cCs�|j�}|jdd�td�D��|j|jd�d�|j|jd�d�|j|jd�d�|j|jd�d	�|j|jd
�d	�|j|jdd�d�|j|jdd�d�|j|jdd�d�|j|jdd�d�|jt|jd�|jt|jd�|jt|j�|jt|jdd�|jt|jddd�|jt|jd�dS(Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>4sitel0itel3R-tel7R"i����itel4tel5tel6Riig333333@(R�R�R�(R�R�R�((R�(	RR0R/RtgetR�RR�R(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_get2s" (R\R1R2R3RR�RWRXR4R5R6R7R�R]R;R�R�R�R^RR�R=R?R�R'(RR.RSRRaRR
ttest_justifyR�ReRjR�R}R~RR�R�R�R�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR[�s2																	t	ScaleTestcBs�eZd+ZdZd�Zd �Zd!�Zd"�Zd#�Zd$�Z	d%�Z
d&�Zd'�Zd(�Z
d)�Zd*�ZRS(,RzR1tbigincrementR2R�R3tdigitsRWRXR�R5R6R7RrtlengthtorientR;R�R�t
resolutiont	showvaluetsliderlengthtsliderreliefR�R=ttickintervalR�ttroughcolorR�R?tverticalcKstj|j|�S(N(R@tScaleRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRSscCs)|j�}|j|dddd�dS(NR�g������(@g������7@i����(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_bigincrementVscCs&|j�}|j|ddd�dS(NR�ii(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_digitsZscCs/|j�}|j|dddddt�dS(NR�idg������-@g333333.@R�(RRtround(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR^scCs6|j�}|j|dd�|j|dd�dS(NRrs
any stringR"(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_labelbscCs,|j�}|j|ddddd�dS(NR�i�gffffff`@g33333�`@t5i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_lengthgscCs,|j�}|j|ddddd�dS(NR�g������@ig������@i����(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_resolutionkscCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_showvalueoscCs/|j�}|j|dddddd�dS(NR�i
gffffff&@g333333/@i����t3m(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sliderlengthsscCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sliderreliefxsc	CsQ|j�}|j|ddddddt�|j|dddd	dt�dS(
NR�ig333333@gffffff@iR�i����Roi(RRR�RF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tickinterval|s
c	Cs2|j�}|j|ddddddt�dS(NR�i,g������-@g333333.@i����R�(RRR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s(RzR1R�R2R�R3R�RWRXR�R5R6R7RrR�R�R;R�R�R�R�R�R�R�R=R�R�R�R�R?(RR.RStdefault_orientRR�R�RR�R�R�R�R�R�R�R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�Fs(											t
ScrollbarTestcBs\eZdZee�ZeZdZd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(RztactivereliefR1R2R�R3telementborderwidthR5R6R7tjumpR�R;R�R�R=R�R?R�cKstj|j|�S(N(R@t	ScrollbarRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_activerelief�scCs,|j�}|j|ddddd�dS(NR�g333333@gffffff@i����t1m(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_elementborderwidth�scCs,|j�}|j|ddddd�dS(NR�R�t
horizontalRs4bad orientation "{}": must be vertical or horizontal(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_orient�scCsg|j�}xdD]}|j|�qW|jd�|jt|j�|jt|jdd�dS(Ntarrow1tslidertarrow2R"(R�R�R�(RtactivateR�R(RtsbR]((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_activate�s

cCs�|j�}|jdd�|j|j�d�|jt|jdd�|jt|jdd�|jt|jdd�|jt|jd�|jt|jddd�dS(	Ng�������?g�������?tabctdefg333333�?gffffff�?g�������?(g�������?g�������?(RtsetRR�R�RR�(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_set�s(RzR�R1R2R�R3R�R5R6R7R�R�R;R�R�R=R�R?(RR.RSR�R
RxR)RKR�RR�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s 					tPanedWindowTestcBsgeZd2ZdZd�Zd�Zd�Zd�Zd�Ze	ddd�d��Z
e	ddd�d��Ze	ddd�d��Zd�Z
d�Zd �Zd!�Zd"�Zd#�Zd$�Zd%�Zed&�Zd'�Zd(�Zd)�Zd*�Ze	dd�d+��Zd,�Zd-�Zd.�Zd/�Ze	dd�d0��Z d1�Z!RS(3R1R2R3t	handlepadt
handlesizeR4topaqueresizeR�tproxybackgroundtproxyborderwidthtproxyreliefR;t
sashcursortsashpadt
sashrelieft	sashwidtht
showhandleR?R�cKstj|j|�S(N(R@tPanedWindowRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR�ig������@gffffff@i����R�(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_handlepad�sc
Cs5|j�}|j|dddddddt�dS(NR�ig������"@g333333%@i����t2mR�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_handlesize�scCs8|j�}|j|ddddddddt�dS(	NR4idg�����LY@gfffff�Y@i����iR>R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s!cCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_opaqueresize�siiicCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxybackground�scCs8|j�}|j|ddddddddt�dS(	NR�ig�������?g333333@ii����RuR�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxyborderwidth�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxyrelief�scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashcursor�scCs/|j�}|j|dddddd�dS(NR�ig�������?g������@i����R�(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashpad�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashrelief�sc
Cs5|j�}|j|dddddddt�dS(NR�i
g333333&@g333333/@i����R�R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashwidth�scCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_showhandle�scCs8|j�}|j|ddddddddt�dS(	NR?i�gfffff6y@g�����Iy@in���iR�R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s!cCsQ|j�}tj|�}tj|�}|j|�|j|�|||fS(N(RR@R�tadd(RtpR�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcreate2s

cCs�|j�\}}}|jt|j�|j|�}|j|t�xl|j�D]^\}}|jt|�d�|j||j||��|j|d|j	||��qTWdS(Nii(
R�R�Rt
paneconfigureRrRsRtRRvtpanecget(RR�R�R�RzR{R|((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigurescCs�d�}|js|r(t|�}n|jr@|r@t}n|j|i||6�|j||j||�d�|�|j||j||��|�dS(NcSs|S(N((tx((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt<lambda>R"i(R(R�R�RR�(RR�R�RmR�Rot	stringifyR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_paneconfigures		&c	Cs4|jt|��|j|id|6�WdQXdS(NtbadValue(RnRR�(RR�R�Rmtmsg((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_paneconfigure_bad$scCsN|j�\}}}|j||d|t|��|j||dd�dS(Ntaftersbad window path name "badValue"(R�R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_after(scCsN|j�\}}}|j||d|t|��|j||dd�dS(Ntbeforesbad window path name "badValue"(R�R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_before.scCsW|j�\}}}|j||ddddt�dk�|j||dd�dS(	NR4i
R�iiisbad screen distance "badValue"(iii(R�R�RR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_height4s
cCsH|j�\}}}|j||dtd�|j||dd�dS(Nthideis)expected boolean value but got "badValue"(R�R�tFalseR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_hide;scCsH|j�\}}}|j||ddd�|j||dd�dS(Ntminsizei
sbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_minsizeBscCsH|j�\}}}|j||ddd�|j||dd�dS(NR9g�������?isbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_padxHscCsH|j�\}}}|j||ddd�|j||dd�dS(NR:g�������?isbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_padyNscCsH|j�\}}}|j||ddd�|j||dd�dS(Ntstickytnsewtnesws[bad stickyness value "badValue": must be a string containing zero or more of n, e, s, and w(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_stickyTscCsH|j�\}}}|j||ddd�|j||dd�dS(NtstretchtalwtalwayssEbad stretch "badValue": must be always, first, last, middle, or never(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_stretch\scCsW|j�\}}}|j||ddddt�dk�|j||dd�dS(	NR?i
R�iiisbad screen distance "badValue"(iii(R�R�RR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_widthds
(R1R2R3R�R�R4R�R�R�R�R�R;R�R�R�R�R�R?("RR.RSR�RR�R�R�R�RR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sH													

								tMenuTestcBseeZdZeZd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
RS(RztactiveborderwidthR{R1R2R3RRWRXtpostcommandR;R�R=ttearoffttearoffcommandRttypecKstj|j|�S(N(R@RERB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRwscCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_postcommandzscCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tearoff~scCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tearoffcommand�scCs#|j�}|j|dd�dS(NRs
any string(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_title�scCs)|j�}|j|dddd�dS(NRR�Rtmenubar(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_type�scCs	|j�}|jdd�|jt|j�|jtd��|jd�WdQX|jd�}|j|t�x�|j	�D]v\}}|j|t
�|j|t�|jt
|�d�|j|d|�|j|jd|�|d�q�W|j�dS(	NRrttestsbad menu entry index "foo"Rniiii(Rtadd_commandR�RtentryconfigureRnRRrRsRtR�ttupleRRvt	entrycgetRq(Rtm1RzR{R|((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure�s$cCsk|j�}|jdd�|j|jdd�d�|jddd�|j|jdd�d�dS(NRrR
itchanged(RRRRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure_label�s
c	Cs�|j�}tj|j�}tj|j�}|jd|dtdtdd�|jt|j	dd��t|��|j
dd|�|jt|j	dd��t|��dS(NR�R�R�RrtNonsensei(RR@t
BooleanVarRBtadd_checkbuttonR)R�RR�RR(RRtv1tv2((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure_variable�s((RzRR{R1R2R3RRWRXRR;R�R=RRRR(RR.RSR	RxRRRR	R
RRRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRls								tMessageTestcBs&eZdZeZd�Zd�ZRS(R|taspectR1R2R3RWRXR5R6R7R�R9R:R;R=R[R�R?cKstj|j|�S(N(R@tMessageRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NRi�ii���(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_aspect�s(R|RR1R2R3RWRXR5R6R7R�R9R:R;R=R[R�R?(RR.RSR	R/RR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s	t__main__(1R�tTkinterR@RRIR�ttest.test_supportRRttest_ttk.supportRRRRtwidget_testsRRR	R
RRR
RRRRtTestCaseR0RTRVRtRyR�R�R�R�R�R�R�RRLR[R�R�R�RRt	tests_guiR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt<module>sl"F
%(	AEh�B�B1�DPK(/�Z�����test_tkinter/test_loadtk.pycnu�[����
zfc@s�ddlZddlZddlZddlmZddlmZmZejd�dej	fd��YZ
e
fZedkr�ej
e�ndS(i����N(ttest_support(tTcltTclErrortguit
TkLoadTestcBs5eZejdejkd�d��Zd�ZRS(tDISPLAYsNo $DISPLAY set.cCsJt�}|jt|j�|j�|jd|j��|j�dS(Ns1x1+0+0(RtassertRaisesRtwinfo_geometrytloadtktassertEqualtdestroy(tselfttcl((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyt
testLoadTks
	
cCs�d}tjjd�rdStj��t}dtjkri|d=tjd�j	�j
�}|ridSnt�}|jt
|j�|jt
|j�WdQXdS(NtwintdarwintcygwinRs
echo $DISPLAY(RRR(tNonetsystplatformt
startswithRtEnvironmentVarGuardtostenvirontpopentreadtstripRRRRR(Rtold_displaytenvtdisplayR((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyttestLoadTkFailures	(t__name__t
__module__tunittesttskipIfRRR
R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyR	s$t__main__(RRR!ttestRtTkinterRRtrequirestTestCaseRt	tests_guiRtrun_unittest(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_loadtk.pyt<module>s
!	PK(/�Z�-�ԠԠ'test_tkinter/test_geometry_managers.pyonu�[����
zfc@sddlZddlZddlZddlmZddlmZmZddlm	Z	m
Z
mZddlm
Z
mZed�de
ejfd��YZd	e
ejfd
��YZde
ejfd��YZeeefZed
kree�ndS(i����N(tTclError(trequirestrun_unittest(tpixels_convttcl_versiontrequires_tcl(tAbstractWidgetTestt	int_roundtguitPackTestcBs�eZd
Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�ZRS(c
Cs�tj|jdd�}|jd�|jdd�tj|dddddd	d
d�}tj|dddd
ddd
d�}tj|ddddddd
d�}tj|dddd	ddd
d�}|||||fS(Ntnametpacks300x200+0+0itatwidthitheighti(tbgtredtbi2itbluetciPtgreentdtyellow(ttkintertTopleveltroottwm_geometryt
wm_minsizetFrame(tselfRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pytcreate2s
''''cCs;|j�\}}}}}|jtd|��|jd|�WdQX|jtd��|jdd�WdQX|jdd�|jdd�|jdd�|jdd�|j|j�||||g�|jd|�|j|j�||||g�|jd|�|j|j�||||g�dS(Nswindow "%s" isn't packedtaftersbad window path name ".foo"s.footsidettop(RtassertRaisesRegexpRtpack_configuretassertEqualtpack_slaves(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_afters""cs��j�\}�}}}��fd�}|dd�|dd�|dd�|dd	�|d
d�|dd
�|dd�|dd�|dd�dS(Ncs[�jddddddddd	d
dtd|��jj��j�j�|�dS(
NR R!tipadxitpadxi
tipadyitpadyitexpandtanchor(R#tTrueRtupdateR$twinfo_geometry(R,tgeom(RR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pytcheck-s'

tns30x70+135+20tnes30x70+260+20tes30x70+260+65tses
30x70+260+110tss
30x70+135+110tsws30x70+10+110tws30x70+10+65tnws30x70+10+20tcenters30x70+135+65(R(RRRRRR1((RRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_anchor+s







cCs;|j�\}}}}}|jtd|��|jd|�WdQX|jtd��|jdd�WdQX|jdd�|jdd�|jdd�|jdd�|j|j�||||g�|jd|�|j|j�||||g�|jd|�|j|j�||||g�dS(Nswindow "%s" isn't packedtbeforesbad window path name ".foo"s.fooR R!(RR"RR#R$R%(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_before<s""cs{�j�\}���������fd�}�jdd��jdd��jdd��jdd�|ddd	d
��jdddd��jdddd
��jdddt��jdddd�|dddd��jdddddd��jdddd
dd��jdddtdd��jdddddd�|dddd�dS(Ncsy�jj��j�j�|d��j�j�|d��j�j�|d��j�j�|d�dS(Niiii(RR.R$R/(tgeoms(RRRRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1Ns

R tleftR!trighttbottoms
20x40+0+80s50x30+135+0s80x80+220+75s
40x30+100+170R+tyestonis20x40+40+80s50x30+175+35s
80x80+180+110s
40x30+100+135tfilltboths100x200+0+0s
200x100+100+0s160x100+140+100s40x100+100+100(RR#R-(RRR1((RRRRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_expandLs"cCs2|j�\}}}}}|jdd�|jdd�|jdd�|jdd�|jd|�|j|j�||||g�|jd|�|j|j�|||g�|j|j�|g�|jtd|f��|jd|�WdQX|jtd��|jdd�WdQXdS(NR R!tin_scan't pack %s inside itselfsbad window path name ".foo"s.foo(RR#R$R%R"R(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_inds"	cs��j�\}��}}���fd�}|dddddd�|dddddd'�|dddddd�|d
ddddddd	�|dddddddd�|dddddd(dd�|dddddddd�|d
ddddddd	dd�|dddddddd)dd�|dddddd�|dddddd*�|dddddd�|dddddddd	�|dddddddd+�|d ddddddd�|d!ddddd,dd�|d#ddddddd�|d$ddddddd	dd�|d%ddddddd-dd��jdd&��j�j�d�j|jd&����jdd&��j�j�d�j|jd&���dS(.Ncst�j��j��j|��jdtdd��jj��j�j�|��j�j�|�dS(NR+RDRE(tpack_forgetR#R-RR.R$R/(tgeom1tgeom2tkwargs(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1ws



s20x40+260+80s240x200+0+0R R@R(is20x40+250+80i
is60x40+240+80R's30x40+260+80s250x200+0+0iRDtxs20x40+249+80i	is30x40+255+80is20x40+140+0s300x160+0+40R!s20x40+120+0ii(s60x40+120+0s30x40+135+0s30x40+130+0s260x40+20+0s260x40+25+0is
300x40+0+0s280x40+10+0s
280x40+5+0t1c(i
i(i	i(ii(ii((ii(ii(ii(RR#R$t	pack_infot_strtwinfo_pixels(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt#test_pack_configure_padx_ipadx_fillusBcs��j�\}��}}���fd�}|dddddd�|dddddd'�|dddddd�|d
ddddddd	�|dddddddd�|dddddd(dd�|dddddddd�|d
ddddddd	dd�|dddddddd)dd�|dddddd�|dddddd*�|dddddd�|dddddddd	�|dddddddd+�|d ddddddd�|d!ddddd,dd�|d#ddddddd�|d$ddddddd	dd�|d%ddddddd-dd��jdd&��j�j�d�j|jd&����jdd&��j�j�d�j|jd&���dS(.Ncst�j��j��j|��jdtdd��jj��j�j�|��j�j�|�dS(NR+RDRE(RIR#R-RR.R$R/(RJRKRL(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1�s



s20x40+280+80s280x200+0+0R R@R*is20x40+280+70i
is20x80+280+60R)s20x50+280+75iRDRMs20x40+280+69i	is20x50+280+70is20x40+140+20s300x120+0+80R!s20x40+140+0ii(s20x80+140+0s20x50+140+10s300x130+0+70s20x50+140+5s300x40+0+20s300x40+0+25is
300x80+0+0s300x50+0+10s
300x50+0+5RN(i
i(i	i(ii(ii((ii(ii(ii(RR#R$RORPRQ(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt#test_pack_configure_pady_ipady_fill�sBcst�j�\}��}}���fd�}|ddd�|ddd�|dd	d
�|ddd
�dS(Ncs}�jd|��j�j�d|��jdtdd��jj��j�j�|��j�j�|�dS(NR R+RDRE(R#R$ROR-RR.R/(R RJRK(RRR(sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR1�s
R!s20x40+140+0s300x160+0+40RAs
20x40+140+160s300x160+0+0R?s
20x40+0+80s280x200+20+0R@s20x40+280+80s280x200+0+0(R(RRRRR1((RRRsG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_configure_side�scCs�|j�\}}}}}|j�|j�|j�|j|j�|||g�|j�|j|j�||g�|j�|j|j�||g�|j�dS(N(RR#R$R%RI(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_forget�s




cCs�|j�\}}}}}|jtd|��|j�WdQX|j�|jddd|dddtdd	d
ddd
dddd�	|j�}|j|t�|j|dd�|j|d|j	d��|j|dd�|j|d|�|j|d
|j	d��|j|d|j	d��|j|d|j	d��|j|d|j	d��|j|dd�|j�}|j|t�|j|dd�|j|d|j	d��|j|dd	�|j|d|�|j|d
|j	d��|j|d|j	d��|j|d|j	d
��|j|d|j	d��|j|dd�dS(Nswindow "%s" isn't packedR R@RGR,R6R+RDRMR'iR(i
R)iR*iR:itnonetinR!i(ii(ii(
RR"RROR#R-tassertIsInstancetdictR$RP(RRRRRRtinfo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_info�s8
'cCs�|j�\}}}}}|jdddd�|j�|jt�|jj�|j|j�d�|j|j	�d�|jt
�|jj�|j|j�d�|j|j	�d�dS(NR
i,Ri�ii((Rt	configureR#tpack_propagatetFalseRR.R$twinfo_reqwidthtwinfo_reqheightR-(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_propagates




cCs~|j�\}}}}}|j|j�g�|j�|j|j�|g�|j�|j|j�||g�dS(N(RR$R%R#(RRRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_pack_slavess

N(t__name__t
__module__tNonet	test_keysRR&R;R=RFRHRRRSRTRUR[RaRb(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR	
s	
						*	*				
t	PlaceTestcBs�eZdZd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�Zd
�Zd�ZRS(c
Cs�tj|jdddddd�}|jd�tj|dddd	dd
dd�}|jd
ddd�tj|dddddd
dd�}|jj�|||fS(NR
i,Ri�tbdis300x200+0+0i�iTitrelieftraisedRMi0tyi&ii<(RRRRRtplace_configureR.(Rtttftf2((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyRs$
''
cCs�|j�\}}}|j|j�d�|jtdtjt|����|jd|�WdQXt	d	kr�|j|j�d�n|jtd��|jdd�WdQX|jd|�|j|j�d�dS(
Nts!can't place %s relative to itselfRGiisbad window path nametspamtplace(ii(
RR$t
winfo_managerR"RtretescapetstrRlR(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_in$sc	Cs5|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jddd	d
�|j|j�dd�|jj�|j|j�d�|jtd
��|jd|dd�WdQXdS(NRGRMt0i2idt100i�i����trelxis-10i�sbad screen distance "spam"Rq(	RRlR$t
place_infoRR.twinfo_xR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_x1s


c	Cs5|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jddd	d
�|j|j�dd�|jj�|j|j�d�|jtd
��|jd|dd�WdQXdS(NRGRkRxi(i2t50iZi����trelyis-10insbad screen distance "spam"Rq(	RRlR$R{RR.twinfo_yR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_yBs


c	Cs/|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd	�|jj�|j|j�d
�|jtd��|jd|dd�WdQXdS(
NRGRzRxi2g�?s0.5i}it1i�s-expected floating-point number but got "spam"Rq(	RRlR$R{RR.R|R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relxSs


c	Cs/|j�\}}}|jd|�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd�|jj�|j|j�d�|jdd�|j|j�dd	�|jj�|j|j�d
�|jtd��|jd|dd�WdQXdS(
NRGRRxi(g�?s0.5iPiR�ixs-expected floating-point number but got "spam"Rq(	RRlR$R{RR.R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relyes


cCs�tj|j�}|jtd��|jdd�WdQX|jtd��|jdd�WdQXx8dD]0}|jd|�|j|j�d|�qkWdS(Nsbad anchor "j"R,tjsambiguous anchor ""RpR2R3R4R5R6R7R8R9R:(	R2R3R4R5R6R7R8R9R:(RRRR"RRlR$R{(RRntvalue((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_anchorws
cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(NRGR
ixRpisbad screen distance "abcd"tabcd(RRlRR.R$twinfo_widthR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_width�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(NRGRixRpi<sbad screen distance "abcd"R�(RRlRR.R$twinfo_heightR"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_height�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(	NRGtrelwidthg�?iKRpis-expected floating-point number but got "abcd"R�(RRlRR.R$R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relwidth�s

cCs�|j�\}}}|jd|dd�|jj�|j|j�d�|jdd�|jj�|j|j�d�|jtd��|jdd�WdQXdS(	NRGt	relheightg�?i(Rpi<s-expected floating-point number but got "abcd"R�(RRlRR.R$R�R"R(RRmRnRo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_relheight�s

cCs�tj|j�}|jtd��|jdd�WdQX|jtd��|jdd�WdQXx8d	D]0}|jd|�|j|j�d|�qkWdS(
Nsbad bordermode "j"t
bordermodeR�sambiguous bordermode ""Rptinsidetoutsidetignore(R�R�R�(RRRR"RRlR$R{(RRnR�((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_configure_bordermode�s
cCs�tj|j�}|jdddd�|jj�|j�|jj�|j|j��|jt	��|jd�WdQXdS(NR
i2Ri(
RRRRlR.tplace_forgettassertFalsetwinfo_ismappedtassertRaisest	TypeError(Rtfoo((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_forget�s


cCs�|j�\}}}|jd|dddddddd	d
ddd
dddddddd�|j�}|j|t�|j|dd�|j|dd�|j|dd�|j|dd�|j|d
d�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|jt��|jd�WdQXdS(NRGRMiRkiR
iRiRzg�������?Rg�������?R�g333333�?R�g�������?R,R5R�R�R�t2t3t4s0.1s0.2s0.3s0.4i(RRlR{RXRYR$R�R�(RRmRnRoRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_info�s('
cCs�tj|j�}tj|j�}|j|j�g�|jd|�|j|j�|g�|jt��|jd�WdQXdS(NRGi(RRRR$tplace_slavesRlR�R�(RR�tbar((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_place_slaves�sN(RcRdReRfRRwR}R�R�R�R�R�R�R�R�R�R�R�R�(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyRgs 			
					
					
	
	tGridTestcBseZdZd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd	�Z
d
�Zd�Zd�Zd
�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Z d�Z!RS(cCs�|jj�\}}x@t|d�D].}|jj|dddddddd�q&Wx@t|d�D].}|jj|dddddddd�qiW|jjd�tt|�j�dS(NitweightitminsizetpadtuniformRp(	Rt	grid_sizetrangetgrid_columnconfiguretgrid_rowconfiguretgrid_propagatetsuperR�ttearDown(Rtcolstrowsti((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR��s,,cCs�tj|j�}|j|j�i�|j�|j|j�d|j�|j|j�d|jd��|j|j�d|jd��|jidd6dd�|j|j�d|jd��|j|j�d|jd��dS(NRWtcolumnitrowii(RtButtonRR$t	grid_infotgrid_configureRP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure�s
###cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns5bad column value "-1": must be a non-negative integerR�i����i(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_column�s
cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns4bad columnspan value "0": must be a positive integert
columnspanii(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_columnspans
cCs�tj|j�}tj|j�}|j|j�i�|j�|j|j�d|j�|jd|�|j|j�d|�|ji|jd6�|j|j�d|j�dS(NRWRG(RRRR�R$R�R�(RRnR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ins
cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jt	t
d�|j���dS(Ns6bad ipadx value "-1": must be positive screen distanceR'i����is.5c(RR�RR"RR�R$R�RPRRtscaling(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ipadxs#cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jt	t
d�|j���dS(Ns6bad ipady value "-1": must be positive screen distanceR)i����is.5c(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_ipady!s#cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jd	��|jdd�|j|j�d|jt	t
d�|j���dS(
Ns4bad pad value "-1": must be positive screen distanceR(i����ii
is.5c(i
i(i
i(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_padx,s##cCs�tj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��|jdd�|j|j�d|jd	��|jdd�|j|j�d|jt	t
d�|j���dS(
Ns4bad pad value "-1": must be positive screen distanceR*i����ii
is.5c(i
i(i
i(RR�RR"RR�R$R�RPRRR�(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_pady9s##cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns9bad (row|grid) value "-1": must be a non-negative integerR�i����i(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_rowFs
cCsrtj|j�}|jtd��|jdd�WdQX|jdd�|j|j�d|jd��dS(Ns1bad rowspan value "0": must be a positive integertrowspanii(	RR�RR"RR�R$R�RP(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_rownspanNs
cCs�tj|jdd�}|jtd��|jdd�WdQX|jdd�|j|j�dd�|jdd�|j|j�dd�dS(	NRRsbad stickyness value "glue"tstickytglueR3sn,s,e,wtnesw(RRRR"RR�R$R�(RRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_configure_stickyVsc	Cs�|jt��|jj�WdQX|j|jjd�idd6dd6dd6dd6�|jtd��|jjdd�WdQX|jjddd	�|jtd
��|jjd�WdQXtj	|j�}|j
dddd�tdkr[|jjddd�|jtd��|jjd�WdQX|j|jjdd�d�n|j|jjdd�d	�|j|jjdd�d�tdkr�|jj|dd�|j|jjdd�d�ndS(NiR�R�R�R�sbad option "-foo"R�iis*must specify a single element on retrievalR�R�iitallsexpected integer but got "all"i	i(ii(ii(ii(ii(R�R�RR�R$ReR"RRR�R�R(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_columnconfigure_s,#	
"cCs�|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�i
(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt!test_grid_columnconfigure_minsizews
c	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsexpected integer but got "bad"iR�tbads-invalid arg "-weight": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt test_grid_columnconfigure_weight~sc	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�s*invalid arg "-pad": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_columnconfigure_pad�scCsY|jjddd�|j|jjdd�d�|j|jjd�dd�dS(NiR�R�(RR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt!test_grid_columnconfigure_uniform�sc	Cs�|jt��|jj�WdQX|j|jjd�idd6dd6dd6dd6�|jtd��|jjdd�WdQX|jjddd	�|jtd
��|jjd�WdQXtj	|j�}|j
dddd�tdkr[|jjddd�|jtd��|jjd�WdQX|j|jjdd�d�n|j|jjdd�d	�|j|jjdd�d�tdkr�|jj|dd�|j|jjdd�d�ndS(NiR�R�R�R�sbad option "-foo"R�iis*must specify a single element on retrievalR�R�iiR�sexpected integer but got "all"i	i(ii(ii(ii(ii(R�R�RR�R$ReR"RRR�R�R(RR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure�s,#	
"cCs�|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�i
(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_minsize�s
c	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsexpected integer but got "bad"iR�R�s-invalid arg "-weight": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_weight�sc	Cs�|jtd��|jjddd�WdQX|jtd��|jjddd�WdQX|jjddd�|j|jjdd�d�|j|jjd�dd�dS(Nsbad screen distance "foo"iR�R�s*invalid arg "-pad": should be non-negativei����i(R"RRR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_pad�scCsY|jjddd�|j|jjdd�d�|j|jjd�dd�dS(NiR�R�(RR�R$(R((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_rowconfigure_uniform�scCs�tj|j�}tj|j�}|jdddddddddddd	d
d�|j|jj�|g�|j�|j�|j|jj�g�|j|j�i�|jdddd�|j�}|j|d|jd��|j|d|jd��|j|d|jd
��|j|d|jd
��|j|d|jd��|j|d|jd��|j|d
d�dS(NR�iR�R�R�R(iR*iR�tnsiiRp(	RR�RR�R$tgrid_slavestgrid_forgetR�RP(RRRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_forget�s$!

cCs�tj|j�}tj|j�}|jdddddddddddd	d
d�|j|jj�|g�|j�|j�|j|jj�g�|j|j�i�|jdddd�|j�}|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd	��|j|d
d�dS(
NR�iR�R�R�R(iR*iR�R�i(	RR�RR�R$R�tgrid_removeR�RP(RRRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_remove�s$!

cCsUtj|j�}|j|j�i�|jdddddddddddd	d
d�|j�}|j|t�|j|d|j�|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd��|j|d|jd	��|j|d
d�dS(
NR�iR�R�R�R(iR*iR�R�RW(	RR�RR$R�R�RXRYRP(RRRZ((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_info�s!cCs�|j|jj�d�|j|jjdd�d�|j|jjdddd�d�|jtd��|jjdd�WdQX|jtd��|jjdd�WdQX|jtd��|jjdddd�WdQX|jtd��|jjdddd�WdQX|jt��!|jjddddd�WdQX|j}|jd�|jd�tj	|ddd	dd
d�}tj	|ddd	dd
d
�}|j
dddd�|j
dddd�|jj�|j|j�d�|j|jdd�d�|j|jdddd�d�|j|jdd�d�|j|jdddd�d�|j|jdddd�d�|j|jdddd�d�dS(Niisexpected integer but got "x"RMs1x1+0+0RpR
iKRRRiZRR�R�i�i
i����i����i(iiii(iiii(iiii(iii�i�(iiiKiK(iii�i�(iKiKiZiZ(iii�i�(iiii(i�i�ii(R$Rt	grid_bboxR"RR�R�RRRR�R.(RRmtf1Ro((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_bboxs8%"	

!!
"""cCs�|jt��|jj�WdQX|jt��|jjd�WdQX|jt��|jjddd�WdQX|jtd��|jjdd�WdQX|jtd��|jjdd�WdQX|j}|jd�|jd�tj|d	d
ddd
ddd�}|j	|jdd�d�|j
�|jj�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|j	|jd
d�d�|j	|jdd�d�|j	|jdd�d�|j	|jdd�d �|j	|jdd�d!�dS("Nisbad screen distance "x"RMRksbad screen distance "y"RNs1x1+0+0RpR
i�RidthighlightthicknessRRi
i����i����i�iie(i����i����(i����i����(i����i(i����i(ii����(ii����(ii(ii(ii(ii(ii(ii(R�R�Rt
grid_locationR"RRRRR$R�R.(RRmRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_location&s:	



c	Cs�|j|jj�t�|jt��|jjtt�WdQX|jjt�|j|jj��tj	|jdddddd�}|j
dddd�|jj�|j|j�d�|j|j
�d�|jt�tj	|jdd	dd
dd�}|j
d|dddd�|jj�|j|j�d�|j|j
�d�|jt�|jj�|j|j�d	�|j|j
�d
�dS(
NR
idRRRR�iR�iKiURRG(R$RR�R-R�R�R^R�RRR�R.R�R�(RRntg((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_propagateFs($

$


cCs�|jt��|jjd�WdQX|j|jj�d�tj|j�}|jdddd�|j|jj�d	�|jdddd�|j|jj�d
�dS(NiR�R�iiii(ii(ii(ii(R�R�RR�R$RtScaleR�(RRn((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_size\scCs�|j|jj�g�tj|j�}|jdddd�tj|j�}|jdddd�tj|j�}|jdddd�tj|j�}|jdddd�|j|jj�||||g�|j|jjdd�|g�|j|jjdd�|||g�|j|jjdd�|g�|j|jjdd�|||g�|j|jjdddd�||g�dS(NR�iR�i(R$RR�RtLabelR�(RRRRR((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyttest_grid_slavesfs%"("(N("RcRdReRfR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyR��s>									
	
							
	
				
	
						 		
t__main__(tunittestRttTkinterRRttest.test_supportRRttest_ttk.supportRRRtwidget_testsRRtTestCaseR	RgR�t	tests_guiRc(((sG/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_geometry_managers.pyt<module>s
����PK(/�Z�3,O'>'>test_tkinter/test_images.pycnu�[����
zfc@s�ddlZddlZddlZddljZddlmZm	Z	ej
d�deejfd��YZdeejfd��YZ
deejfd	��YZee
efZed
kr�eje�ndS(i����N(tAbstractTkTesttrequires_tcltguitMiscTestcBseZd�Zd�ZRS(cCsC|jj�}|j|t�|jd|�|jd|�dS(Ntphototbitmap(troottimage_typestassertIsInstancettupletassertIn(tselfR((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_image_typesscCs#|jj�}|j|t�dS(N(Rtimage_namesRR	(RR
((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_image_namess(t__name__t
__module__RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR
s	tBitmapImageTestcBsVeZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
RS(cCs,tjj|�tjddd�|_dS(Ns
python.xbmtsubdirt
imghdrdata(Rt
setUpClasst__func__tsupporttfindfilettestfile(tcls((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRsc
Cs�tjdd|jddddd|j�}|jt|�d�|j|j�d�|j|j�d	�|j|j�d	�|j	d|jj
��~|jd|jj
��dS(
Ns::img::testtmastert
foregroundtyellowt
backgroundtbluetfileRi(ttkintertBitmapImageRRtassertEqualtstrttypetwidththeightR
R
tassertNotIn(Rtimage((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_filescCs�t|jd��}|j�}WdQXtjdd|jddddd|�}|jt|�d�|j|j�d	�|j|j	�d
�|j|j
�d
�|jd|jj��~|j
d|jj��dS(Ntrbs::img::testRRRRRtdataRi(topenRtreadR R!RR"R#R$R%R&R
R
R'(RtfR+R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_data*s	cCs0|j|t�|j|jj|�|�dS(N(RR#R"Rt	splitlist(Rtactualtexpected((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytassertEqualStrList8scCs�tjdd|j�}|j|dd�t|jd��}|j�}WdQX|jd|�|j|ddddd|f�|j|j	�d�|j|j
�d�|j|d	d
�|jd	|�|j|d	dddd|f�dS(Ns::img::testRR+s-data {} {} {} {}R*s-datatitmaskdatas-maskdata {} {} {} {}s	-maskdata(R R!RR"R,RR-t	configureR3R%R&(RR(R.R+((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_data<s

cCs�tjdd|j�}|j|dd�|jd|j�|j|ddddd|jf�|j|j�d�|j|j�d�|j|dd	�|jd|j�|j|dd
ddd|jf�dS(Ns::img::testRRs-file {} {} {} {}s-fileR4itmaskfiles-maskfile {} {} {} {}s	-maskfile(	R R!RR"R6RR3R%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_fileLs

cCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRRs-background {} {} {} {}Rs-background {} {} {} blue(R R!RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_backgroundZscCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRRs!-foreground {} {} #000000 #000000Rs -foreground {} {} #000000 yellow(R R!RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_foreground`s

(RRtclassmethodRR)R/R3R7R9R:R;(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRs						tPhotoImageTestcBseZed��Zd�Zd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd	�Zd
�Z
edd�d
��Zedd�d��Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�Zd�ZRS(cCs,tjj|�tjddd�|_dS(Ns
python.gifRR(RRRRRR(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyRkscCstjdd|jd|j�S(Ns::img::testRR(R t
PhotoImageRR(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcreatepscGs-tjdkr|jr|Stj|�SdS(Ng333333!@(R t	TkVersiontwantobjectst_join(Rtargs((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	colorlisttscCs�tjd|dd�}tjdd|jd|�}|jt|�d�|j|j�d�|j|j�d�|j|j	�d�|j|d	d
�|j|d|�|j
d|jj��~|jd|jj��dS(Nspython.RRs::img::testRRRiR+R4(
RRR R>RR"R#R$R%R&R
R
R'(RtextRR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcheck_create_from_filezs	cCs,tjd|dd�}t|d��}|j�}WdQXtjdd|jd|�}|jt|�d�|j|j	�d�|j|j
�d	�|j|j�d	�|j|d|jr�|n|j
d
��|j|dd�|jd|jj��~|jd|jj��dS(
Nspython.RRR*s::img::testRR+Ritlatin1RR4(RRR,R-R R>RR"R#R$R%R&RAtdecodeR
R
R'(RRERR.R+R(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pytcheck_create_from_data�s	cCs|jd�dS(Ntppm(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_ppm_file�scCs|jd�dS(NRJ(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_ppm_data�scCs|jd�dS(Ntpgm(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_pgm_file�scCs|jd�dS(NRM(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_pgm_data�scCs|jd�dS(Ntgif(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_gif_file�scCs|jd�dS(NRP(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_gif_data�siicCs|jd�dS(Ntpng(RF(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_png_file�scCs|jd�dS(NRS(RI(R((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_create_from_png_data�scCs�tjdd|j�}|j|dd�t|jd��}|j�}WdQX|jd|�|j|d|jr|n|j	d��|j|j
�d�|j|j�d�dS(Ns::img::testRR+R4R*RGi(R R>RR"R,RR-R6RARHR%R&(RR(R.R+((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR7�scCs�tjdd|j�}|j|dd�|jd|jdd�|j|d|jradnd�|j|j�d�|j|j�d�dS(	Ns::img::testRtformatR4RRPi(RP(	R R>RR"R6RRAR%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_format�scCs�tjdd|j�}|j|dd�|jd|j�|j|d|j�|j|j�d�|j|j�d�dS(Ns::img::testRRR4i(R R>RR"R6RR%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR9�scCsTtjdd|j�}|j|dd�|jdd�|j|dd�dS(Ns::img::testRtgammas1.0g@s2.0(R R>RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_gamma�scCs�tjdd|j�}|j|dd�|j|dd�|jdd�|jdd�|j|dd�|j|dd	�|j|j�d�|j|j�d�dS(
Ns::img::testRR%t0R&ii
t20t10(R R>RR"R6R%R&(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_width_height�scCsxtjdd|j�}|j|dd�|jdd�|j|dd�|jdd�|j|dd�dS(Ns::img::testRtpaletteR4it256s3/4/2(R R>RR"R6(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_configure_palette�scCsq|j�}|j�|j|j�d�|j|j�d�|j|jdd�|jddd��dS(Niiii(R?tblankR"R%R&tgetRD(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt
test_blank�s

cCsp|j�}|j�}|j|j�d�|j|j�d�|j|jdd�|jdd��dS(Niii(R?tcopyR"R%R&Rb(RR(timage2((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	test_copy�s
cCs�|j�}|jdd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|jd�}|j|j�d�|j|j�d�|j|jdd�|jdd��dS(Niiiii(R?t	subsampleR"R%R&Rb(RR(Re((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_subsample�s(cCs)|j�}|jdd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|j|jd	d
�|jdd��|jd�}|j|j�d�|j|j�d�|j|jdd�|jdd��|j|jd	d�|jdd��dS(
Niii i0iiiii	iii
(R?tzoomR"R%R&Rb(RR(Re((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt	test_zooms(((cCs�|j�}|jddd�|j|jdd�|jddd��|j|jdd�|jdtjdkr}d	ndd��|j|jdd
�|jddd��|j|jdd
�|jddd��|jddf�|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��dS(Ns{red green} {blue yellow}ttoiii�iig333333!@i�is#f00s#00ff00s
#000000fffs
#ffffffff0000i(ii(s#f00s#00ff00(s
#000000fffs
#ffffffff0000(R?tputR"RbRDR R@(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_puts+
+++++cCs|j�}|j|jdd�|jddd��|j|jdd�|jddd��|j|jdd�|jddd��|jtj|jdd�|jtj|jdd�|jtj|jd	d�|jtj|jdd	�dS(
Niii>iti�iii����i(R?R"RbRDtassertRaisesR tTclError(RR(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyttest_get s+++c	Cs�|j�}|jtjtj�|jtj�tjdd|jdddtj�}|j	t
|�d�|j	|j�d�|j	|j�d�|j	|j
�d�|j	|jdd�|jdd��|j	|jd	d
�|jd	d
��|jtjdddd�tjdd|jdddtj�}|j	t
|�d�|j	|j�d�|j	|j�d�|j	|j
�d�|j	|jdd�|jd
d��|j	|jdd�|jdd
��dS(Ns::img::test2RRVRJRRiiiiRPtfrom_coordsiii	s::img::test3iiii(iiii	(R?t
addCleanupRtunlinktTESTFNtwriteR R>RR"R#R$R%R&Rb(RR(Retimage3((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt
test_write*s,((((RRR<RR?RDRFRIRKRLRNRORQRRRRTRUR7RWR9RYR]R`RcRfRhRjRmRpRw(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyR=is4																							
t__main__(tunittesttTkinterR tttkttest.test_supportttest_supportRttest_ttk.supportRRtrequirestTestCaseRRR=t	tests_guiRtrun_unittest(((s</usr/lib64/python2.7/lib-tk/test/test_tkinter/test_images.pyt<module>s

R�PK(/�Z��r��test_tkinter/test_misc.pynu�[���import unittest
import Tkinter as tkinter
from test.test_support import requires, run_unittest
from test_ttk.support import AbstractTkTest

requires('gui')

class MiscTest(AbstractTkTest, unittest.TestCase):

    def test_after(self):
        root = self.root
        cbcount = {'count': 0}

        def callback(start=0, step=1):
            cbcount['count'] = start + step

        # Without function, sleeps for ms.
        self.assertIsNone(root.after(1))

        # Set up with callback with no args.
        cbcount['count'] = 0
        timer1 = root.after(0, callback)
        self.assertIn(timer1, root.tk.call('after', 'info'))
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1))
        root.update()  # Process all pending events.
        self.assertEqual(cbcount['count'], 1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)

        # Set up with callback with args.
        cbcount['count'] = 0
        timer1 = root.after(0, callback, 42, 11)
        root.update()  # Process all pending events.
        self.assertEqual(cbcount['count'], 53)

        # Cancel before called.
        timer1 = root.after(1000, callback)
        self.assertIn(timer1, root.tk.call('after', 'info'))
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1))
        root.after_cancel(timer1)  # Cancel this event.
        self.assertEqual(cbcount['count'], 53)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)

    def test_after_idle(self):
        root = self.root
        cbcount = {'count': 0}

        def callback(start=0, step=1):
            cbcount['count'] = start + step

        # Set up with callback with no args.
        cbcount['count'] = 0
        idle1 = root.after_idle(callback)
        self.assertIn(idle1, root.tk.call('after', 'info'))
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1))
        root.update_idletasks()  # Process all pending events.
        self.assertEqual(cbcount['count'], 1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)

        # Set up with callback with args.
        cbcount['count'] = 0
        idle1 = root.after_idle(callback, 42, 11)
        root.update_idletasks()  # Process all pending events.
        self.assertEqual(cbcount['count'], 53)

        # Cancel before called.
        idle1 = root.after_idle(callback)
        self.assertIn(idle1, root.tk.call('after', 'info'))
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1))
        root.after_cancel(idle1)  # Cancel this event.
        self.assertEqual(cbcount['count'], 53)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)

    def test_after_cancel(self):
        root = self.root
        cbcount = {'count': 0}

        def callback():
            cbcount['count'] += 1

        timer1 = root.after(5000, callback)
        idle1 = root.after_idle(callback)

        # No value for id raises a ValueError.
        with self.assertRaises(ValueError):
            root.after_cancel(None)

        # Cancel timer event.
        cbcount['count'] = 0
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1))
        root.tk.call(script)
        self.assertEqual(cbcount['count'], 1)
        root.after_cancel(timer1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)
        self.assertEqual(cbcount['count'], 1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call('after', 'info', timer1)

        # Cancel same event - nothing happens.
        root.after_cancel(timer1)

        # Cancel idle event.
        cbcount['count'] = 0
        (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1))
        root.tk.call(script)
        self.assertEqual(cbcount['count'], 1)
        root.after_cancel(idle1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call(script)
        self.assertEqual(cbcount['count'], 1)
        with self.assertRaises(tkinter.TclError):
            root.tk.call('after', 'info', idle1)


tests_gui = (MiscTest, )

if __name__ == "__main__":
    run_unittest(*tests_gui)
PK(/�Z���*test_tkinter/test_misc.pycnu�[����
zfc@s�ddlZddlZddlmZmZddlmZed�deejfd��YZ	e	fZ
edkr�ee
�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguitMiscTestcBs#eZd�Zd�Zd�ZRS(cs�|j}idd6�dd�fd�}|j|jd��d�d<|jd|�}|j||jjdd��|jj|jjdd|��\}}|j�|j�dd�|j	t
j��|jj|�WdQXd�d<|jd|dd�}|j�|j�dd	�|jd
|�}|j||jjdd��|jj|jjdd|��\}}|j|�|j�dd	�|j	t
j��|jj|�WdQXdS(Nitcountics||�d<dS(NR((tstarttstep(tcbcount(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pytcallbackstaftertinfoi*ii5i�(
troottassertIsNoneR
tassertInttktcallt	splitlisttupdatetassertEqualtassertRaisesttkintertTclErrortafter_cancel(tselfRR	ttimer1tscriptt_((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyt
test_after
s.	

*


*
cs�|j}idd6�dd�fd�}d�d<|j|�}|j||jjdd��|jj|jjdd|��\}}|j�|j�dd�|jt	j
��|jj|�WdQXd�d<|j|dd�}|j�|j�dd	�|j|�}|j||jjdd��|jj|jjdd|��\}}|j|�|j�dd	�|jt	j
��|jj|�WdQXdS(
NiRics||�d<dS(NR((RR(R(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyR	1sR
Ri*ii5(Rt
after_idleRRRRtupdate_idletasksRRRRR(RRR	tidle1RR((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyttest_after_idle-s,	

*


*
cs|j}idd6��fd�}|jd|�}|j|�}|jt��|jd�WdQXd�d<|jj|jj	dd|��\}}|jj	|�|j
�dd�|j|�|jtj��|jj	|�WdQX|j
�dd�|jtj��|jj	dd|�WdQX|j|�d�d<|jj|jj	dd|��\}}|jj	|�|j
�dd�|j|�|jtj��|jj	|�WdQX|j
�dd�|jtj��|jj	dd|�WdQXdS(NiRcs�dcd7<dS(NRi(((R(s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyR	Qsi�R
Ri(
RR
RRt
ValueErrorRtNoneRRRRRR(RRR	RRRR((Rs:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyttest_after_cancelMs8	

*


*
(t__name__t
__module__RR R#(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyRs	#	 t__main__(tunittesttTkinterRttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR$(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_misc.pyt<module>s
o	PK(/�ZT�D���test_tkinter/__init__.pycnu�[����
zfc@sdS(N((((s9/usr/lib64/python2.7/lib-tk/test/test_tkinter/__init__.pyt<module>tPK(/�Z0<477test_tkinter/test_text.pyonu�[����
zfc@s�ddlZddlZddlmZmZddlmZed�deejfd��YZ	e	fZ
edkr�ee
�ndS(i����N(trequirestrun_unittest(tAbstractTkTesttguitTextTestcBs#eZd�Zd�Zd�ZRS(cCs,tt|�j�tj|j�|_dS(N(tsuperRtsetUpttkintertTexttrootttext(tself((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyR
scCs�|j}|j�}zJ|jd�|j|j�d�|jd�|j|j�d�Wd|j|�|j|j�|�XdS(Nii(R
tdebugtassertEqual(RR
tolddebug((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyt
test_debugs	


cCs�|j}|jtj|jdd�|jtj|jdd�|jtj|jdd�|jtj|jdd�|jdd�|j|jddd�d�|j|jd	dd�d
�dS(Ns1.0tatishi-tests-testtends1.2ttests1.3(R
tassertRaisesRtTclErrortsearchtNonetinsertR
(RR
((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyttest_searchs	(t__name__t
__module__RRR(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyRs		t__main__(tunittesttTkinterRttest.test_supportRRttest_ttk.supportRtTestCaseRt	tests_guiR(((s:/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_text.pyt<module>s
$	PK(/�Z�l��test_tkinter/test_widgets.pycnu�[����
zfc@sTddlZddlZddlmZddlZddlZddlmZmZddl	m
Z
mZmZm
Z
ddlmZmZmZmZmZmZmZmZmZmZed�deefd��YZee�d	eejfd
��Y�Zee�deejfd��Y�Zee�d
eejfd��Y�Zdeefd��YZee�deejfd��Y�Zee�deejfd��Y�Z ee�deejfd��Y�Z!ee�deejfd��Y�Z"ee�deejfd��Y�Z#de#ejfd��YZ$eee�deejfd��Y�Z%ee�de%ejfd ��Y�Z&ee�d!eejfd"��Y�Z'eee�d#eejfd$��Y�Z(eee�d%eejfd&��Y�Z)eee�d'eejfd(��Y�Z*eee�d)eejfd*��Y�Z+ee�d+eejfd,��Y�Z,ee�d-eejfd.��Y�Z-eee�d/eejfd0��Y�Z.e e(e!e%eeee)e#e-e.e$e,e"e*e+e&e'egZ/e0d1krPee/�ndS(2i����N(tTclError(trequirestrun_unittest(ttcl_versiontrequires_tcltget_tk_patchlevelt	widget_eq(
tadd_standard_optionstnoconvtnoconv_metht	int_roundtpixels_roundtAbstractWidgetTesttStandardOptionsTeststIntegerSizeTeststPixelSizeTeststsetUpModuletguitAbstractToplevelTestcBs2eZeZd�Zd�Zd�Zd�ZRS(cCso|j�}|j|d|jjj��|j|dddd�|jdd�}|j|dd�dS(NtclasstFooterrmsgs2can't modify -class option after widget is createdtclass_(tcreatetassertEqualt	__class__t__name__ttitletcheckInvalidParam(tselftwidgettwidget2((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_classs
cCsc|j�}|j|dd�|j|dddd�|jdd�}|j|dd�dS(NtcolormapttnewRs5can't modify -colormap option after widget is created(RRR(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_colormapscCs�|j�}|j|d|jr(dnd�|j|dddd�|jdt�}|j|d|jrvdnd�dS(Nt	containerit0iRs6can't modify -container option after widget is createdt1(RRtwantobjectsRtTrue(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_container's#cCsc|j�}|j|dd�|j|dddd�|jdd�}|j|dd�dS(NtvisualR"tdefaultRs3can't modify -visual option after widget is created(RRR(RRR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_visual/s(Rt
__module__R	t_conv_pad_pixelsR R$R*R-(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRs
				tToplevelTestcBs2eZdZd�Zd�Zd�Zd�ZRS(t
backgroundtborderwidthRR!R%tcursortheightthighlightbackgroundthighlightcolorthighlightthicknesstmenutpadxtpadytrelieftscreent	takefocustuseR+twidthcKstj|j|�S(N(ttkintertTopleveltroot(Rtkwargs((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRBscCsN|j�}tj|j�}|j|d|dt�|j|dd�dS(NR8teqR"(RR@tMenuRBt
checkParamR(RRR8((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_menuEscCs�|j�}|j|dd�ytjd}Wntk
rQ|jd�nX|j|d|dd�|jd|�}|j|d|�dS(NR<R"tDISPLAYsNo $DISPLAY set.Rs3can't modify -screen option after widget is created(RRtostenvirontKeyErrortskipTestR(RRtdisplayR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_screenKs
cCsl|j�}|j|dd�|jdt�}d|j�}|jd|�}|j|d|�dS(NR>R"R%s%#x(RRR)twinfo_id(RRtparenttwidR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_useWs(R1R2RR!R%R3R4R5R6R7R8R9R:R;R<R=R>R+R?(RR.tOPTIONSRRGRNRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR08s			t	FrameTestcBseZdZd�ZRS(R1R2RR!R%R3R4R5R6R7R9R:R;R=R+R?cKstj|j|�S(N(R@tFrameRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRjs(R1R2RR!R%R3R4R5R6R7R9R:R;R=R+R?(RR.RSR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRTas
tLabelFrameTestcBs)eZdZd�Zd�Zd�ZRS(R1R2RR!R%R3tfontt
foregroundR4R5R6R7tlabelanchortlabelwidgetR9R:R;R=ttextR+R?cKstj|j|�S(N(R@t
LabelFrameRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRyscCsW|j�}|j|ddddddddd	d
ddd
�|j|dd�dS(NRYtetentestntnetnwtstsetswtwtwntwstcenter(RtcheckEnumParamR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_labelanchor|s
cCsQ|j�}tj|jdddd�}|j|d|dd�|j�dS(NR[tMupptnametfooRZtexpecteds.foo(RR@tLabelRBRFtdestroy(RRtlabel((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_labelwidget�s(R1R2RR!R%R3RWRXR4R5R6R7RYRZR9R:R;R=R[R+R?(RR.RSRRkRs(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRVns		tAbstractLabelTestcBseZeZd�ZRS(c	Cs2|j�}|j|ddddddd�dS(NR7ig�������?g������@ii����t10p(RtcheckPixelsParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_highlightthickness�s(RR.R	t_conv_pixelsRw(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRt�st	LabelTestcBseZdZd�ZRS(tactivebackgroundtactiveforegroundtanchorR1tbitmapR2tcompoundR3tdisabledforegroundRWRXR4R5R6R7timagetjustifyR9R:R;tstateR=R[ttextvariablet	underlineR?t
wraplengthcKstj|j|�S(N(R@RpRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s(RzR{R|R1R}R2R~R3RRWRXR4R5R6R7R�R�R9R:R;R�R=R[R�R�R?R�(RR.RSR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRy�st
ButtonTestc Bs eZd"Zd �Zd!�ZRS(#RzR{R|R1R}R2tcommandR~R3R,RRWRXR4R5R6R7R�R�t
overreliefR9R:R;trepeatdelaytrepeatintervalR�R=R[R�R�R?R�cKstj|j|�S(N(R@tButtonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR,tactivetdisabledtnormal(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_default�s( RzR{R|R1R}R2R�R~R3R,RRWRXR4R5R6R7R�R�R�R9R:R;R�R�R�R=R[R�R�R?R�(RR.RSRR�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s	tCheckbuttonTestc&Bs)eZd)Zd&�Zd'�Zd(�ZRS(*RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�tindicatoronR�t	offrelieftoffvaluetonvalueR�R9R:R;tselectcolortselectimageR�R=R[R�t
tristateimaget
tristatevalueR�tvariableR?R�cKstj|j|�S(N(R@tCheckbuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RtcheckParams(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_offvalue�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_onvalue�s(&RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�R�R?R�(RR.RSRR�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s		tRadiobuttonTestc%Bs eZd'Zd%�Zd&�ZRS((RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�tvalueR�R?R�cKstj|j|�S(N(R@tRadiobuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs,|j�}|j|ddddd�dS(NR�igffffff@R"s
any string(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_value�s(%RzR{R|R1R}R2R�R~R3RRWRXR4R5R6R7R�R�R�R�R�R9R:R;R�R�R�R=R[R�R�R�R�R�R�R?R�(RR.RSRR�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s	tMenubuttonTestcBs�eZd(Zee�Zd�Zd�Zd �Ze	j
jZ
ej
ejd!kd"�d#��Zd$�Zd%�Zd&�Zd'�ZRS()RzR{R|R1R}R2R~R3t	directionRRWRXR4R5R6R7R�R�R�R8R9R:R;R�R=R[R�R�R?R�cKstj|j|�S(N(R@t
MenubuttonRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR�tabovetbelowtflushtlefttright(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_direction�scCs/|j�}|j|dddddt�dS(NR4idi����itconv(RtcheckIntegerParamtstr(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_heightstdarwins"crashes with Cocoa Tk (issue19733)c	Cs�|j�}tjd|jdd�}|j|d|dt�d}|jtj��}d|d<WdQX|dk	r�|j	t|j
�|�n|jtj��}|jidd6�WdQX|dk	r�|j	t|j
�|�ndS(NtmasterRmtimage1R�R�simage "spam" doesn't existtspam(RR@t
PhotoImageRBRFR�tassertRaisesRtNoneRt	exceptiont	configure(RRR�Rtcm((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_image	scCsH|j�}tj|dd�}|j|d|dt�|j�dS(NRmR8RD(RR@RERFRRq(RRR8((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRGscCsE|j�}|j|ddddd�|j|dddd�dS(	NR9ig������@gffffff@t12mi����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_padxscCsE|j�}|j|ddddd�|j|dddd�dS(	NR:ig������@gffffff@R�i����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_pady$scCs/|j�}|j|dddddt�dS(NR?i�in���iR�(RR�R�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_width)s(RzR{R|R1R}R2R~R3R�RRWRXR4R5R6R7R�R�R�R8R9R:R;R�R=R[R�R�R?R�(RR.RStstaticmethodRRxRR�R�R
Rwtim_functunittesttskipIftsystplatformR�RGR�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s(						tOptionMenuTestcBseZddd�ZRS(tbtatccKstj|jd|||�S(N(R@t
OptionMenuRBR�(RR,tvaluesRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR0s(R�R�R�(RR.R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�.st	EntryTestcBsheZd)Zd�Zd �Zd!�Zd"�Zd#�Zd$�Zd%�Z	d&�Z
d'�Zd(�ZRS(*R1R2R3tdisabledbackgroundRtexportselectionRWRXR5R6R7tinsertbackgroundtinsertborderwidtht
insertofftimetinsertontimetinsertwidthtinvalidcommandR�treadonlybackgroundR;tselectbackgroundtselectborderwidthtselectforegroundtshowR�R=R�tvalidatetvalidatecommandR?txscrollcommandcKstj|j|�S(N(R@tEntryRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRCscCs |j�}|j|d�dS(NR�(RtcheckColorParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_disabledbackgroundFsc	CsQ|jdd�}|j|ddddddd	�|j|dd
dd
�dS(NR�idR�ig�������?g������@ii����Rui<Roii2(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertborderwidthJscCs�|j�}|j|dddd�|j|dddd�|j|dddd�td	�d
kr�|j|dd	dd�n|j|dd	dd�dS(NR�g�������?g������@Rug�������?Roii����g�������?ii(RRvRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertwidthQscCs0|j�}|j|d�|j|d�dS(NR�tinvcmd(RtcheckCommandParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_invalidcommand[scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_readonlybackground`scCsI|j�}|j|dd�|j|dd�|j|dd�dS(NR�t*R"t (RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_showdscCs)|j�}|j|dddd�dS(NR�R�R�treadonly(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_statejsc	Cs2|j�}|j|ddddddd�dS(NR�talltkeytfocustfocusintfocusouttnone(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_validateoscCs0|j�}|j|d�|j|d�dS(NR�tvcmd(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_validatecommandts(R1R2R3R�RR�RWRXR5R6R7R�R�R�R�R�R�R�R�R;R�R�R�R�R�R=R�R�R�R?R�(
RR.RSRR�R�R�R�R�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�4s(				
					tSpinboxTestc,Bs�eZd9Zd,�Zd:Zd-�Zd.�Zd/�Zd0�Z	d1�Z
d2�Zd3�Zd4�Z
d5�Zd6�Zd7�Zd8�ZRS(;RzR1R2tbuttonbackgroundtbuttoncursortbuttondownrelieftbuttonupreliefR�R3R�RR�RWRXtformattfromR5R6R7t	incrementR�R�R�R�R�R�R�R;R�R�R�R�R�R�R�R=R�ttoR�R�R�R?twrapR�cKstj|j|�S(N(R@tSpinboxRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttonbackground�scCs |j�}|j|d�dS(NR�(RtcheckCursorParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttoncursor�scCs |j�}|j|d�dS(NR�(RtcheckReliefParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttondownrelief�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_buttonuprelief�scCs�|j�}|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd�|j|dd	�|j|dd
�|j|dd�|j|dd�|j|dd
�dS(NR�s%2fs%2.2fs%.2fs%2.fs%2e-1fs2.2s%2.-2fs%-2.02fs% 2.02fs	% -2.200fs%09.200fs%d(RRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_format�scCsU|j�}|j|dd�|j|dddd�|j|dddd	�dS(
NR�gY@R�i����gffffff$@gffffff'@i�Rs*-to value must be greater than -from value(RRFtcheckFloatParamR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_from�s
cCs/|j�}|j|dddddd�dS(NR�i����igffffff$@g������)@i(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_increment�scCsU|j�}|j|dd�|j|dddd�|j|dddd	�dS(
NR�gY�R�i����gffffff$@gffffff'@i8���Rs*-to value must be greater than -from value(RRFRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_to�s
cCs||j�}|j|dd�|j|dd�|j|dd
dd�|j|dddd�|j|dd�dS(NR�R"smon tue wed thurtmonttuetwedtthurRoi*g��Q�	@s
any strings42 3.14 {} {any string}(RR	R
R(i*g��Q�	@R"s
any string(RRRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_values�scCs |j�}|j|d�dS(NR�(RtcheckBooleanParam(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_wrap�scCs�|j�}|j|jd��|jtj|jd�|jtj|jd�|jt|j�|jt|jdd�dS(Nitnoindexi(RtassertIsBoundingBoxtbboxR�R@RR�t	TypeError(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_bbox�scCsl|j�}|j|j�d�|jd�|j|j�d�|jd�|j|j�d�dS(NR�tbuttonupt
buttondown(RRtselection_element(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selection_element�s

(,RzR1R2R�R�R�R�R�R3R�RR�RWRXR�R�R5R6R7R�R�R�R�R�R�R�R�R;R�R�R�R�R�R�R�R=R�R�R�R�R�R?R�R�N(RR.RSRR�R�R�R�RRRRRRRRRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�zs8												tTextTestc)Bs1eZd@ZedAkr!eZnd+�Zd,�Zed)d*�d-��Z	ed)d*�d.��Z
d/�Zd0�Zed)d*�d1��Z
ed)d2�d3��Zd4�Zd5�Zd6�Zd7�Zed)d*�d8��Zd9�Zd:�Zed)d*�d;��Zd<�Zd=�Zd>�Zd?�ZRS(BtautoseparatorsR1tblockcursorR2R3tendlineR�RWRXR4R5R6R7tinactiveselectbackgroundR�R�R�R�tinsertunfocussedR�tmaxundoR9R:R;R�R�R�tsetgridtspacing1tspacing2tspacing3t	startlineR�ttabsttabstyleR=tundoR?R�R�tyscrollcommandiicKstj|j|�S(N(R@tTextRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_autoseparators�scCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_blockcursor�scCs�|j�}djd�td�D��}|jd|�|j|dddd�|j|dd	dd�|j|dd
dd�|j|dd
�|j|dd�|j|dddd�dS(Ns
css|]}dVqdS(sLine %dN((t.0ti((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>sidtendRi�RoR"i����R�Rsexpected integer but got "spam"i2R#ii
s1-startline must be less than or equal to -endline(RtjointrangetinsertRFR(RRR[((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_endlinescCs^|j�}|j|ddddd�|j|dddd�|j|dd	dd�dS(
NR4idg�����LY@gfffff�Y@t3ci����Roii(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NRiii����(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_maxundoscCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_inactiveselectbackgroundsicCs)|j�}|j|dddd�dS(NRthollowR�tsolid(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_insertunfocussedsc
Cs>|j�}|j|ddddddtdtd
k�dS(NR�g�������?g������@i����RuR�t	keep_origii(ii(RRvRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selectborderwidth$scCsE|j�}|j|ddddd�|j|dddd�dS(	NR igffffff5@g������6@s0.5ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing1*scCsE|j�}|j|ddddd�|j|dddd�dS(	NR!ig������@gffffff@s0.1ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing2/scCsE|j�}|j|ddddd�|j|dddd�dS(	NR"igffffff5@g������6@s0.5ci����Roi(RRvRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_spacing34scCs�|j�}djd�td�D��}|jd|�|j|dddd�|j|dd	dd�|j|dd
dd�|j|dd
�|j|dd�|j|dddd�dS(Ns
css|]}dVqdS(sLine %dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr><sidR-R#i�RoR"i����R�Rsexpected integer but got "spam"i
Ri2iFs1-startline must be less than or equal to -endline(RR.R/R0RFR(RRR[((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_startline9scCsK|j�}tdkr1|j|ddd�n|j|ddd�dS(NiiR�R�R�(ii(RRR�Rj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�Gsc
Cs�|j�}t�dkr7|j|ddd	d�n|j|dd�|j|ddd	d�|j|dd
d	d�|j|dddddtdk�dS(NiiiR$gffffff$@g33333�4@t1it2iRos10.2s20.7s10.2 20.7 1i 2is2c left 4c 6c centert2cR�t4ct6cRiR�Rsbad screen distance "spam"R8(iii(gffffff$@g33333�4@R>R?(s10.2s20.7R>R?(gffffff$@g33333�4@R>R?(s10.2s20.7R>R?(R@R�RARBRi(ii(RRRFRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_tabsNs
cCs&|j�}|j|ddd�dS(NR%ttabulart
wordprocessor(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_tabstyle]scCs |j�}|j|d�dS(NR&(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_undobscCsU|j�}|j|dd�|j|dddd�|j|dddd�dS(NR?i�in���Roii(RR�RF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�fscCsQ|j�}tdkr4|j|dddd�n|j|dddd�dS(NiiR�tcharR�tword(ii(RRR�Rj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRlscCs�|j�}|j|jd��|j|jd��|jtj|jd�|jtj|jd�|jtj|j�|jtj|jdd�dS(Ns1.1R-R(RRRtassertIsNoneR�R@RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRss()RR1RR2R3RR�RWRXR4R5R6R7RR�R�R�R�RR�RR9R:R;R�R�R�RR R!R"R#R�R$R%R=R&R?R�R�R'(ii(RR.RSRR)t
_stringifyRR)RR*R1R�R3R4R7R9R:R;R<R=R�RCRFRGR�RR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�sB														t
CanvasTestcBsheZd#Zee�ZeZd�Zd�Z	d�Z
d�Zd�Zd �Z
d!�Zd"�ZRS($R1R2tcloseenoughtconfineR3R4R5R6R7R�R�R�R�R�toffsetR;tscrollregionR�R�R�R�R=R�txscrollincrementR'tyscrollincrementR?cKstj|j|�S(N(R@tCanvasRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�sc	Cs2|j�}|j|ddddddt�dS(NRMig333333@g������@i����R�(RRtfloat(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_closeenough�scCs |j�}|j|d�dS(NRN(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_confine�scCs�|j�}|j|dd�|j|dddddddd	d
d�|j|dd�|j|dd
�|j|dd�dS(NROs0,0R`RaR]RdRcReRfRbRis10,20s#5,6R�(RRR�RFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_offset�scCs�|j�}|j|dd�|j|dddd�|j|dd�|j|ddd	d
�|j|dd�|j|dd
�|j|dd�dS(NRPs0 0 200 150ii�i�RoR"R�Rsbad scrollRegion "spam"(iii�i�(iii�R�(iii�(iii�i�i(RRFR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_scrollregion�scCs,|j�}|j|ddddd�dS(NR�R�R�Rs0bad state value "{}": must be normal or disabled(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sc	Cs2|j�}|j|ddddddd�dS(NRQi(ig������D@g������E@i���s0.5i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_xscrollincrement�sc	Cs2|j�}|j|ddddddd�dS(NRRi
igffffff&@g333333+@i����s0.1i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_yscrollincrement�s(R1R2RMRNR3R4R5R6R7R�R�R�R�R�ROR;RPR�R�R�R�R=R�RQR'RRR?(RR.RSR�R
RxR)RKRRURVRWRXR�RYRZ(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRL}s(								tListboxTestcBs�eZd,Zd�Zd�Zeddd�ejj�Zd�Z	d�Z
d �Zd!�Zd"�Z
d#�Zd$�Zd%�Zd&�Zd'�Zd(�Zd)�Zd*�Zd+�ZRS(-tactivestyleR1R2R3RR�RWRXR4R5R6R7R�tlistvariableR;R�R�R�t
selectmodeRR�R=R?R�R'cKstj|j|�S(N(R@tListboxRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NR\tdotboxR�R�(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_activestyle�siiicCs5|j�}tj|j�}|j|d|�dS(NR](RR@t	DoubleVarRBtcheckVariableParam(RRtvar((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_listvariable�scCs\|j�}|j|dd�|j|dd�|j|dd�|j|dd�dS(NR^tsingletbrowsetmultipletextended(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_selectmode�s
cCs&|j�}|j|ddd�dS(NR�R�R�(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sc
Cs�|j�}|jtd��|jd�WdQXdj�}|jd|�x-t|�D]\}}|j|d|�q[W|jt��|j�WdQX|jtd��|jd�WdQX|j	|jdd�d�|j	|jdd�d�|j	|jdd�d�|jd�}|j
|t�x�|j�D]s\}}|j
t|�d�t|�d
krD|j	||jd|��|j	|d|jd|��qDqDWdS(Nsitem number "0" out of rangeis)red orange yellow green blue white violetR-R1sbad listbox index "red"tredt
BackgroundR"tviolets@0,0iii(R1R1RlR"Rk(R1R1RlR"Rm(R1R1RlR"Rk(ii(RtassertRaisesRegexpRt
itemconfiguretsplitR0t	enumerateR�RRtassertIsInstancetdicttitemstassertIntlentitemcget(RRtcolorsR,tcolortdtktv((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure�s0c	Cs�|j�}|jddddd�|jdi||6�|j|jd|�d|�|j|jd|�|�|jtd��|jdid	|6�WdQXdS(
NR-R�R�R�Rziisunknown color name "spam"R�(RR0RoRRwRnR(RRmR�R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_itemconfigures cCs|jdd�dS(NR1s#ff0000(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_backgroundscCs|jdd�dS(Ntbgs#ff0000(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_bgscCs|jdd�dS(Ntfgs#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_fgscCs|jdd�dS(NRXs#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_itemconfigure_foregroundscCs|jdd�dS(NR�s#110022(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt#test_itemconfigure_selectbackgroundscCs|jdd�dS(NR�s#654321(R~(R((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt#test_itemconfigure_selectforegroundscCs�|j�}|jdd�td�D��|j�|j|jd��|j|jd��|j|jd��|jt|jd�|jt|jd�|jt
|j�|jt
|jdd�dS(Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>sii����i
Ri(RR0R/tpackRRRJR�RR�R(Rtlb((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_boxs 
cCs�|j�}|jdd�td�D��|jdtj�|jdd�|jd�|j|j�d�|j	t
|jd�dS(	Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>+siiiii(iiii(RR0R/tselection_clearR@tENDt
selection_setRtcurselectionR�R(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_curselection)s 
cCs�|j�}|jdd�td�D��|j|jd�d�|j|jd�d�|j|jd�d�|j|jd�d	�|j|jd
�d	�|j|jdd�d�|j|jdd�d�|j|jdd�d�|j|jdd�d�|jt|jd�|jt|jd�|jt|j�|jt|jdd�|jt|jddd�|jt|jd�dS(Nicss|]}d|VqdS(sel%dN((R+R,((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pys	<genexpr>4sitel0itel3R-tel7R"i����itel4tel5tel6Riig333333@(R�R�R�(R�R�R�((R�(	RR0R/RtgetR�RR�R(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_get2s" (R\R1R2R3RR�RWRXR4R5R6R7R�R]R;R�R�R�R^RR�R=R?R�R'(RR.RSRRaRR
ttest_justifyR�ReRjR�R}R~RR�R�R�R�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR[�s2																	t	ScaleTestcBs�eZd+ZdZd�Zd �Zd!�Zd"�Zd#�Zd$�Z	d%�Z
d&�Zd'�Zd(�Z
d)�Zd*�ZRS(,RzR1tbigincrementR2R�R3tdigitsRWRXR�R5R6R7RrtlengthtorientR;R�R�t
resolutiont	showvaluetsliderlengthtsliderreliefR�R=ttickintervalR�ttroughcolorR�R?tverticalcKstj|j|�S(N(R@tScaleRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRSscCs)|j�}|j|dddd�dS(NR�g������(@g������7@i����(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_bigincrementVscCs&|j�}|j|ddd�dS(NR�ii(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_digitsZscCs/|j�}|j|dddddt�dS(NR�idg������-@g333333.@R�(RRtround(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR^scCs6|j�}|j|dd�|j|dd�dS(NRrs
any stringR"(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_labelbscCs,|j�}|j|ddddd�dS(NR�i�gffffff`@g33333�`@t5i(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_lengthgscCs,|j�}|j|ddddd�dS(NR�g������@ig������@i����(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_resolutionkscCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_showvalueoscCs/|j�}|j|dddddd�dS(NR�i
gffffff&@g333333/@i����t3m(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sliderlengthsscCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sliderreliefxsc	CsQ|j�}|j|ddddddt�|j|dddd	dt�dS(
NR�ig333333@gffffff@iR�i����Roi(RRR�RF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tickinterval|s
c	Cs2|j�}|j|ddddddt�dS(NR�i,g������-@g333333.@i����R�(RRR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s(RzR1R�R2R�R3R�RWRXR�R5R6R7RrR�R�R;R�R�R�R�R�R�R�R=R�R�R�R�R?(RR.RStdefault_orientRR�R�RR�R�R�R�R�R�R�R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�Fs(											t
ScrollbarTestcBs\eZdZee�ZeZdZd�Z	d�Z
d�Zd�Zd�Z
d�ZRS(RztactivereliefR1R2R�R3telementborderwidthR5R6R7tjumpR�R;R�R�R=R�R?R�cKstj|j|�S(N(R@t	ScrollbarRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_activerelief�scCs,|j�}|j|ddddd�dS(NR�g333333@gffffff@i����t1m(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_elementborderwidth�scCs,|j�}|j|ddddd�dS(NR�R�t
horizontalRs4bad orientation "{}": must be vertical or horizontal(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_orient�scCsg|j�}xdD]}|j|�qW|jd�|jt|j�|jt|jdd�dS(Ntarrow1tslidertarrow2R"(R�R�R�(RtactivateR�R(RtsbR]((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_activate�s

cCs�|j�}|jdd�|j|j�d�|jt|jdd�|jt|jdd�|jt|jdd�|jt|jd�|jt|jddd�dS(	Ng�������?g�������?tabctdefg333333�?gffffff�?g�������?(g�������?g�������?(RtsetRR�R�RR�(RR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_set�s(RzR�R1R2R�R3R�R5R6R7R�R�R;R�R�R=R�R?(RR.RSR�R
RxR)RKR�RR�R�R�R�R�(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s 					tPanedWindowTestcBsgeZd2ZdZd�Zd�Zd�Zd�Zd�Ze	ddd�d��Z
e	ddd�d��Ze	ddd�d��Zd�Z
d�Zd �Zd!�Zd"�Zd#�Zd$�Zd%�Zed&�Zd'�Zd(�Zd)�Zd*�Ze	dd�d+��Zd,�Zd-�Zd.�Zd/�Ze	dd�d0��Z d1�Z!RS(3R1R2R3t	handlepadt
handlesizeR4topaqueresizeR�tproxybackgroundtproxyborderwidthtproxyreliefR;t
sashcursortsashpadt
sashrelieft	sashwidtht
showhandleR?R�cKstj|j|�S(N(R@tPanedWindowRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs/|j�}|j|dddddd�dS(NR�ig������@gffffff@i����R�(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_handlepad�sc
Cs5|j�}|j|dddddddt�dS(NR�ig������"@g333333%@i����t2mR�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_handlesize�scCs8|j�}|j|ddddddddt�dS(	NR4idg�����LY@gfffff�Y@i����iR>R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��s!cCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_opaqueresize�siiicCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxybackground�scCs8|j�}|j|ddddddddt�dS(	NR�ig�������?g333333@ii����RuR�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxyborderwidth�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_proxyrelief�scCs |j�}|j|d�dS(NR�(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashcursor�scCs/|j�}|j|dddddd�dS(NR�ig�������?g������@i����R�(RRv(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashpad�scCs |j�}|j|d�dS(NR�(RR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashrelief�sc
Cs5|j�}|j|dddddddt�dS(NR�i
g333333&@g333333/@i����R�R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_sashwidth�scCs |j�}|j|d�dS(NR�(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_showhandle�scCs8|j�}|j|ddddddddt�dS(	NR?i�gfffff6y@g�����Iy@in���iR�R�(RRvR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s!cCsQ|j�}tj|�}tj|�}|j|�|j|�|||fS(N(RR@R�tadd(RtpR�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcreate2s

cCs�|j�\}}}|jt|j�|j|�}|j|t�xl|j�D]^\}}|jt|�d�|j||j||��|j|d|j	||��qTWdS(Nii(
R�R�Rt
paneconfigureRrRsRtRRvtpanecget(RR�R�R�RzR{R|((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigurescCs�d�}|js|r(t|�}n|jr@|r@t}n|j|i||6�|j||j||�d�|�|j||j||��|�dS(NcSs|S(N((tx((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt<lambda>R"i(R(R�R�RR�(RR�R�RmR�Rot	stringifyR�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_paneconfigures		&c	Cs4|jt|��|j|id|6�WdQXdS(NtbadValue(RnRR�(RR�R�Rmtmsg((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pytcheck_paneconfigure_bad$scCsN|j�\}}}|j||d|t|��|j||dd�dS(Ntaftersbad window path name "badValue"(R�R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_after(scCsN|j�\}}}|j||d|t|��|j||dd�dS(Ntbeforesbad window path name "badValue"(R�R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_before.scCsW|j�\}}}|j||ddddt�dk�|j||dd�dS(	NR4i
R�iiisbad screen distance "badValue"(iii(R�R�RR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_height4s
cCsH|j�\}}}|j||dtd�|j||dd�dS(Nthideis)expected boolean value but got "badValue"(R�R�tFalseR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_hide;scCsH|j�\}}}|j||ddd�|j||dd�dS(Ntminsizei
sbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_minsizeBscCsH|j�\}}}|j||ddd�|j||dd�dS(NR9g�������?isbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_padxHscCsH|j�\}}}|j||ddd�|j||dd�dS(NR:g�������?isbad screen distance "badValue"(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_padyNscCsH|j�\}}}|j||ddd�|j||dd�dS(Ntstickytnsewtnesws[bad stickyness value "badValue": must be a string containing zero or more of n, e, s, and w(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_stickyTscCsH|j�\}}}|j||ddd�|j||dd�dS(NtstretchtalwtalwayssEbad stretch "badValue": must be always, first, last, middle, or never(R�R�R�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_stretch\scCsW|j�\}}}|j||ddddt�dk�|j||dd�dS(	NR?i
R�iiisbad screen distance "badValue"(iii(R�R�RR�(RR�R�R�((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_paneconfigure_widthds
(R1R2R3R�R�R4R�R�R�R�R�R;R�R�R�R�R�R?("RR.RSR�RR�R�R�R�RR�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R�R(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR��sH													

								tMenuTestcBseeZdZeZd�Zd�Zd�Zd�Zd�Z	d�Z
d�Zd�Zd�Z
RS(RztactiveborderwidthR{R1R2R3RRWRXtpostcommandR;R�R=ttearoffttearoffcommandRttypecKstj|j|�S(N(R@RERB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRwscCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_postcommandzscCs |j�}|j|d�dS(NR(RR
(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tearoff~scCs |j�}|j|d�dS(NR(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_tearoffcommand�scCs#|j�}|j|dd�dS(NRs
any string(RRF(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt
test_title�scCs)|j�}|j|dddd�dS(NRR�Rtmenubar(RRj(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt	test_type�scCs	|j�}|jdd�|jt|j�|jtd��|jd�WdQX|jd�}|j|t�x�|j	�D]v\}}|j|t
�|j|t�|jt
|�d�|j|d|�|j|jd|�|d�q�W|j�dS(	NRrttestsbad menu entry index "foo"Rniiii(Rtadd_commandR�RtentryconfigureRnRRrRsRtR�ttupleRRvt	entrycgetRq(Rtm1RzR{R|((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure�s$cCsk|j�}|jdd�|j|jdd�d�|jddd�|j|jdd�d�dS(NRrR
itchanged(RRRRR(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure_label�s
c	Cs�|j�}tj|j�}tj|j�}|jd|dtdtdd�|jt|j	dd��t|��|j
dd|�|jt|j	dd��t|��dS(NR�R�R�RrtNonsensei(RR@t
BooleanVarRBtadd_checkbuttonR)R�RR�RR(RRtv1tv2((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_entryconfigure_variable�s((RzRR{R1R2R3RRWRXRR;R�R=RRRR(RR.RSR	RxRRRR	R
RRRR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyRls								tMessageTestcBs&eZdZeZd�Zd�ZRS(R|taspectR1R2R3RWRXR5R6R7R�R9R:R;R=R[R�R?cKstj|j|�S(N(R@tMessageRB(RRC((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�scCs)|j�}|j|dddd�dS(NRi�ii���(RR�(RR((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyttest_aspect�s(R|RR1R2R3RWRXR5R6R7R�R9R:R;R=R[R�R?(RR.RSR	R/RR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyR�s	t__main__(1R�tTkinterR@RRIR�ttest.test_supportRRttest_ttk.supportRRRRtwidget_testsRRR	R
RRR
RRRRtTestCaseR0RTRVRtRyR�R�R�R�R�R�R�RRLR[R�R�R�RRt	tests_guiR(((s=/usr/lib64/python2.7/lib-tk/test/test_tkinter/test_widgets.pyt<module>sl"F
%(	AEh�B�B1�DPK1[�1����0Structures_LinkedList/tests/single_link_007.phptnu�[���--TEST--
single_link_007: Test many corner cases
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single();

// prepend to an empty list corner case: 1
$xyy->prependNode($tester1);
print "Current: {$xyy->current()->getNumb()}\n";

// prepend to a list with only one element: 21
$xyy->prependNode($tester2);
print "Current: {$xyy->current()->getNumb()}\n";

// insert after tail node corner case: 213
$xyy->insertNode($tester3, $tester1);
print "Current: {$xyy->current()->getNumb()}\n";

// insert before root node corner case: 4213
$xyy->insertNode($tester4, $tester2, true);
print "Current: {$xyy->current()->getNumb()}\n";

// insert before tail node corner case: 42153
$xyy->insertNode($tester5, $tester3, true);
print "Current: {$xyy->current()->getNumb()}\n";

print "Foreach: ";
foreach ($xyy as $node) {
    print $node->getNumb();
}

print "\nWhile (in reverse): ";
// test reverse iteration with while()
$link = $xyy->end();
do {
    print $link->getNumb();
} while ($link = $xyy->previous());
?>
--EXPECT--
Current: 1
Current: 1
Current: 1
Current: 1
Current: 1
Foreach: 42153
While (in reverse): 35124
PK1[�Z�x��0Structures_LinkedList/tests/single_link_002.phptnu�[���--TEST--
single_link_002: Append links to an initially empty linked list
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single();
$xyy->appendNode($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->insertNode($tester4, $tester2, true);

$link = $xyy->current();
print $link->getNumb();

// test iteration with while()
while ($link = $xyy->next()) {
    print $link->getNumb();
}
$link = $xyy->rewind();
print "\n";
print $link->getNumb();
print "\n";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
1423
1
1423
PK1[(��  )Structures_LinkedList/tests/link_004.phptnu�[���--TEST--
link_004: Delete every link in the list
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->appendNode($tester4);

// Delete all nodes from the list
while ($link = $xyy->rewind()) {
    print "Deleted " . $link->getNumb() . "\n";
    $xyy->deleteNode($link);
}
$link = $xyy->rewind();
print "Done\n";
?>
--EXPECT--
Deleted 1
Deleted 2
Deleted 3
Deleted 4
Done
PK1[���|��0Structures_LinkedList/tests/SingleLinkTester.phpnu�[���<?php
class LinkTester extends Structures_LinkedList_SingleNode {
    protected $_my_number;

    function __construct($num) {
        $this->_my_number = $num;
    }

    function getNumb() {
        return $this->_my_number;
    }

    function setNumb($numb) {
        $this->_my_number = $numb;
    }
}

$tester1 = new LinkTester(1);
$tester2 = new LinkTester(2);
$tester3 = new LinkTester(3);
$tester4 = new LinkTester(4);
$tester5 = new LinkTester(5);

?>
PK1[髂[��0Structures_LinkedList/tests/single_link_006.phptnu�[���--TEST--
single_link_006: Corner case: add a node before the root
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single();
$xyy->prependNode($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->insertNode($tester4, $tester2, true);

// Ensure we can increment the current node without messing up the list
print "\nCurrent: " . $xyy->current()->getNumb() . "\n";
$link = $xyy->next();
print "Current: " . $link->getNumb() . "\n";

$xyy->insertNode($tester5, $tester1, true);

print "\n";

$link = $xyy->current();
print "Current: " . $link->getNumb();

print "\n\nWhile: ";
// test iteration with while()
$link = $xyy->rewind();
do {
    print $link->getNumb();
} while ($link = $xyy->next());

print "\n\nForeach: ";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
Current: 1
Current: 4

Current: 4

While: 51423

Foreach: 51423
PK 1[s��DHH)Structures_LinkedList/tests/link_007.phptnu�[���--TEST--
link_007: Test many corner cases
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double();

// prepend to an empty list corner case: 1
$xyy->prependNode($tester1);
print "Current: {$xyy->current()->getNumb()}\n";

// prepend to a list with only one element: 21
$xyy->prependNode($tester2);
print "Current: {$xyy->current()->getNumb()}\n";

// insert after tail node corner case: 213
$xyy->insertNode($tester3, $tester1);
print "Current: {$xyy->current()->getNumb()}\n";

// insert before root node corner case: 4213
$xyy->insertNode($tester4, $tester2, true);
print "Current: {$xyy->current()->getNumb()}\n";

// insert before tail node corner case: 42153
$xyy->insertNode($tester5, $tester3, true);
print "Current: {$xyy->current()->getNumb()}\n";

// insert after root node corner case: 421653
$xyy->insertNode($tester6, $tester1);
print "Current: {$xyy->current()->getNumb()}\n";

print "Foreach: ";
foreach ($xyy as $node) {
    print $node->getNumb();
}

print "\nWhile (in reverse): ";
// test reverse iteration with while()
$link = $xyy->end();
do {
    print $link->getNumb();
} while ($link = $xyy->previous());
?>
--EXPECT--
Current: 1
Current: 1
Current: 1
Current: 1
Current: 1
Current: 1
Foreach: 421653
While (in reverse): 356124
PK 1[�����)Structures_LinkedList/tests/link_005.phptnu�[���--TEST--
link_005: Pass different class types to constructors
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';

class TesterExtend extends Structures_LinkedList_DoubleNode {
    protected $_my_number;

    function __construct($tester, $num) {
        $this->_my_number = $num;
        parent::__construct($tester);
    }
}

class TesterFail {
    protected $summary;
    protected $fulltext;

    function __construct($summary, $fulltext) {
        $this->summary = $summary;
        $this->fulltext = $fulltext;
    }
}


// This should work: TesterExtend extends the Structure_LinkedList_DoubleNode class
$tester_extend = new TesterExtend(null, 1);
$xyy = new Structures_LinkedList_Double($tester_extend);
print "Checking for errors in the expected success case:\n";

// This should fail
print "Checking for errors in the expected failure case:\n";
$tester_fail = new TesterFail(null, 1);
$xyy_fail = new Structures_LinkedList_Double($tester_fail);
?>
--EXPECTF--
Checking for errors in the expected success case:
Checking for errors in the expected failure case:

%satal error: Argument 1 passed to Structures_LinkedList_Double::__construct() must be an instance of Structures_LinkedList_DoubleNode%s
PK 1[�#,E��0Structures_LinkedList/tests/single_link_005.phptnu�[���--TEST--
single_link_005: Pass different class types to constructors
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';

class TesterExtend extends Structures_LinkedList_SingleNode {
    protected $_my_number;

    function __construct($tester, $num) {
        $this->_my_number = $num;
        parent::__construct($tester);
    }
}

class TesterFail {
    protected $summary;
    protected $fulltext;

    function __construct($summary, $fulltext) {
        $this->summary = $summary;
        $this->fulltext = $fulltext;
    }
}


// This should work: TesterExtend extends the Structure_LinkedList_SingleNode class
$tester_extend = new TesterExtend(null, 1);
$xyy = new Structures_LinkedList_Single($tester_extend);
print "Checking for errors in the expected success case:\n";

// This should fail
print "Checking for errors in the expected failure case:\n";
$tester_fail = new TesterFail(null, 1);
$xyy_fail = new Structures_LinkedList_Single($tester_fail);
?>
--EXPECTF--
Checking for errors in the expected success case:
Checking for errors in the expected failure case:

%satal error: Argument 1 passed to Structures_LinkedList_Single::__construct() must be an instance of Structures_LinkedList_SingleNode%s
PK 1[����*Structures_LinkedList/tests/LinkTester.phpnu�[���<?php
class LinkTester extends Structures_LinkedList_DoubleNode {
    protected $_my_number;

    function __construct($num) {
        $this->_my_number = $num;
    }

    function getNumb() {
        return $this->_my_number;
    }

    function setNumb($numb) {
        $this->_my_number = $numb;
    }
}

$tester1 = new LinkTester(1);
$tester2 = new LinkTester(2);
$tester3 = new LinkTester(3);
$tester4 = new LinkTester(4);
$tester5 = new LinkTester(5);
$tester6 = new LinkTester(6);

?>
PK 1[� ���)Structures_LinkedList/tests/link_001.phptnu�[���--TEST--
link_001: Test linked list constructed with an initial link
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->appendNode($tester4);

$link = $xyy->current();
print "Current: " . $link->getNumb() . "\n";

print "While: ";
// test iteration with while()
do {
    print $link->getNumb();
} while ($link = $xyy->next());

print "\nRewind: ";
$link = $xyy->rewind();
print $link->getNumb();
print "\n";

print "Foreach: ";
// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}

print "\nEnd: ";
$link = $xyy->end();
print $link->getNumb();
print "\n";

print "While (in reverse): ";
// test iteration with while()
do {
    print $link->getNumb();
} while ($link = $xyy->previous());


?>
--EXPECT--
Current: 1
While: 1234
Rewind: 1
Foreach: 1234
End: 4
While (in reverse): 4321
PK 1[骗���)Structures_LinkedList/tests/link_006.phptnu�[���--TEST--
link_006: Corner case: add a node before the root
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double();
$xyy->prependNode($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->insertNode($tester4, $tester2, true);

// Ensure we can increment the current node without messing up the list
print "\nCurrent: " . $xyy->current()->getNumb() . "\n";
$link = $xyy->next();
print "Current: " . $link->getNumb() . "\n";

$xyy->insertNode($tester5, $tester1, true);

print "\n";

$link = $xyy->current();
print "Current: " . $link->getNumb();

print "\n\nWhile: ";
// test iteration with while()
$link = $xyy->rewind();
do {
    print $link->getNumb();
} while ($link = $xyy->next());

print "\n\nForeach: ";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
Current: 1
Current: 4

Current: 4

While: 51423

Foreach: 51423
PK 1[��)��)Structures_LinkedList/tests/link_002.phptnu�[���--TEST--
link_002: Append links to an initially empty linked list
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double();
$xyy->appendNode($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->insertNode($tester4, $tester2, true);

$link = $xyy->current();
print $link->getNumb();

// test iteration with while()
while ($link = $xyy->next()) {
    print $link->getNumb();
}
$link = $xyy->rewind();
print "\n";
print $link->getNumb();
print "\n";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
1423
1
1423
PK 1[�4����0Structures_LinkedList/tests/single_link_001.phptnu�[���--TEST--
single_link_001: Test linked list constructed with an initial link
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->appendNode($tester4);

$link = $xyy->current();
print "Current: " . $link->getNumb() . "\n";

print "While: ";
// test iteration with while()
do {
    print $link->getNumb();
} while ($link = $xyy->next());

print "\nRewind: ";
$link = $xyy->rewind();
print $link->getNumb();
print "\n";

print "Foreach: ";
// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}

print "\nEnd: ";
$link = $xyy->end();
print $link->getNumb();
print "\n";

print "While (in reverse): ";
// test iteration with while()
do {
    print $link->getNumb();
} while ($link = $xyy->previous());


?>
--EXPECT--
Current: 1
While: 1234
Rewind: 1
Foreach: 1234
End: 4
While (in reverse): 4321
PK 1[)�y--0Structures_LinkedList/tests/single_link_004.phptnu�[���--TEST--
single_link_004: Delete every link in the list
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single($tester1);
$xyy->appendNode($tester2);
$xyy->appendNode($tester3);
$xyy->appendNode($tester4);

// Delete all nodes from the list
while ($link = $xyy->rewind()) {
    print "Deleted " . $link->getNumb() . "\n";
    $xyy->deleteNode($link);
}
$link = $xyy->rewind();
print "Done\n";
?>
--EXPECT--
Deleted 1
Deleted 2
Deleted 3
Deleted 4
Done
PK 1[�K��0Structures_LinkedList/tests/single_link_003.phptnu�[���--TEST--
single_link_003: Append links in a specific order
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Single.php';
require 'SingleLinkTester.php';

$xyy = new Structures_LinkedList_Single();

// add initial link in the list
$xyy->appendNode($tester1);
print $tester1->getNumb() . "\n";

// add after initial link
$xyy->appendNode($tester2);
print $tester2->getNumb() . "\n";

// add after initial link, bumping #2 up
$xyy->insertNode($tester3, $tester1);
print $tester3->getNumb() . "\n";

// add after link #3, bumping #2 up again
$xyy->insertNode($tester4, $tester3);
print $tester4->getNumb() . "\n";

print "\n";

$link = $xyy->current();
print $link->getNumb();
print "\n";

// test iteration with while()
while ($link = $xyy->next()) {
    print $link->getNumb();
    print "\n";
}
$link = $xyy->rewind();
print "\n";
print $link->getNumb();
print "\n";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
1
2
3
4

1
3
4
2

1
1342
PK 1[�o���)Structures_LinkedList/tests/link_003.phptnu�[���--TEST--
link_003: Append links in a specific order
--FILE--
<?php
 
$dir = dirname(__FILE__);
require 'Structures/LinkedList/Double.php';
require 'LinkTester.php';

$xyy = new Structures_LinkedList_Double();

// add initial link in the list
$xyy->appendNode($tester1);
print $tester1->getNumb() . "\n";

// add after initial link
$xyy->appendNode($tester2);
print $tester2->getNumb() . "\n";

// add after initial link, bumping #2 up
$xyy->insertNode($tester3, $tester1);
print $tester3->getNumb() . "\n";

// add after link #3, bumping #2 up again
$xyy->insertNode($tester4, $tester3);
print $tester4->getNumb() . "\n";

print "\n";

$link = $xyy->current();
print $link->getNumb();
print "\n";

// test iteration with while()
while ($link = $xyy->next()) {
    print $link->getNumb();
    print "\n";
}
$link = $xyy->rewind();
print "\n";
print $link->getNumb();
print "\n";

// test foreach() iteration
foreach ($xyy as $bull) {
  print $bull->getNumb();
}
?>
--EXPECT--
1
2
3
4

1
3
4
2

1
1342
PK 1[�x`(��Mail/tests/bug17317.phptnu�[���--TEST--
Mail_RFC822::parseAddressList invalid periods in mail address
--FILE--
<?php
require "Mail/RFC822.php";

$result[] = Mail_RFC822::parseAddressList('.name@example.com');
$result[] = Mail_RFC822::parseAddressList('name.@example.com');
$result[] = Mail_RFC822::parseAddressList('name..name@example.com');

foreach ($result as $r) {
    if (is_a($r, 'PEAR_Error')) {
        echo "OK\n";
    }
}
--EXPECT--
OK
OK
OK
PK 1[��q/��Mail/tests/13659.phptnu�[���--TEST--
Mail: Test for bug #13659
--FILE--
<?php
//require_once dirname(__FILE__) . '/../Mail/RFC822.php';
require_once 'Mail/RFC822.php';
require_once 'PEAR.php';

$address = '"Test Student" <test@mydomain.com> (test)';
$parser = new Mail_RFC822();
$result = $parser->parseAddressList($address, 'anydomain.com', TRUE);

if (!PEAR::isError($result) && is_array($result) && is_object($result[0]))
    if ($result[0]->personal == '"Test Student"' &&
        $result[0]->mailbox == "test" &&
	$result[0]->host == "mydomain.com" &&
	is_array($result[0]->comment) && $result[0]->comment[0] == 'test')
    {
        print("OK");
    }


?>
--EXPECT--
OK
PK 1[��Mail/tests/9137_2.phptnu�[���--TEST--
Mail: Test for bug #9137, take 2
--FILE--
<?php

require_once dirname(__FILE__) . '/../Mail/RFC822.php';
require_once 'PEAR.php';

$addresses = array(
    array('raw' => '"John Doe" <test@example.com>'),
    array('raw' => '"John Doe' . chr(92) . '" <test@example.com>'),
    array('raw' => '"John Doe' . chr(92) . chr(92) . '" <test@example.com>'),
    array('raw' => '"John Doe' . chr(92) . chr(92) . chr(92) . '" <test@example.com>'),
    array('raw' => '"John Doe' . chr(92) . chr(92) . chr(92) . chr(92) . '" <test@example.com>'),
    array('raw' => '"John Doe <test@example.com>'),
);

for ($i = 0; $i < count($addresses); $i++) {
    // construct the address
    $address = $addresses[$i]['raw'];
    $parsedAddresses = Mail_RFC822::parseAddressList($address);
    if (PEAR::isError($parsedAddresses)) {
        echo $address." :: Failed to validate\n";
    } else {
        echo $address." :: Parsed\n";
    }
}

--EXPECT--
"John Doe" <test@example.com> :: Parsed
"John Doe\" <test@example.com> :: Failed to validate
"John Doe\\" <test@example.com> :: Parsed
"John Doe\\\" <test@example.com> :: Failed to validate
"John Doe\\\\" <test@example.com> :: Parsed
"John Doe <test@example.com> :: Failed to validate
PK 1[w�����Mail/tests/smtp_error.phptnu�[���--TEST--
Mail: SMTP Error Reporting
--SKIPIF--
<?php

require_once 'PEAR/Registry.php';
$registry = new PEAR_Registry();

if (!$registry->packageExists('Net_SMTP')) die("skip\n");
--FILE--
<?php
require_once 'Mail.php';

/* Reference a bogus SMTP server address to guarantee a connection failure. */
$params = array('host' => 'bogus.host.tld');

/* Create our SMTP-based mailer object. */
$mailer = Mail::factory('smtp', $params);

/* Attempt to send an empty message in order to trigger an error. */
$e = $mailer->send(array(), array(), '');
if (is_a($e, 'PEAR_Error')) {
     $err = $e->getMessage();
     if (preg_match('/Failed to connect to bogus.host.tld:25 \[SMTP: Failed to connect socket:.*/i', $err)) {
        echo "OK";
     }
}

--EXPECT--
OKPK 1[)f$�!!Mail/tests/rfc822.phptnu�[���--TEST--
Mail_RFC822: Address Parsing
--FILE--
<?php
require_once 'Mail/RFC822.php';

$parser = new Mail_RFC822();

/* A simple, bare address. */
$address = 'user@example.com';
print_r($parser->parseAddressList($address, null, true, true));

/* Address groups. */
$address = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
print_r($parser->parseAddressList($address, null, true, true));

/* A valid address with spaces in the local part. */
$address = '<"Jon Parise"@php.net>';
print_r($parser->parseAddressList($address, null, true, true));

/* An invalid address with spaces in the local part. */
$address = '<Jon Parise@php.net>';
$result = $parser->parseAddressList($address, null, true, true);
if (is_a($result, 'PEAR_Error')) echo $result->getMessage() . "\n";

/* A valid address with an uncommon TLD. */
$address = 'jon@host.longtld';
$result = $parser->parseAddressList($address, null, true, true);
if (is_a($result, 'PEAR_Error')) echo $result->getMessage() . "\n";

--EXPECT--
Array
(
    [0] => stdClass Object
        (
            [personal] => 
            [comment] => Array
                (
                )

            [mailbox] => user
            [host] => example.com
        )

)
Array
(
    [0] => stdClass Object
        (
            [groupname] => My Group
            [addresses] => Array
                (
                    [0] => stdClass Object
                        (
                            [personal] => "Richard"
                            [comment] => Array
                                (
                                    [0] => A comment
                                )

                            [mailbox] => richard
                            [host] => localhost
                        )

                    [1] => stdClass Object
                        (
                            [personal] => 
                            [comment] => Array
                                (
                                    [0] => Ted Bloggs
                                )

                            [mailbox] => ted
                            [host] => example.com
                        )

                    [2] => stdClass Object
                        (
                            [personal] => 
                            [comment] => Array
                                (
                                )

                            [mailbox] => Barney
                            [host] => localhost
                        )

                )

        )

)
Array
(
    [0] => stdClass Object
        (
            [personal] => 
            [comment] => Array
                (
                )

            [mailbox] => "Jon Parise"
            [host] => php.net
        )

)
Validation failed for: <Jon Parise@php.net>
PK 1[8x����Mail/tests/bug17178.phptnu�[���--TEST--
Mail_RFC822::parseAddressList does not accept RFC-valid group syntax
--FILE--
<?php
require "Mail/RFC822.php";

var_dump(Mail_RFC822::parseAddressList("empty-group:;","invalid",false,false)); 

--EXPECT--
array(0) {
} 
PK 1[*����Mail/tests/9137.phptnu�[���--TEST--
Mail: Test for bug #9137
--FILE--
<?php

require_once dirname(__FILE__) . '/../Mail/RFC822.php';
require_once 'PEAR.php';

$addresses = array(
    array('name' => 'John Doe', 'email' => 'test@example.com'),
    array('name' => 'John Doe\\', 'email' => 'test@example.com'),
    array('name' => 'John "Doe', 'email' => 'test@example.com'),
    array('name' => 'John "Doe\\', 'email' => 'test@example.com'),
);

for ($i = 0; $i < count($addresses); $i++) {
    // construct the address
    $address = "\"" . addslashes($addresses[$i]['name']) . "\" ".
        "<".$addresses[$i]['email'].">";

    $parsedAddresses = Mail_RFC822::parseAddressList($address);
    if (is_a($parsedAddresses, 'PEAR_Error')) {
        echo $address." :: Failed to validate\n";
    } else {
        echo $address." :: Parsed\n";
    }
}

--EXPECT--
"John Doe" <test@example.com> :: Parsed
"John Doe\\" <test@example.com> :: Parsed
"John \"Doe" <test@example.com> :: Parsed
"John \"Doe\\" <test@example.com> :: Parsed
PK 1[AFinder/Symfony/Component/Finder/Tests/Fixtures/with space/foo.txtnu�[���PK!1[<Finder/Symfony/Component/Finder/Tests/Fixtures/A/B/C/abc.datnu�[���PK!1[9Finder/Symfony/Component/Finder/Tests/Fixtures/A/B/ab.datnu�[���PK!1[6Finder/Symfony/Component/Finder/Tests/Fixtures/A/a.datnu�[���PK!1[4Finder/Symfony/Component/Finder/Tests/Fixtures/one/anu�[���PK!1[;Finder/Symfony/Component/Finder/Tests/Fixtures/one/b/d.neonnu�[���PK!1[;Finder/Symfony/Component/Finder/Tests/Fixtures/one/b/c.neonnu�[���PK!1[o�5|8Finder/Symfony/Component/Finder/Tests/Fixtures/dolor.txtnu�[���dolor sit amet
DOLOR SIT AMETPK!1['���))8Finder/Symfony/Component/Finder/Tests/Fixtures/ipsum.txtnu�[���ipsum dolor sit amet
IPSUM DOLOR SIT AMETPK!1[��558Finder/Symfony/Component/Finder/Tests/Fixtures/lorem.txtnu�[���lorem ipsum dolor sit amet
LOREM IPSUM DOLOR SIT AMETPK!1[@Finder/Symfony/Component/Finder/Tests/Fixtures/copy/A/a.dat.copynu�[���PK!1[FFinder/Symfony/Component/Finder/Tests/Fixtures/copy/A/B/C/abc.dat.copynu�[���PK!1[CFinder/Symfony/Component/Finder/Tests/Fixtures/copy/A/B/ab.dat.copynu�[���PK!1[˟�ׄ	�	GFinder/Symfony/Component/Finder/Tests/Comparator/DateComparatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Comparator;

use Symfony\Component\Finder\Comparator\DateComparator;

class DateComparatorTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        try {
            new DateComparator('foobar');
            $this->fail('__construct() throws an \InvalidArgumentException if the test expression is not valid.');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '__construct() throws an \InvalidArgumentException if the test expression is not valid.');
        }

        try {
            new DateComparator('');
            $this->fail('__construct() throws an \InvalidArgumentException if the test expression is not valid.');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '__construct() throws an \InvalidArgumentException if the test expression is not valid.');
        }
    }

    /**
     * @dataProvider getTestData
     */
    public function testTest($test, $match, $noMatch)
    {
        $c = new DateComparator($test);

        foreach ($match as $m) {
            $this->assertTrue($c->test($m), '->test() tests a string against the expression');
        }

        foreach ($noMatch as $m) {
            $this->assertFalse($c->test($m), '->test() tests a string against the expression');
        }
    }

    public function getTestData()
    {
        return array(
            array('< 2005-10-10', array(strtotime('2005-10-09')), array(strtotime('2005-10-15'))),
            array('until 2005-10-10', array(strtotime('2005-10-09')), array(strtotime('2005-10-15'))),
            array('before 2005-10-10', array(strtotime('2005-10-09')), array(strtotime('2005-10-15'))),
            array('> 2005-10-10', array(strtotime('2005-10-15')), array(strtotime('2005-10-09'))),
            array('after 2005-10-10', array(strtotime('2005-10-15')), array(strtotime('2005-10-09'))),
            array('since 2005-10-10', array(strtotime('2005-10-15')), array(strtotime('2005-10-09'))),
            array('!= 2005-10-10', array(strtotime('2005-10-11')), array(strtotime('2005-10-10'))),
        );

    }
}
PK!1[�W.�//IFinder/Symfony/Component/Finder/Tests/Comparator/NumberComparatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Comparator;

use Symfony\Component\Finder\Comparator\NumberComparator;

class NumberComparatorTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @dataProvider getConstructorTestData
     */
    public function testConstructor($successes, $failures)
    {
        foreach ($successes as $s) {
            new NumberComparator($s);
        }

        foreach ($failures as $f) {
            try {
                new NumberComparator($f);
                $this->fail('__construct() throws an \InvalidArgumentException if the test expression is not valid.');
            } catch (\Exception $e) {
                $this->assertInstanceOf('InvalidArgumentException', $e, '__construct() throws an \InvalidArgumentException if the test expression is not valid.');
            }
        }
    }

    /**
     * @dataProvider getTestData
     */
    public function testTest($test, $match, $noMatch)
    {
        $c = new NumberComparator($test);

        foreach ($match as $m) {
            $this->assertTrue($c->test($m), '->test() tests a string against the expression');
        }

        foreach ($noMatch as $m) {
            $this->assertFalse($c->test($m), '->test() tests a string against the expression');
        }
    }

    public function getTestData()
    {
        return array(
            array('< 1000', array('500', '999'), array('1000', '1500')),

            array('< 1K', array('500', '999'), array('1000', '1500')),
            array('<1k', array('500', '999'), array('1000', '1500')),
            array('  < 1 K ', array('500', '999'), array('1000', '1500')),
            array('<= 1K', array('1000'), array('1001')),
            array('> 1K', array('1001'), array('1000')),
            array('>= 1K', array('1000'), array('999')),

            array('< 1KI', array('500', '1023'), array('1024', '1500')),
            array('<= 1KI', array('1024'), array('1025')),
            array('> 1KI', array('1025'), array('1024')),
            array('>= 1KI', array('1024'), array('1023')),

            array('1KI', array('1024'), array('1023', '1025')),
            array('==1KI', array('1024'), array('1023', '1025')),

            array('==1m', array('1000000'), array('999999', '1000001')),
            array('==1mi', array(1024*1024), array(1024*1024-1, 1024*1024+1)),

            array('==1g', array('1000000000'), array('999999999', '1000000001')),
            array('==1gi', array(1024*1024*1024), array(1024*1024*1024-1, 1024*1024*1024+1)),

            array('!= 1000', array('500', '999'), array('1000')),
        );
    }

    public function getConstructorTestData()
    {
        return array(
            array(
                array(
                    '1', '0',
                    '3.5', '33.55', '123.456', '123456.78',
                    '.1', '.123',
                    '.0', '0.0',
                    '1.', '0.', '123.',
                    '==1', '!=1', '<1', '>1', '<=1', '>=1',
                    '==1k', '==1ki', '==1m', '==1mi', '==1g', '==1gi',
                    '1k', '1ki', '1m', '1mi', '1g', '1gi',
                ),
                array(
                    false, null, '',
                    ' ', 'foobar',
                    '=1', '===1',
                    '0 . 1', '123 .45', '234. 567',
                    '..', '.0.', '0.1.2',
                )
            ),
        );
    }

}
PK!1[��Ŗ�CFinder/Symfony/Component/Finder/Tests/Comparator/ComparatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Comparator;

use Symfony\Component\Finder\Comparator\Comparator;

class ComparatorTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSetOperator()
    {
        $comparator = new Comparator();
        try {
            $comparator->setOperator('foo');
            $this->fail('->setOperator() throws an \InvalidArgumentException if the operator is not valid.');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '->setOperator() throws an \InvalidArgumentException if the operator is not valid.');
        }

        $comparator = new Comparator();
        $comparator->setOperator('>');
        $this->assertEquals('>', $comparator->getOperator(), '->getOperator() returns the current operator');
    }

    public function testGetSetTarget()
    {
        $comparator = new Comparator();
        $comparator->setTarget(8);
        $this->assertEquals(8, $comparator->getTarget(), '->getTarget() returns the target');
    }

    /**
     * @dataProvider getTestData
     */
    public function testTest($operator, $target, $match, $noMatch)
    {
        $c = new Comparator();
        $c->setOperator($operator);
        $c->setTarget($target);

        foreach ($match as $m) {
            $this->assertTrue($c->test($m), '->test() tests a string against the expression');
        }

        foreach ($noMatch as $m) {
            $this->assertFalse($c->test($m), '->test() tests a string against the expression');
        }
    }

    public function getTestData()
    {
        return array(
            array('<', '1000', array('500', '999'), array('1000', '1500')),
        );
    }
}
PK!1[6G��mwmw4Finder/Symfony/Component/Finder/Tests/FinderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests;

use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\Adapter;

class FinderTest extends Iterator\RealIteratorTestCase
{

    public function testCreate()
    {
        $this->assertInstanceOf('Symfony\Component\Finder\Finder', Finder::create());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testDirectories($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->directories());
        $this->assertIterator($this->toAbsolute(array('foo', 'toto')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->directories();
        $finder->files();
        $finder->directories();
        $this->assertIterator($this->toAbsolute(array('foo', 'toto')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testFiles($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->files());
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php', 'test.py', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->files();
        $finder->directories();
        $finder->files();
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php', 'test.py', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testDepth($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->depth('< 1'));
        $this->assertIterator($this->toAbsolute(array('foo', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->depth('<= 0'));
        $this->assertIterator($this->toAbsolute(array('foo', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->depth('>= 1'));
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->depth('< 1')->depth('>= 1');
        $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testName($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->name('*.php'));
        $this->assertIterator($this->toAbsolute(array('test.php')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('test.ph*');
        $finder->name('test.py');
        $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('~^test~i');
        $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('~\\.php$~i');
        $this->assertIterator($this->toAbsolute(array('test.php')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('test.p{hp,y}');
        $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testNotName($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->notName('*.php'));
        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->notName('*.php');
        $finder->notName('*.py');
        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('test.ph*');
        $finder->name('test.py');
        $finder->notName('*.php');
        $finder->notName('*.py');
        $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->name('test.ph*');
        $finder->name('test.py');
        $finder->notName('*.p{hp,y}');
        $this->assertIterator(array(), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getRegexNameTestData
     *
     * @group regexName
     */
    public function testRegexName($adapter, $regex)
    {
        $finder = $this->buildFinder($adapter);
        $finder->name($regex);
        $this->assertIterator($this->toAbsolute(array('test.py', 'test.php')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSize($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->files()->size('< 1K')->size('> 500'));
        $this->assertIterator($this->toAbsolute(array('test.php')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testDate($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->files()->date('until last month'));
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testExclude($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->exclude('foo'));
        $this->assertIterator($this->toAbsolute(array('test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testIgnoreVCS($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->ignoreVCS(false)->ignoreDotFiles(false));
        $this->assertIterator($this->toAbsolute(array('.git', 'foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->ignoreVCS(false)->ignoreVCS(false)->ignoreDotFiles(false);
        $this->assertIterator($this->toAbsolute(array('.git', 'foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->ignoreVCS(true)->ignoreDotFiles(false));
        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testIgnoreDotFiles($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->ignoreDotFiles(false)->ignoreVCS(false));
        $this->assertIterator($this->toAbsolute(array('.git', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $finder->ignoreDotFiles(false)->ignoreDotFiles(false)->ignoreVCS(false);
        $this->assertIterator($this->toAbsolute(array('.git', '.bar', '.foo', '.foo/.bar', '.foo/bar', 'foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());

        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->ignoreDotFiles(true)->ignoreVCS(false));
        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSortByName($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sortByName());
        $this->assertIterator($this->toAbsolute(array('foo', 'foo bar', 'foo/bar.tmp', 'test.php', 'test.py', 'toto')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSortByType($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sortByType());
        $this->assertIterator($this->toAbsolute(array('foo', 'foo bar', 'toto', 'foo/bar.tmp', 'test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSortByAccessedTime($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sortByAccessedTime());
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php', 'toto', 'test.py', 'foo', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSortByChangedTime($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sortByChangedTime());
        $this->assertIterator($this->toAbsolute(array('toto', 'test.py', 'test.php', 'foo/bar.tmp', 'foo', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSortByModifiedTime($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sortByModifiedTime());
        $this->assertIterator($this->toAbsolute(array('foo/bar.tmp', 'test.php', 'toto', 'test.py', 'foo', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testSort($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealpath(), $b->getRealpath()); }));
        $this->assertIterator($this->toAbsolute(array('foo', 'foo bar', 'foo/bar.tmp', 'test.php', 'test.py', 'toto')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testFilter($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->filter(function (\SplFileInfo $f) { return preg_match('/test/', $f) > 0; }));
        $this->assertIterator($this->toAbsolute(array('test.php', 'test.py')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testFollowLinks($adapter)
    {
        if ('\\' == DIRECTORY_SEPARATOR) {
            return;
        }

        $finder = $this->buildFinder($adapter);
        $this->assertSame($finder, $finder->followLinks());
        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto', 'foo bar')), $finder->in(self::$tmpDir)->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testIn($adapter)
    {
        $finder = $this->buildFinder($adapter);
        try {
            $finder->in('foobar');
            $this->fail('->in() throws a \InvalidArgumentException if the directory does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '->in() throws a \InvalidArgumentException if the directory does not exist');
        }

        $finder = $this->buildFinder($adapter);
        $iterator = $finder->files()->name('*.php')->depth('< 1')->in(array(self::$tmpDir, __DIR__))->getIterator();

        $this->assertIterator(array(self::$tmpDir.DIRECTORY_SEPARATOR.'test.php', __DIR__.DIRECTORY_SEPARATOR.'FinderTest.php'), $iterator);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testInWithGlob($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(array(__DIR__.'/Fixtures/*/B/C', __DIR__.'/Fixtures/*/*/B/C'))->getIterator();

        $this->assertIterator($this->toAbsoluteFixtures(array('A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy')), $finder);
    }

    /**
     * @dataProvider getAdaptersTestData
     * @expectedException \InvalidArgumentException
     */
    public function testInWithNonDirectoryGlob($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(__DIR__.'/Fixtures/A/a*');
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testGetIterator($adapter)
    {
        $finder = $this->buildFinder($adapter);
        try {
            $finder->getIterator();
            $this->fail('->getIterator() throws a \LogicException if the in() method has not been called');
        } catch (\Exception $e) {
            $this->assertInstanceOf('LogicException', $e, '->getIterator() throws a \LogicException if the in() method has not been called');
        }

        $finder = $this->buildFinder($adapter);
        $dirs = array();
        foreach ($finder->directories()->in(self::$tmpDir) as $dir) {
            $dirs[] = (string) $dir;
        }

        $expected = $this->toAbsolute(array('foo', 'toto'));

        sort($dirs);
        sort($expected);

        $this->assertEquals($expected, $dirs, 'implements the \IteratorAggregate interface');

        $finder = $this->buildFinder($adapter);
        $this->assertEquals(2, iterator_count($finder->directories()->in(self::$tmpDir)), 'implements the \IteratorAggregate interface');

        $finder = $this->buildFinder($adapter);
        $a = iterator_to_array($finder->directories()->in(self::$tmpDir));
        $a = array_values(array_map(function ($a) { return (string) $a; }, $a));
        sort($a);
        $this->assertEquals($expected, $a, 'implements the \IteratorAggregate interface');
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testRelativePath($adapter)
    {
        $finder = $this->buildFinder($adapter)->in(self::$tmpDir);

        $paths = array();

        foreach ($finder as $file) {
            $paths[] = $file->getRelativePath();
        }

        $ref = array("", "", "", "", "foo", "");

        sort($ref);
        sort($paths);

        $this->assertEquals($ref, $paths);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testRelativePathname($adapter)
    {
        $finder = $this->buildFinder($adapter)->in(self::$tmpDir)->sortByName();

        $paths = array();

        foreach ($finder as $file) {
            $paths[] = $file->getRelativePathname();
        }

        $ref = array("test.php", "toto", "test.py", "foo", "foo".DIRECTORY_SEPARATOR."bar.tmp", "foo bar");

        sort($paths);
        sort($ref);

        $this->assertEquals($ref, $paths);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testAppendWithAFinder($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->files()->in(self::$tmpDir.DIRECTORY_SEPARATOR.'foo');

        $finder1 = $this->buildFinder($adapter);
        $finder1->directories()->in(self::$tmpDir);

        $finder = $finder->append($finder1);

        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testAppendWithAnArray($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->files()->in(self::$tmpDir.DIRECTORY_SEPARATOR.'foo');

        $finder->append($this->toAbsolute(array('foo', 'toto')));

        $this->assertIterator($this->toAbsolute(array('foo', 'foo/bar.tmp', 'toto')), $finder->getIterator());
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testAppendReturnsAFinder($adapter)
    {
        $this->assertInstanceOf('Symfony\\Component\\Finder\\Finder', $this->buildFinder($adapter)->append(array()));
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testAppendDoesNotRequireIn($adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(self::$tmpDir.DIRECTORY_SEPARATOR.'foo');

        $finder1 = Finder::create()->append($finder);

        $this->assertIterator(iterator_to_array($finder->getIterator()), $finder1->getIterator());
    }

    public function testCountDirectories()
    {
        $directory = Finder::create()->directories()->in(self::$tmpDir);
        $i = 0;

        foreach ($directory as $dir) {
            $i++;
        }

        $this->assertCount($i, $directory);
    }

    public function testCountFiles()
    {
        $files = Finder::create()->files()->in(__DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $i = 0;

        foreach ($files as $file) {
            $i++;
        }

        $this->assertCount($i, $files);
    }

    /**
     * @expectedException \LogicException
     */
    public function testCountWithoutIn()
    {
        $finder = Finder::create()->files();
        count($finder);
    }

    /**
     * @dataProvider getContainsTestData
     * @group grep
     */
    public function testContains($adapter, $matchPatterns, $noMatchPatterns, $expected)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(__DIR__.DIRECTORY_SEPARATOR.'Fixtures')
            ->name('*.txt')->sortByName()
            ->contains($matchPatterns)
            ->notContains($noMatchPatterns);

        $this->assertIterator($this->toAbsoluteFixtures($expected), $finder);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testContainsOnDirectory(Adapter\AdapterInterface $adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(__DIR__)
            ->directories()
            ->name('Fixtures')
            ->contains('abc');
        $this->assertIterator(array(), $finder);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testNotContainsOnDirectory(Adapter\AdapterInterface $adapter)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(__DIR__)
            ->directories()
            ->name('Fixtures')
            ->notContains('abc');
        $this->assertIterator(array(), $finder);
    }

    /**
     * Searching in multiple locations involves AppendIterator which does an unnecessary rewind which leaves FilterIterator
     * with inner FilesystemIterator in an invalid state.
     *
     * @see https://bugs.php.net/bug.php?id=49104
     *
     * @dataProvider getAdaptersTestData
     */
    public function testMultipleLocations(Adapter\AdapterInterface $adapter)
    {
        $locations = array(
            self::$tmpDir.'/',
            self::$tmpDir.'/toto/',
        );

        // it is expected that there are test.py test.php in the tmpDir
        $finder = $this->buildFinder($adapter);
        $finder->in($locations)->depth('< 1')->name('test.php');

        $this->assertCount(1, $finder);
    }

    /**
     * Iterator keys must be the file pathname.
     *
     * @dataProvider getAdaptersTestData
     */
    public function testIteratorKeys(Adapter\AdapterInterface $adapter)
    {
        $finder = $this->buildFinder($adapter)->in(self::$tmpDir);
        foreach ($finder as $key => $file) {
            $this->assertEquals($file->getPathname(), $key);
        }
    }

    public function testAdaptersOrdering()
    {
        $finder = Finder::create()
            ->removeAdapters()
            ->addAdapter(new FakeAdapter\NamedAdapter('a'), 0)
            ->addAdapter(new FakeAdapter\NamedAdapter('b'), -50)
            ->addAdapter(new FakeAdapter\NamedAdapter('c'), 50)
            ->addAdapter(new FakeAdapter\NamedAdapter('d'), -25)
            ->addAdapter(new FakeAdapter\NamedAdapter('e'), 25);

        $this->assertEquals(
            array('c', 'e', 'a', 'd', 'b'),
            array_map(function (Adapter\AdapterInterface $adapter) {
                return $adapter->getName();
            }, $finder->getAdapters())
        );
    }

    public function testAdaptersChaining()
    {
        $iterator  = new \ArrayIterator(array());
        $filenames = $this->toAbsolute(array('foo', 'foo/bar.tmp', 'test.php', 'test.py', 'toto'));
        foreach ($filenames as $file) {
            $iterator->append(new \Symfony\Component\Finder\SplFileInfo($file, null, null));
        }

        $finder = Finder::create()
            ->removeAdapters()
            ->addAdapter(new FakeAdapter\UnsupportedAdapter(), 3)
            ->addAdapter(new FakeAdapter\FailingAdapter(), 2)
            ->addAdapter(new FakeAdapter\DummyAdapter($iterator), 1);

        $this->assertIterator($filenames, $finder->in(sys_get_temp_dir())->getIterator());
    }

    public function getAdaptersTestData()
    {
        return array_map(
            function ($adapter) { return array($adapter); },
            $this->getValidAdapters()
        );
    }

    public function getContainsTestData()
    {
        $tests = array(
            array('', '', array()),
            array('foo', 'bar', array()),
            array('', 'foobar', array('dolor.txt', 'ipsum.txt', 'lorem.txt')),
            array('lorem ipsum dolor sit amet', 'foobar', array('lorem.txt')),
            array('sit', 'bar', array('dolor.txt', 'ipsum.txt', 'lorem.txt')),
            array('dolor sit amet', '@^L@m', array('dolor.txt', 'ipsum.txt')),
            array('/^lorem ipsum dolor sit amet$/m', 'foobar', array('lorem.txt')),
            array('lorem', 'foobar', array('lorem.txt')),
            array('', 'lorem', array('dolor.txt', 'ipsum.txt')),
            array('ipsum dolor sit amet', '/^IPSUM/m', array('lorem.txt')),
        );

        return $this->buildTestData($tests);
    }

    public function getRegexNameTestData()
    {
        $tests = array(
            array('~.+\\.p.+~i'),
            array('~t.*s~i'),
        );

        return $this->buildTestData($tests);
    }

    /**
     * @dataProvider getTestPathData
     */
    public function testPath(Adapter\AdapterInterface $adapter, $matchPatterns, $noMatchPatterns, array $expected)
    {
        $finder = $this->buildFinder($adapter);
        $finder->in(__DIR__.DIRECTORY_SEPARATOR.'Fixtures')
            ->path($matchPatterns)
            ->notPath($noMatchPatterns);

        $this->assertIterator($this->toAbsoluteFixtures($expected), $finder);
    }

    public function testAdapterSelection()
    {
        // test that by default, PhpAdapter is selected
        $adapters = Finder::create()->getAdapters();
        $this->assertTrue($adapters[0] instanceof Adapter\PhpAdapter);

        // test another adapter selection
        $adapters = Finder::create()->setAdapter('gnu_find')->getAdapters();
        $this->assertTrue($adapters[0] instanceof Adapter\GnuFindAdapter);

        // test that useBestAdapter method removes selection
        $adapters = Finder::create()->useBestAdapter()->getAdapters();
        $this->assertFalse($adapters[0] instanceof Adapter\PhpAdapter);
    }

    public function getTestPathData()
    {
        $tests = array(
            array('', '', array()),
            array('/^A\/B\/C/', '/C$/',
                array('A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat')
            ),
            array('/^A\/B/', 'foobar',
                array(
                    'A'.DIRECTORY_SEPARATOR.'B',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'ab.dat',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat',
                )
            ),
            array('A/B/C', 'foobar',
                array(
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat.copy',
                )
            ),
            array('A/B', 'foobar',
                array(
                    //dirs
                    'A'.DIRECTORY_SEPARATOR.'B',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C',
                    //files
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'ab.dat',
                    'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'ab.dat.copy',
                    'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat.copy',
                )
            ),
            array('/^with space\//', 'foobar',
                array(
                    'with space'.DIRECTORY_SEPARATOR.'foo.txt',
                )
            ),
        );

        return $this->buildTestData($tests);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testAccessDeniedException(Adapter\AdapterInterface $adapter)
    {
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $this->markTestSkipped('chmod is not supported on Windows');
        }

        $finder = $this->buildFinder($adapter);
        $finder->files()->in(self::$tmpDir);

        // make 'foo' directory non-readable
        chmod(self::$tmpDir.DIRECTORY_SEPARATOR.'foo', 0333);

        try {
            $this->assertIterator($this->toAbsolute(array('foo bar', 'test.php', 'test.py')), $finder->getIterator());
            $this->fail('Finder should throw an exception when opening a non-readable directory.');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\Finder\\Exception\\AccessDeniedException', $e);
        }

        // restore original permissions
        chmod(self::$tmpDir.DIRECTORY_SEPARATOR.'foo', 0777);
    }

    /**
     * @dataProvider getAdaptersTestData
     */
    public function testIgnoredAccessDeniedException(Adapter\AdapterInterface $adapter)
    {
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $this->markTestSkipped('chmod is not supported on Windows');
        }

        $finder = $this->buildFinder($adapter);
        $finder->files()->ignoreUnreadableDirs()->in(self::$tmpDir);

        // make 'foo' directory non-readable
        chmod(self::$tmpDir.DIRECTORY_SEPARATOR.'foo', 0333);

        $this->assertIterator($this->toAbsolute(array('foo bar', 'test.php', 'test.py')), $finder->getIterator());

        // restore original permissions
        chmod(self::$tmpDir.DIRECTORY_SEPARATOR.'foo', 0777);
    }

    private function buildTestData(array $tests)
    {
        $data = array();
        foreach ($this->getValidAdapters() as $adapter) {
            foreach ($tests as $test) {
                $data[] = array_merge(array($adapter), $test);
            }
        }

        return $data;
    }

    private function buildFinder(Adapter\AdapterInterface $adapter)
    {
        return Finder::create()
            ->removeAdapters()
            ->addAdapter($adapter);
    }

    private function getValidAdapters()
    {
        return array_filter(
            array(
                new Adapter\BsdFindAdapter(),
                new Adapter\GnuFindAdapter(),
                new Adapter\PhpAdapter()
            ),
            function (Adapter\AdapterInterface $adapter) {
                return $adapter->isSupported();
            }
        );
    }

   /**
     * Searching in multiple locations with sub directories involves
     * AppendIterator which does an unnecessary rewind which leaves
     * FilterIterator with inner FilesystemIterator in an invalid state.
     *
     * @see https://bugs.php.net/bug.php?id=49104
     */
    public function testMultipleLocationsWithSubDirectories()
    {
        $locations = array(
            __DIR__.'/Fixtures/one',
            self::$tmpDir.DIRECTORY_SEPARATOR.'toto',
        );

        $finder = new Finder();
        $finder->in($locations)->depth('< 10')->name('*.neon');

        $expected = array(
            __DIR__.'/Fixtures/one'.DIRECTORY_SEPARATOR.'b'.DIRECTORY_SEPARATOR.'c.neon',
            __DIR__.'/Fixtures/one'.DIRECTORY_SEPARATOR.'b'.DIRECTORY_SEPARATOR.'d.neon',
        );

        $this->assertIterator($expected, $finder);
        $this->assertIteratorInForeach($expected, $finder);
    }

    public function testNonSeekableStream()
    {
        try {
            $i = Finder::create()->in('ftp://ftp.mozilla.org/')->depth(0)->getIterator();
        } catch (\UnexpectedValueException $e) {
            $this->markTestSkipped(sprintf('Unsupported stream "%s".', 'ftp'));
        }

        $contains = array(
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'README',
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'index.html',
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'pub',
        );

        $this->assertIteratorInForeach($contains, $i);
    }
}
PK!1[+드44GFinder/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

abstract class RealIteratorTestCase extends IteratorTestCase
{

    protected static $tmpDir;
    protected static $files;

    public static function setUpBeforeClass()
    {
        self::$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'symfony2_finder';

        self::$files = array(
            '.git/',
            '.foo/',
            '.foo/.bar',
            '.foo/bar',
            '.bar',
            'test.py',
            'foo/',
            'foo/bar.tmp',
            'test.php',
            'toto/',
            'foo bar'
        );

        self::$files = self::toAbsolute(self::$files);

        if (is_dir(self::$tmpDir)) {
            self::tearDownAfterClass();
        } else {
            mkdir(self::$tmpDir);
        }

        foreach (self::$files as $file) {
            if (DIRECTORY_SEPARATOR === $file[strlen($file) - 1]) {
                mkdir($file);
            } else {
                touch($file);
            }
        }

        file_put_contents(self::toAbsolute('test.php'), str_repeat(' ', 800));
        file_put_contents(self::toAbsolute('test.py'), str_repeat(' ', 2000));

        touch(self::toAbsolute('foo/bar.tmp'), strtotime('2005-10-15'));
        touch(self::toAbsolute('test.php'), strtotime('2005-10-15'));
    }

    public static function tearDownAfterClass()
    {
        foreach (array_reverse(self::$files) as $file) {
            if (DIRECTORY_SEPARATOR === $file[strlen($file) - 1]) {
                @rmdir($file);
            } else {
                @unlink($file);
            }
        }
    }

    protected static function toAbsolute($files = null)
    {
        /*
         * Without the call to setUpBeforeClass() property can be null.
         */
        if (!self::$tmpDir) {
            self::$tmpDir = realpath(sys_get_temp_dir()).DIRECTORY_SEPARATOR.'symfony2_finder';
        }

        if (is_array($files)) {
            $f = array();
            foreach ($files as $file) {
                $f[] = self::$tmpDir.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $file);
            }

            return $f;
        }

        if (is_string($files)) {
            return self::$tmpDir.DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, $files);
        }

        return self::$tmpDir;
    }

    protected static function toAbsoluteFixtures($files)
    {
        $f = array();
        foreach ($files as $file) {
            $f[] = realpath(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.$file);
        }

        return $f;
    }

}
PK!1[:@���
�
HFinder/Symfony/Component/Finder/Tests/Iterator/FilePathsIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\FilePathsIterator;

class FilePathsIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getSubPathData
     */
    public function testSubPath($baseDir, array $paths, array $subPaths, array $subPathnames)
    {
        $iterator = new FilePathsIterator($paths, $baseDir);

        foreach ($iterator as $index => $file) {
            $this->assertEquals($paths[$index], $file->getPathname());
            $this->assertEquals($subPaths[$index], $iterator->getSubPath());
            $this->assertEquals($subPathnames[$index], $iterator->getSubPathname());
        }
    }

    public function getSubPathData()
    {
        $tmpDir = sys_get_temp_dir().'/symfony2_finder';

        return array(
            array(
                $tmpDir,
                array( // paths
                    $tmpDir.DIRECTORY_SEPARATOR.'.git' => $tmpDir.DIRECTORY_SEPARATOR.'.git',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.py' => $tmpDir.DIRECTORY_SEPARATOR.'test.py',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo' => $tmpDir.DIRECTORY_SEPARATOR.'foo',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => $tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.php' => $tmpDir.DIRECTORY_SEPARATOR.'test.php',
                    $tmpDir.DIRECTORY_SEPARATOR.'toto' => $tmpDir.DIRECTORY_SEPARATOR.'toto'
                ),
                array( // subPaths
                    $tmpDir.DIRECTORY_SEPARATOR.'.git' => '',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.py' => '',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo' => '',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => 'foo',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.php' => '',
                    $tmpDir.DIRECTORY_SEPARATOR.'toto' => ''
                ),
                array( // subPathnames
                    $tmpDir.DIRECTORY_SEPARATOR.'.git' => '.git',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.py' => 'test.py',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo' => 'foo',
                    $tmpDir.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'bar.tmp' => 'foo'.DIRECTORY_SEPARATOR.'bar.tmp',
                    $tmpDir.DIRECTORY_SEPARATOR.'test.php' => 'test.php',
                    $tmpDir.DIRECTORY_SEPARATOR.'toto' => 'toto'
                ),
            ),
        );
    }
}
PK!1[�qbe�
�
PFinder/Symfony/Component/Finder/Tests/Iterator/FilecontentFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;

class FilecontentFilterIteratorTest extends IteratorTestCase
{

    public function testAccept()
    {
        $inner = new MockFileListIterator(array('test.txt'));
        $iterator = new FilecontentFilterIterator($inner, array(), array());
        $this->assertIterator(array('test.txt'), $iterator);
    }

    public function testDirectory()
    {
        $inner = new MockFileListIterator(array('directory'));
        $iterator = new FilecontentFilterIterator($inner, array('directory'), array());
        $this->assertIterator(array(), $iterator);
    }

    public function testUnreadableFile()
    {
        $inner = new MockFileListIterator(array('file r-'));
        $iterator = new FilecontentFilterIterator($inner, array('file r-'), array());
        $this->assertIterator(array(), $iterator);
    }

    /**
     * @dataProvider getTestFilterData
     */
    public function testFilter(\Iterator $inner, array $matchPatterns, array $noMatchPatterns, array $resultArray)
    {
        $iterator = new FilecontentFilterIterator($inner, $matchPatterns, $noMatchPatterns);
        $this->assertIterator($resultArray, $iterator);
    }

    public function getTestFilterData()
    {
        $inner = new MockFileListIterator();

        $inner[] = new MockSplFileInfo(array(
            'name'     => 'a.txt',
            'contents' => 'Lorem ipsum...',
            'type'     => 'file',
            'mode'     => 'r+')
        );

        $inner[] = new MockSplFileInfo(array(
            'name'     => 'b.yml',
            'contents' => 'dolor sit...',
            'type'     => 'file',
            'mode'     => 'r+')
        );

        $inner[] = new MockSplFileInfo(array(
            'name'     => 'some/other/dir/third.php',
            'contents' => 'amet...',
            'type'     => 'file',
            'mode'     => 'r+')
        );

        $inner[] = new MockSplFileInfo(array(
            'name'     => 'unreadable-file.txt',
            'contents' => false,
            'type'     => 'file',
            'mode'     => 'r+')
        );

        return array(
            array($inner, array('.'), array(), array('a.txt', 'b.yml', 'some/other/dir/third.php')),
            array($inner, array('ipsum'), array(), array('a.txt')),
            array($inner, array('i', 'amet'), array('Lorem', 'amet'), array('b.yml')),
        );
    }
}
PK!1[Ybk�MMMFinder/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\FileTypeFilterIterator;

class FileTypeFilterIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($mode, $expected)
    {
        $inner = new InnerTypeIterator(self::$files);

        $iterator = new FileTypeFilterIterator($inner, $mode);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        $onlyFiles = array(
            'test.py',
            'foo/bar.tmp',
            'test.php',
            '.bar',
            '.foo/.bar',
            '.foo/bar',
            'foo bar',
        );

        $onlyDirectories = array(
            '.git',
            'foo',
            'toto',
            '.foo',
        );

        return array(
            array(FileTypeFilterIterator::ONLY_FILES, $this->toAbsolute($onlyFiles)),
            array(FileTypeFilterIterator::ONLY_DIRECTORIES, $this->toAbsolute($onlyDirectories)),
        );
    }
}

class InnerTypeIterator extends \ArrayIterator
{
   public function current()
    {
        return new \SplFileInfo(parent::current());
    }

    public function isFile()
    {
        return $this->current()->isFile();
    }

    public function isDir()
    {
        return $this->current()->isDir();
    }
}
PK!1[���Ŋ�QFinder/Symfony/Component/Finder/Tests/Iterator/RecursiveDirectoryIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator;

class RecursiveDirectoryIteratorTest extends IteratorTestCase
{
    /**
     * @dataProvider getPaths
     *
     * @param string  $path
     * @param Boolean $seekable
     * @param array   $contains
     * @param string  $message
     */
    public function testRewind($path, $seekable, $contains, $message = null)
    {
        try {
            $i = new RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
        } catch (\UnexpectedValueException $e) {
            $this->markTestSkipped(sprintf('Unsupported stream "%s".', $path));
        }

        $i->rewind();

        $this->assertTrue(true, $message);
    }

    /**
     * @dataProvider getPaths
     *
     * @param string  $path
     * @param Boolean $seekable
     * @param array   $contains
     * @param string  $message
     */
    public function testSeek($path, $seekable, $contains, $message = null)
    {
        try {
            $i = new RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
        } catch (\UnexpectedValueException $e) {
            $this->markTestSkipped(sprintf('Unsupported stream "%s".', $path));
        }

        $actual = array();

        $i->seek(0);
        $actual[] = $i->getPathname();

        $i->seek(1);
        $actual[] = $i->getPathname();

        $i->seek(2);
        $actual[] = $i->getPathname();

        $this->assertEquals($contains, $actual);
    }

    public function getPaths()
    {
        $data = array();

        // ftp
        $contains = array(
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'README',
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'index.html',
            'ftp://ftp.mozilla.org'.DIRECTORY_SEPARATOR.'pub',
        );
        $data[] = array('ftp://ftp.mozilla.org/', false, $contains);

        return $data;
    }
}
PK!1[4/aaUFinder/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
use Symfony\Component\Finder\Iterator\RecursiveDirectoryIterator;

class ExcludeDirectoryFilterIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($directories, $expected)
    {
        $inner = new \RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->toAbsolute(), \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);

        $iterator = new ExcludeDirectoryFilterIterator($inner, $directories);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        $foo = array(
            '.bar',
            '.foo',
            '.foo/.bar',
            '.foo/bar',
            '.git',
            'test.py',
            'test.php',
            'toto',
            'foo bar'
        );

        $fo = array(
            '.bar',
            '.foo',
            '.foo/.bar',
            '.foo/bar',
            '.git',
            'test.py',
            'foo',
            'foo/bar.tmp',
            'test.php',
            'toto',
            'foo bar'
        );

        return array(
            array(array('foo'), $this->toAbsolute($foo)),
            array(array('fo'), $this->toAbsolute($fo)),
        );
    }

}
PK!1[��nI��IFinder/Symfony/Component/Finder/Tests/Iterator/PathFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\PathFilterIterator;

class PathFilterIteratorTest extends IteratorTestCase
{

    /**
     * @dataProvider getTestFilterData
     */
    public function testFilter(\Iterator $inner, array $matchPatterns, array $noMatchPatterns, array $resultArray)
    {
        $iterator = new PathFilterIterator($inner, $matchPatterns, $noMatchPatterns);
        $this->assertIterator($resultArray, $iterator);
    }

    public function getTestFilterData()
    {
        $inner = new MockFileListIterator();

        //PATH:   A/B/C/abc.dat
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'abc.dat',
            'relativePathname'  => 'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat',
        ));

        //PATH:   A/B/ab.dat
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'ab.dat',
            'relativePathname'  => 'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'ab.dat',
        ));

        //PATH:   A/a.dat
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'a.dat',
            'relativePathname'  => 'A'.DIRECTORY_SEPARATOR.'a.dat',
        ));

        //PATH:   copy/A/B/C/abc.dat.copy
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'abc.dat.copy',
            'relativePathname'  => 'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'C'.DIRECTORY_SEPARATOR.'abc.dat',
        ));

        //PATH:   copy/A/B/ab.dat.copy
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'ab.dat.copy',
            'relativePathname'  => 'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'B'.DIRECTORY_SEPARATOR.'ab.dat',
        ));

        //PATH:   copy/A/a.dat.copy
        $inner[] = new MockSplFileInfo(array(
            'name'              => 'a.dat.copy',
            'relativePathname'  => 'copy'.DIRECTORY_SEPARATOR.'A'.DIRECTORY_SEPARATOR.'a.dat',
        ));

        return array(
            array($inner, array('/^A/'),       array(), array('abc.dat', 'ab.dat', 'a.dat')),
            array($inner, array('/^A\/B/'),    array(), array('abc.dat', 'ab.dat')),
            array($inner, array('/^A\/B\/C/'), array(), array('abc.dat')),
            array($inner, array('/A\/B\/C/'),  array(), array('abc.dat', 'abc.dat.copy')),

            array($inner, array('A'),      array(), array('abc.dat', 'ab.dat', 'a.dat', 'abc.dat.copy', 'ab.dat.copy', 'a.dat.copy')),
            array($inner, array('A/B'),    array(), array('abc.dat', 'ab.dat', 'abc.dat.copy', 'ab.dat.copy')),
            array($inner, array('A/B/C'),  array(), array('abc.dat', 'abc.dat.copy')),

            array($inner, array('copy/A'),      array(), array('abc.dat.copy', 'ab.dat.copy', 'a.dat.copy')),
            array($inner, array('copy/A/B'),    array(), array('abc.dat.copy', 'ab.dat.copy')),
            array($inner, array('copy/A/B/C'),  array(), array('abc.dat.copy')),

        );
    }

}
PK!1[��++QFinder/Symfony/Component/Finder/Tests/Iterator/MultiplePcreFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\MultiplePcreFilterIterator;

class MultiplePcreFilterIteratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getIsRegexFixtures
     */
    public function testIsRegex($string, $isRegex, $message)
    {
        $testIterator = new TestMultiplePcreFilterIterator();
        $this->assertEquals($isRegex, $testIterator->isRegex($string), $message);
    }

    public function getIsRegexFixtures()
    {
        return array(
            array('foo', false, 'string'),
            array(' foo ', false, '" " is not a valid delimiter'),
            array('\\foo\\', false, '"\\" is not a valid delimiter'),
            array('afooa', false, '"a" is not a valid delimiter'),
            array('//', false, 'the pattern should contain at least 1 character'),
            array('/a/', true, 'valid regex'),
            array('/foo/', true, 'valid regex'),
            array('/foo/i', true, 'valid regex with a single modifier'),
            array('/foo/imsxu', true, 'valid regex with multiple modifiers'),
            array('#foo#', true, '"#" is a valid delimiter'),
            array('{foo}', true, '"{,}" is a valid delimiter pair'),
            array('*foo.*', false, '"*" is not considered as a valid delimiter'),
            array('?foo.?', false, '"?" is not considered as a valid delimiter'),
        );
    }
}

class TestMultiplePcreFilterIterator extends MultiplePcreFilterIterator
{
    public function __construct()
    {
    }

    public function accept()
    {
        throw new \BadFunctionCallException('Not implemented');
    }

    public function isRegex($str)
    {
        return parent::isRegex($str);
    }

    public function toRegex($str)
    {
        throw new \BadFunctionCallException('Not implemented');
    }
}
PK!1[�7Wa	a	GFinder/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\SortableIterator;

class SortableIteratorTest extends RealIteratorTestCase
{
    public function testConstructor()
    {
        try {
            new SortableIterator(new Iterator(array()), 'foobar');
            $this->fail('__construct() throws an \InvalidArgumentException exception if the mode is not valid');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '__construct() throws an \InvalidArgumentException exception if the mode is not valid');
        }
    }

    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($mode, $expected)
    {
        $inner = new Iterator(self::$files);

        $iterator = new SortableIterator($inner, $mode);

        $this->assertOrderedIterator($expected, $iterator);
    }

    public function getAcceptData()
    {

        $sortByName = array(
            '.bar',
            '.foo',
            '.foo/.bar',
            '.foo/bar',
            '.git',
            'foo',
            'foo bar',
            'foo/bar.tmp',
            'test.php',
            'test.py',
            'toto',
        );

        $sortByType = array(
            '.foo',
            '.git',
            'foo',
            'toto',
            '.bar',
            '.foo/.bar',
            '.foo/bar',
            'foo bar',
            'foo/bar.tmp',
            'test.php',
            'test.py',
        );

        $customComparison = array(
            '.bar',
            '.foo',
            '.foo/.bar',
            '.foo/bar',
            '.git',
            'foo',
            'foo bar',
            'foo/bar.tmp',
            'test.php',
            'test.py',
            'toto',
        );

        return array(
            array(SortableIterator::SORT_BY_NAME, $this->toAbsolute($sortByName)),
            array(SortableIterator::SORT_BY_TYPE, $this->toAbsolute($sortByType)),
            array(function (\SplFileInfo $a, \SplFileInfo $b) { return strcmp($a->getRealpath(), $b->getRealpath()); }, $this->toAbsolute($customComparison)),
        );
    }
}
PK!1[�7���MFinder/Symfony/Component/Finder/Tests/Iterator/FilenameFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\FilenameFilterIterator;

class FilenameFilterIteratorTest extends IteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($matchPatterns, $noMatchPatterns, $expected)
    {
        $inner = new InnerNameIterator(array('test.php', 'test.py', 'foo.php'));

        $iterator = new FilenameFilterIterator($inner, $matchPatterns, $noMatchPatterns);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        return array(
            array(array('test.*'), array(), array('test.php', 'test.py')),
            array(array(), array('test.*'), array('foo.php')),
            array(array('*.php'), array('test.*'), array('foo.php')),
            array(array('*.php', '*.py'), array('foo.*'), array('test.php', 'test.py')),
            array(array('/\.php$/'), array(), array('test.php', 'foo.php')),
            array(array(), array('/\.php$/'), array('test.py')),
        );
    }
}

class InnerNameIterator extends \ArrayIterator
{
    public function current()
    {
        return new \SplFileInfo(parent::current());
    }

    public function getFilename()
    {
        return parent::current();
    }
}
PK!1[߫����KFinder/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\CustomFilterIterator;

class CustomFilterIteratorTest extends IteratorTestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testWithInvalidFilter()
    {
        new CustomFilterIterator(new Iterator(), array('foo'));
    }

    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($filters, $expected)
    {
        $inner = new Iterator(array('test.php', 'test.py', 'foo.php'));

        $iterator = new CustomFilterIterator($inner, $filters);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        return array(
            array(array(function (\SplFileInfo $fileinfo) { return false; }), array()),
            array(array(function (\SplFileInfo $fileinfo) { return preg_match('/^test/', $fileinfo) > 0; }), array('test.php', 'test.py')),
            array(array('is_dir'), array()),
        );
    }
}
PK!1[��o�
�
BFinder/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

class MockSplFileInfo extends \SplFileInfo
{
    const   TYPE_DIRECTORY = 1;
    const   TYPE_FILE      = 2;
    const   TYPE_UNKNOWN   = 3;

    private $contents         = null;
    private $mode             = null;
    private $type             = null;
    private $relativePath     = null;
    private $relativePathname = null;

    public function __construct($param)
    {
        if (is_string($param)) {
            parent::__construct($param);
        } elseif (is_array($param)) {
            $defaults = array(
              'name'             => 'file.txt',
              'contents'         => null,
              'mode'             => null,
              'type'             => null,
              'relativePath'     => null,
              'relativePathname' => null,
            );
            $defaults = array_merge($defaults, $param);
            parent::__construct($defaults['name']);
            $this->setContents($defaults['contents']);
            $this->setMode($defaults['mode']);
            $this->setType($defaults['type']);
            $this->setRelativePath($defaults['relativePath']);
            $this->setRelativePathname($defaults['relativePathname']);
        } else {
            throw new \RuntimeException(sprintf('Incorrect parameter "%s"', $param));
        }
    }

    public function isFile()
    {
        if ($this->type === null) {
            return preg_match('/file/', $this->getFilename());
        };

        return self::TYPE_FILE === $this->type;
    }

    public function isDir()
    {
        if ($this->type === null) {
            return preg_match('/directory/', $this->getFilename());
        }

        return self::TYPE_DIRECTORY === $this->type;
    }

    public function isReadable()
    {
        if ($this->mode === null) {
            return preg_match('/r\+/', $this->getFilename());
        }

        return preg_match('/r\+/', $this->mode);
    }

    public function getContents()
    {
        return $this->contents;
    }

    public function setContents($contents)
    {
        $this->contents = $contents;
    }

    public function setMode($mode)
    {
        $this->mode = $mode;
    }

    public function setType($type)
    {
        if (is_string($type)) {
            switch ($type) {
                case 'directory':
                    $this->type = self::TYPE_DIRECTORY;
                case 'd':
                    $this->type = self::TYPE_DIRECTORY;
                    break;
                case 'file':
                    $this->type = self::TYPE_FILE;
                case 'f':
                    $this->type = self::TYPE_FILE;
                    break;
                default:
                    $this->type = self::TYPE_UNKNOWN;
            }
        } else {
            $this->type = $type;
        }
    }

    public function setRelativePath($relativePath)
    {
        $this->relativePath = $relativePath;
    }

    public function setRelativePathname($relativePathname)
    {
        $this->relativePathname = $relativePathname;
    }

    public function getRelativePath()
    {
        return $this->relativePath;
    }

    public function getRelativePathname()
    {
        return $this->relativePathname;
    }
}
PK!1[Zo�*))OFinder/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;

class DepthRangeFilterIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($minDepth, $maxDepth, $expected)
    {
        $inner = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->toAbsolute(), \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST);

        $iterator = new DepthRangeFilterIterator($inner, $minDepth, $maxDepth);

        $actual = array_keys(iterator_to_array($iterator));
        sort($expected);
        sort($actual);
        $this->assertEquals($expected, $actual);
    }

    public function getAcceptData()
    {
        $lessThan1 = array(
            '.git',
            'test.py',
            'foo',
            'test.php',
            'toto',
            '.foo',
            '.bar',
            'foo bar',
        );

        $lessThanOrEqualTo1 = array(
            '.git',
            'test.py',
            'foo',
            'foo/bar.tmp',
            'test.php',
            'toto',
            '.foo',
            '.foo/.bar',
            '.bar',
            'foo bar',
            '.foo/bar',
        );

        $graterThanOrEqualTo1 = array(
            'foo/bar.tmp',
            '.foo/.bar',
            '.foo/bar',
        );

        $equalTo1 = array(
            'foo/bar.tmp',
            '.foo/.bar',
            '.foo/bar',
        );

        return array(
            array(0, 0, $this->toAbsolute($lessThan1)),
            array(0, 1, $this->toAbsolute($lessThanOrEqualTo1)),
            array(2, PHP_INT_MAX, array()),
            array(1, PHP_INT_MAX, $this->toAbsolute($graterThanOrEqualTo1)),
            array(1, 1, $this->toAbsolute($equalTo1)),
        );
    }

}
PK"1[�S�;Finder/Symfony/Component/Finder/Tests/Iterator/Iterator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

class Iterator implements \Iterator
{
    protected $values = array();

    public function __construct(array $values = array())
    {
        foreach ($values as $value) {
            $this->attach(new \SplFileInfo($value));
        }
        $this->rewind();
    }

    public function attach(\SplFileInfo $fileinfo)
    {
        $this->values[] = $fileinfo;
    }

    public function rewind()
    {
        reset($this->values);
    }

    public function valid()
    {
        return false !== $this->current();
    }

    public function next()
    {
        next($this->values);
    }

    public function current()
    {
        return current($this->values);
    }

    public function key()
    {
        return key($this->values);
    }
}
PK"1[���FNFinder/Symfony/Component/Finder/Tests/Iterator/SizeRangeFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
use Symfony\Component\Finder\Comparator\NumberComparator;

class SizeRangeFilterIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($size, $expected)
    {
        $inner = new InnerSizeIterator(self::$files);

        $iterator = new SizeRangeFilterIterator($inner, $size);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        $lessThan1KGreaterThan05K = array(
            '.foo',
            '.git',
            'foo',
            'test.php',
            'toto',
        );

        return array(
            array(array(new NumberComparator('< 1K'), new NumberComparator('> 0.5K')), $this->toAbsolute($lessThan1KGreaterThan05K)),
        );
    }
}

class InnerSizeIterator extends \ArrayIterator
{
   public function current()
    {
        return new \SplFileInfo(parent::current());
    }

    public function getFilename()
    {
        return parent::current();
    }

    public function isFile()
    {
        return $this->current()->isFile();
    }

    public function getSize()
    {
        return $this->current()->getSize();
    }
}
PK"1[-���66EFinder/Symfony/Component/Finder/Tests/Iterator/FilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

/**
 * @author Alex Bogomazov
 */
class FilterIteratorTest extends RealIteratorTestCase
{
    public function testFilterFilesystemIterators()
    {
        $i = new \FilesystemIterator($this->toAbsolute());

        // it is expected that there are test.py test.php in the tmpDir
        $i = $this->getMockForAbstractClass('Symfony\Component\Finder\Iterator\FilterIterator', array($i));
        $i->expects($this->any())
            ->method('accept')
            ->will($this->returnCallback(function () use ($i) {
                return (bool) preg_match('/\.php/', (string) $i->current());
            })
        );

        $c = 0;
        foreach ($i as $item) {
            $c++;
        }

        $this->assertEquals(1, $c);

        $i->rewind();

        $c = 0;
        foreach ($i as $item) {
            $c++;
        }

        // This would fail with \FilterIterator but works with Symfony\Component\Finder\Iterator\FilterIterator
        // see https://bugs.php.net/bug.php?id=49104
        $this->assertEquals(1, $c);
    }
}
PK"1[{�)\o	o	CFinder/Symfony/Component/Finder/Tests/Iterator/IteratorTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

abstract class IteratorTestCase extends \PHPUnit_Framework_TestCase
{
    protected function assertIterator($expected, \Traversable $iterator)
    {
        // set iterator_to_array $use_key to false to avoid values merge
        // this made FinderTest::testAppendWithAnArray() failed with GnuFinderAdapter
        $values = array_map(function (\SplFileInfo $fileinfo) { return str_replace('/', DIRECTORY_SEPARATOR, $fileinfo->getPathname()); }, iterator_to_array($iterator, false));

        $expected = array_map(function ($path) { return str_replace('/', DIRECTORY_SEPARATOR, $path); }, $expected);

        sort($values);
        sort($expected);

        $this->assertEquals($expected, array_values($values));
    }

    protected function assertOrderedIterator($expected, \Traversable $iterator)
    {
        $values = array_map(function (\SplFileInfo $fileinfo) { return $fileinfo->getPathname(); }, iterator_to_array($iterator));

        $this->assertEquals($expected, array_values($values));
    }

    /**
     * Same as IteratorTestCase::assertIterator with foreach usage
     *
     * @param array $expected
     * @param \Traversable $iterator
     */
    protected function assertIteratorInForeach($expected, \Traversable $iterator)
    {
        $values = array();
        foreach ($iterator as $file) {
            $this->assertInstanceOf('Symfony\\Component\\Finder\\SplFileInfo', $file);
            $values[] = $file->getPathname();
        }

        sort($values);
        sort($expected);

        $this->assertEquals($expected, array_values($values));
    }

    /**
     * Same as IteratorTestCase::assertOrderedIterator with foreach usage
     *
     * @param array $expected
     * @param \Traversable $iterator
     */
    protected function assertOrderedIteratorInForeach($expected, \Traversable $iterator)
    {
        $values = array();
        foreach ($iterator as $file) {
            $this->assertInstanceOf('Symfony\\Component\\Finder\\SplFileInfo', $file);
            $values[] = $file->getPathname();
        }

        $this->assertEquals($expected, array_values($values));
    }
}
PK"1[�[+((GFinder/Symfony/Component/Finder/Tests/Iterator/MockFileListIterator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

class MockFileListIterator extends \ArrayIterator
{
    public function __construct(array $filesArray = array())
    {
        $files = array_map(function ($file) { return new MockSplFileInfo($file); }, $filesArray);
        parent::__construct($files);
    }
}
PK"1[(��g==NFinder/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Iterator;

use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
use Symfony\Component\Finder\Comparator\DateComparator;

class DateRangeFilterIteratorTest extends RealIteratorTestCase
{
    /**
     * @dataProvider getAcceptData
     */
    public function testAccept($size, $expected)
    {
        $inner = new Iterator(self::$files);

        $iterator = new DateRangeFilterIterator($inner, $size);

        $this->assertIterator($expected, $iterator);
    }

    public function getAcceptData()
    {
        $since20YearsAgo = array(
            '.git',
            'test.py',
            'foo',
            'foo/bar.tmp',
            'test.php',
            'toto',
            '.bar',
            '.foo',
            '.foo/.bar',
            'foo bar',
            '.foo/bar',
        );

        $since2MonthsAgo = array(
            '.git',
            'test.py',
            'foo',
            'toto',
            '.bar',
            '.foo',
            '.foo/.bar',
            'foo bar',
            '.foo/bar',
        );

        $untilLastMonth = array(
            '.git',
            'foo',
            'foo/bar.tmp',
            'test.php',
            'toto',
            '.foo',
        );

        return array(
            array(array(new DateComparator('since 20 years ago')), $this->toAbsolute($since20YearsAgo)),
            array(array(new DateComparator('since 2 months ago')), $this->toAbsolute($since2MonthsAgo)),
            array(array(new DateComparator('until last month')), $this->toAbsolute($untilLastMonth)),
        );
    }
}
PK"1[�|ߐ�CFinder/Symfony/Component/Finder/Tests/Expression/ExpressionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Expression;

use Symfony\Component\Finder\Expression\Expression;

class ExpressionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTypeGuesserData
     */
    public function testTypeGuesser($expr, $type)
    {
        $this->assertEquals($type, Expression::create($expr)->getType());
    }

    /**
     * @dataProvider getCaseSensitiveData
     */
    public function testCaseSensitive($expr, $isCaseSensitive)
    {
        $this->assertEquals($isCaseSensitive, Expression::create($expr)->isCaseSensitive());
    }

    /**
     * @dataProvider getRegexRenderingData
     */
    public function testRegexRendering($expr, $body)
    {
        $this->assertEquals($body, Expression::create($expr)->renderPattern());
    }

    public function getTypeGuesserData()
    {
        return array(
            array('{foo}', Expression::TYPE_REGEX),
            array('/foo/', Expression::TYPE_REGEX),
            array('foo',   Expression::TYPE_GLOB),
            array('foo*',  Expression::TYPE_GLOB),
        );
    }

    public function getCaseSensitiveData()
    {
        return array(
            array('{foo}m', true),
            array('/foo/i', false),
            array('foo*',   true),
        );
    }

    public function getRegexRenderingData()
    {
        return array(
            array('{foo}m', 'foo'),
            array('/foo/i', 'foo'),
        );
    }
}
PK"1[�9]��>Finder/Symfony/Component/Finder/Tests/Expression/RegexTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Expression;

use Symfony\Component\Finder\Expression\Expression;

class RegexTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getHasFlagsData
     */
    public function testHasFlags($regex, $start, $end)
    {
        $expr = new Expression($regex);

        $this->assertEquals($start, $expr->getRegex()->hasStartFlag());
        $this->assertEquals($end,   $expr->getRegex()->hasEndFlag());
    }

    /**
     * @dataProvider getHasJokersData
     */
    public function testHasJokers($regex, $start, $end)
    {
        $expr = new Expression($regex);

        $this->assertEquals($start, $expr->getRegex()->hasStartJoker());
        $this->assertEquals($end,   $expr->getRegex()->hasEndJoker());
    }

    /**
     * @dataProvider getSetFlagsData
     */
    public function testSetFlags($regex, $start, $end, $expected)
    {
        $expr = new Expression($regex);
        $expr->getRegex()->setStartFlag($start)->setEndFlag($end);

        $this->assertEquals($expected, $expr->render());
    }

    /**
     * @dataProvider getSetJokersData
     */
    public function testSetJokers($regex, $start, $end, $expected)
    {
        $expr = new Expression($regex);
        $expr->getRegex()->setStartJoker($start)->setEndJoker($end);

        $this->assertEquals($expected, $expr->render());
    }

    public function testOptions()
    {
        $expr = new Expression('~abc~is');
        $expr->getRegex()->removeOption('i')->addOption('m');

        $this->assertEquals('~abc~sm', $expr->render());
    }

    public function testMixFlagsAndJokers()
    {
        $expr = new Expression('~^.*abc.*$~is');

        $expr->getRegex()->setStartFlag(false)->setEndFlag(false)->setStartJoker(false)->setEndJoker(false);
        $this->assertEquals('~abc~is', $expr->render());

        $expr->getRegex()->setStartFlag(true)->setEndFlag(true)->setStartJoker(true)->setEndJoker(true);
        $this->assertEquals('~^.*abc.*$~is', $expr->render());
    }

    /**
     * @dataProvider getReplaceJokersTestData
     */
    public function testReplaceJokers($regex, $expected)
    {
        $expr = new Expression($regex);
        $expr = $expr->getRegex()->replaceJokers('@');

        $this->assertEquals($expected, $expr->renderPattern());
    }

    public function getHasFlagsData()
    {
        return array(
            array('~^abc~', true, false),
            array('~abc$~', false, true),
            array('~abc~', false, false),
            array('~^abc$~', true, true),
            array('~^abc\\$~', true, false),
        );
    }

    public function getHasJokersData()
    {
        return array(
            array('~.*abc~', true, false),
            array('~abc.*~', false, true),
            array('~abc~', false, false),
            array('~.*abc.*~', true, true),
            array('~.*abc\\.*~', true, false),
        );
    }

    public function getSetFlagsData()
    {
        return array(
            array('~abc~', true, false, '~^abc~'),
            array('~abc~', false, true, '~abc$~'),
            array('~abc~', false, false, '~abc~'),
            array('~abc~', true, true, '~^abc$~'),
        );
    }

    public function getSetJokersData()
    {
        return array(
            array('~abc~', true, false, '~.*abc~'),
            array('~abc~', false, true, '~abc.*~'),
            array('~abc~', false, false, '~abc~'),
            array('~abc~', true, true, '~.*abc.*~'),
        );
    }

    public function getReplaceJokersTestData()
    {
        return array(
            array('~.abc~', '@abc'),
            array('~\\.abc~', '\\.abc'),
            array('~\\\\.abc~', '\\\\@abc'),
            array('~\\\\\\.abc~', '\\\\\\.abc'),
        );
    }
}
PK"1[7u��tt=Finder/Symfony/Component/Finder/Tests/Expression/GlobTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\Expression;

use Symfony\Component\Finder\Expression\Expression;

class GlobTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getToRegexData
     */
    public function testGlobToRegex($glob, $match, $noMatch)
    {
        foreach ($match as $m) {
            $this->assertRegExp(Expression::create($glob)->getRegex()->render(), $m, '::toRegex() converts a glob to a regexp');
        }

        foreach ($noMatch as $m) {
            $this->assertNotRegExp(Expression::create($glob)->getRegex()->render(), $m, '::toRegex() converts a glob to a regexp');
        }
    }

    public function getToRegexData()
    {
        return array(
            array('', array(''), array('f', '/')),
            array('*', array('foo'), array('foo/', '/foo')),
            array('foo.*', array('foo.php', 'foo.a', 'foo.'), array('fooo.php', 'foo.php/foo')),
            array('fo?', array('foo', 'fot'), array('fooo', 'ffoo', 'fo/')),
            array('fo{o,t}', array('foo', 'fot'), array('fob', 'fo/')),
            array('foo(bar|foo)', array('foo(bar|foo)'), array('foobar', 'foofoo')),
            array('foo,bar', array('foo,bar'), array('foo', 'bar')),
            array('fo{o,\\,}', array('foo', 'fo,'), array()),
            array('fo{o,\\\\}', array('foo', 'fo\\'), array()),
            array('/foo', array('/foo'), array('foo')),
        );
    }
}
PK"1[`�2��BFinder/Symfony/Component/Finder/Tests/FakeAdapter/NamedAdapter.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\FakeAdapter;

use Symfony\Component\Finder\Adapter\AbstractAdapter;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class NamedAdapter extends AbstractAdapter
{
    /**
     * @var string
     */
    private $name;

    /**
     * @param string $name
     */
    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * {@inheritdoc}
     */
    public function searchInDirectory($dir)
    {
        return new \ArrayIterator(array());
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * {@inheritdoc}
     */
    protected function canBeUsed()
    {
        return true;
    }
}
PK"1[I����BFinder/Symfony/Component/Finder/Tests/FakeAdapter/DummyAdapter.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\FakeAdapter;

use Symfony\Component\Finder\Adapter\AbstractAdapter;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class DummyAdapter extends AbstractAdapter
{
    /**
     * @var \Iterator
     */
    private $iterator;

    /**
     * @param \Iterator $iterator
     */
    public function __construct(\Iterator $iterator)
    {
        $this->iterator = $iterator;
    }

    /**
     * {@inheritdoc}
     */
    public function searchInDirectory($dir)
    {
        return $this->iterator;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'yes';
    }

    /**
     * {@inheritdoc}
     */
    protected function canBeUsed()
    {
        return true;
    }
}
PK"1[/��00HFinder/Symfony/Component/Finder/Tests/FakeAdapter/UnsupportedAdapter.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\FakeAdapter;

use Symfony\Component\Finder\Adapter\AbstractAdapter;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class UnsupportedAdapter extends AbstractAdapter
{
    /**
     * {@inheritdoc}
     */
    public function searchInDirectory($dir)
    {
        return new \ArrayIterator(array());
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'unsupported';
    }

    /**
     * {@inheritdoc}
     */
    protected function canBeUsed()
    {
        return false;
    }
}
PK"1[��mmDFinder/Symfony/Component/Finder/Tests/FakeAdapter/FailingAdapter.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Finder\Tests\FakeAdapter;

use Symfony\Component\Finder\Adapter\AbstractAdapter;
use Symfony\Component\Finder\Exception\AdapterFailureException;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class FailingAdapter extends AbstractAdapter
{
    /**
     * {@inheritdoc}
     */
    public function searchInDirectory($dir)
    {
        throw new AdapterFailureException($this);
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'failing';
    }

    /**
     * {@inheritdoc}
     */
    protected function canBeUsed()
    {
        return true;
    }
}
PK"1[���550Finder/Symfony/Component/Finder/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Finder Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK"1[9���FTwigBridge/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Translation;

use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Translation\TwigExtractor;
use Symfony\Component\Translation\MessageCatalogue;

class TwigExtractorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getExtractData
     */
    public function testExtract($template, $messages)
    {
        $loader = new \Twig_Loader_Array(array());
        $twig = new \Twig_Environment($loader, array(
            'strict_variables' => true,
            'debug' => true,
            'cache' => false,
            'autoescape' => false,
        ));
        $twig->addExtension(new TranslationExtension($this->getMock('Symfony\Component\Translation\TranslatorInterface')));

        $extractor = new TwigExtractor($twig);
        $extractor->setPrefix('prefix');
        $catalogue = new MessageCatalogue('en');

        $m = new \ReflectionMethod($extractor, 'extractTemplate');
        $m->setAccessible(true);
        $m->invoke($extractor, $template, $catalogue);

        foreach ($messages as $key => $domain) {
            $this->assertTrue($catalogue->has($key, $domain));
            $this->assertEquals('prefix'.$key, $catalogue->get($key, $domain));
        }
    }

    public function getExtractData()
    {
        return array(
            array('{{ "new key" | trans() }}', array('new key' => 'messages')),
            array('{{ "new key" | trans() | upper }}', array('new key' => 'messages')),
            array('{{ "new key" | trans({}, "domain") }}', array('new key' => 'domain')),
            array('{{ "new key" | transchoice(1) }}', array('new key' => 'messages')),
            array('{{ "new key" | transchoice(1) | upper }}', array('new key' => 'messages')),
            array('{{ "new key" | transchoice(1, {}, "domain") }}', array('new key' => 'domain')),
            array('{% trans %}new key{% endtrans %}', array('new key' => 'messages')),
            array('{% trans %}  new key  {% endtrans %}', array('new key' => 'messages')),
            array('{% trans from "domain" %}new key{% endtrans %}', array('new key' => 'domain')),
            array('{% set foo = "new key" | trans %}', array('new key' => 'messages')),
            array('{{ 1 ? "new key" | trans : "another key" | trans }}', array('new key' => 'messages', 'another key' => 'messages')),

            // make sure 'trans_default_domain' tag is supported
            array('{% trans_default_domain "domain" %}{{ "new key"|trans }}', array('new key' => 'domain')),
            array('{% trans_default_domain "domain" %}{{ "new key"|transchoice }}', array('new key' => 'domain')),
            array('{% trans_default_domain "domain" %}{% trans %}new key{% endtrans %}', array('new key' => 'domain')),

            // make sure this works with twig's named arguments
            array('{{ "new key" | trans(domain="domain") }}', array('new key' => 'domain')),
            array('{{ "new key" | transchoice(domain="domain", count=1) }}', array('new key' => 'domain')),
        );
    }
}
PK#1[�O#�''JTwigBridge/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Node;

use Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode;

class SearchAndRenderBlockNodeTest extends \PHPUnit_Framework_TestCase
{
    public function testCompileWidget()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
        ));

        $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'widget\')',
                $this->getVariableGetter('form')
             ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileWidgetWithVariables()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Array(array(
                new \Twig_Node_Expression_Constant('foo', 0),
                new \Twig_Node_Expression_Constant('bar', 0),
            ), 0),
        ));

        $node = new SearchAndRenderBlockNode('form_widget', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'widget\', array("foo" => "bar"))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithLabel()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Constant('my label', 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\', array("label" => "my label"))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithNullLabel()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Constant(null, 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        // "label" => null must not be included in the output!
        // Otherwise the default label is overwritten with null.
        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\')',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithEmptyStringLabel()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Constant('', 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        // "label" => null must not be included in the output!
        // Otherwise the default label is overwritten with null.
        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\')',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithDefaultLabel()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\')',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithAttributes()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Constant(null, 0),
            new \Twig_Node_Expression_Array(array(
                new \Twig_Node_Expression_Constant('foo', 0),
                new \Twig_Node_Expression_Constant('bar', 0),
            ), 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        // "label" => null must not be included in the output!
        // Otherwise the default label is overwritten with null.
        // https://github.com/symfony/symfony/issues/5029
        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\', array("foo" => "bar"))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithLabelAndAttributes()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Constant('value in argument', 0),
            new \Twig_Node_Expression_Array(array(
                new \Twig_Node_Expression_Constant('foo', 0),
                new \Twig_Node_Expression_Constant('bar', 0),
                new \Twig_Node_Expression_Constant('label', 0),
                new \Twig_Node_Expression_Constant('value in attributes', 0),
            ), 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\', array("foo" => "bar", "label" => "value in argument"))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithLabelThatEvaluatesToNull()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Conditional(
                // if
                new \Twig_Node_Expression_Constant(true, 0),
                // then
                new \Twig_Node_Expression_Constant(null, 0),
                // else
                new \Twig_Node_Expression_Constant(null, 0),
                0
            ),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        // "label" => null must not be included in the output!
        // Otherwise the default label is overwritten with null.
        // https://github.com/symfony/symfony/issues/5029
        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\', (twig_test_empty($_label_ = ((true) ? (null) : (null))) ? array() : array("label" => $_label_)))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    public function testCompileLabelWithLabelThatEvaluatesToNullAndAttributes()
    {
        $arguments = new \Twig_Node(array(
            new \Twig_Node_Expression_Name('form', 0),
            new \Twig_Node_Expression_Conditional(
                // if
                new \Twig_Node_Expression_Constant(true, 0),
                // then
                new \Twig_Node_Expression_Constant(null, 0),
                // else
                new \Twig_Node_Expression_Constant(null, 0),
                0
            ),
            new \Twig_Node_Expression_Array(array(
                new \Twig_Node_Expression_Constant('foo', 0),
                new \Twig_Node_Expression_Constant('bar', 0),
                new \Twig_Node_Expression_Constant('label', 0),
                new \Twig_Node_Expression_Constant('value in attributes', 0),
            ), 0),
        ));

        $node = new SearchAndRenderBlockNode('form_label', $arguments, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        // "label" => null must not be included in the output!
        // Otherwise the default label is overwritten with null.
        // https://github.com/symfony/symfony/issues/5029
        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->searchAndRenderBlock(%s, \'label\', array("foo" => "bar", "label" => "value in attributes") + (twig_test_empty($_label_ = ((true) ? (null) : (null))) ? array() : array("label" => $_label_)))',
                $this->getVariableGetter('form')
            ),
            trim($compiler->compile($node)->getSource())
        );
    }

    protected function getVariableGetter($name)
    {
        if (version_compare(phpversion(), '5.4.0RC1', '>=')) {
            return sprintf('(isset($context["%s"]) ? $context["%s"] : null)', $name, $name);
        }

        return sprintf('$this->getContext($context, "%s")', $name);
    }
}
PK#1[�h�H	H	;TwigBridge/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Node;

use Symfony\Bridge\Twig\Node\FormThemeNode;

class FormThemeTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $form = new \Twig_Node_Expression_Name('form', 0);
        $resources = new \Twig_Node(array(
            new \Twig_Node_Expression_Constant('tpl1', 0),
            new \Twig_Node_Expression_Constant('tpl2', 0)
        ));

        $node = new FormThemeNode($form, $resources, 0);

        $this->assertEquals($form, $node->getNode('form'));
        $this->assertEquals($resources, $node->getNode('resources'));
    }

    public function testCompile()
    {
        $form = new \Twig_Node_Expression_Name('form', 0);
        $resources = new \Twig_Node_Expression_Array(array(
            new \Twig_Node_Expression_Constant(0, 0),
            new \Twig_Node_Expression_Constant('tpl1', 0),
            new \Twig_Node_Expression_Constant(1, 0),
            new \Twig_Node_Expression_Constant('tpl2', 0)
        ), 0);

        $node = new FormThemeNode($form, $resources, 0);

        $compiler = new \Twig_Compiler(new \Twig_Environment());

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->setTheme(%s, array(0 => "tpl1", 1 => "tpl2"));',
                $this->getVariableGetter('form')
             ),
            trim($compiler->compile($node)->getSource())
        );

        $resources = new \Twig_Node_Expression_Constant('tpl1', 0);

        $node = new FormThemeNode($form, $resources, 0);

        $this->assertEquals(
            sprintf(
                '$this->env->getExtension(\'form\')->renderer->setTheme(%s, "tpl1");',
                $this->getVariableGetter('form')
             ),
            trim($compiler->compile($node)->getSource())
        );
    }

    protected function getVariableGetter($name)
    {
        if (version_compare(phpversion(), '5.4.0RC1', '>=')) {
            return sprintf('(isset($context["%s"]) ? $context["%s"] : null)', $name, $name);
        }

        return sprintf('$this->getContext($context, "%s")', $name);
    }
}
PK#1[ͅi�997TwigBridge/Symfony/Bridge/Twig/Tests/TwigEngineTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests;

use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Component\Templating\TemplateReference;

class TwigEngineTest extends \PHPUnit_Framework_TestCase
{
    public function testExistsWithTemplateInstances()
    {
        $engine = $this->getTwig();

        $this->assertTrue($engine->exists($this->getMockForAbstractClass('Twig_Template', array(), '', false)));
    }

    public function testExistsWithNonExistentTemplates()
    {
        $engine = $this->getTwig();

        $this->assertFalse($engine->exists('foobar'));
        $this->assertFalse($engine->exists(new TemplateReference('foorbar')));
    }

    public function testExistsWithTemplateWithSyntaxErrors()
    {
        $engine = $this->getTwig();

        $this->assertTrue($engine->exists('error'));
        $this->assertTrue($engine->exists(new TemplateReference('error')));
    }

    public function testExists()
    {
        $engine = $this->getTwig();

        $this->assertTrue($engine->exists('index'));
        $this->assertTrue($engine->exists(new TemplateReference('index')));
    }

    public function testRender()
    {
        $engine = $this->getTwig();

        $this->assertSame('foo', $engine->render('index'));
        $this->assertSame('foo', $engine->render(new TemplateReference('index')));
    }

    /**
     * @expectedException \Twig_Error_Syntax
     */
    public function testRenderWithError()
    {
        $engine = $this->getTwig();

        $engine->render(new TemplateReference('error'));
    }

    protected function getTwig()
    {
        $twig = new \Twig_Environment(new \Twig_Loader_Array(array(
            'index' => 'foo',
            'error' => '{{ foo }',
        )));
        $parser = $this->getMock('Symfony\Component\Templating\TemplateNameParserInterface');

        return new TwigEngine($twig, $parser);
    }
}
PK#1[k�K�\TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\NodeVisitor;

use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor;
use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor;

class TranslationDefaultDomainNodeVisitorTest extends \PHPUnit_Framework_TestCase
{
    private static $message = 'message';
    private static $domain = 'domain';

    /** @dataProvider getDefaultDomainAssignmentTestData */
    public function testDefaultDomainAssignment(\Twig_Node $node)
    {
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0));
        $visitor = new TranslationDefaultDomainNodeVisitor();

        // visit trans_default_domain tag
        $defaultDomain = TwigNodeProvider::getTransDefaultDomainTag(self::$domain);
        $visitor->enterNode($defaultDomain, $env);
        $visitor->leaveNode($defaultDomain, $env);

        // visit tested node
        $enteredNode = $visitor->enterNode($node, $env);
        $leavedNode = $visitor->leaveNode($node, $env);
        $this->assertSame($node, $enteredNode);
        $this->assertSame($node, $leavedNode);

        // extracting tested node messages
        $visitor = new TranslationNodeVisitor();
        $visitor->enable();
        $visitor->enterNode($node, $env);
        $visitor->leaveNode($node, $env);

        $this->assertEquals(array(array(self::$message, self::$domain)), $visitor->getMessages());
    }

    /** @dataProvider getDefaultDomainAssignmentTestData */
    public function testNewModuleWithoutDefaultDomainTag(\Twig_Node $node)
    {
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0));
        $visitor = new TranslationDefaultDomainNodeVisitor();

        // visit trans_default_domain tag
        $newModule = TwigNodeProvider::getModule('test');
        $visitor->enterNode($newModule, $env);
        $visitor->leaveNode($newModule, $env);

        // visit tested node
        $enteredNode = $visitor->enterNode($node, $env);
        $leavedNode = $visitor->leaveNode($node, $env);
        $this->assertSame($node, $enteredNode);
        $this->assertSame($node, $leavedNode);

        // extracting tested node messages
        $visitor = new TranslationNodeVisitor();
        $visitor->enable();
        $visitor->enterNode($node, $env);
        $visitor->leaveNode($node, $env);

        $this->assertEquals(array(array(self::$message, null)), $visitor->getMessages());
    }

    public function getDefaultDomainAssignmentTestData()
    {
        return array(
            array(TwigNodeProvider::getTransFilter(self::$message)),
            array(TwigNodeProvider::getTransChoiceFilter(self::$message)),
            array(TwigNodeProvider::getTransTag(self::$message)),
        );
    }
}
PK#1[¶
���OTwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\NodeVisitor;

use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor;

class TranslationNodeVisitorTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getMessagesExtractionTestData */
    public function testMessagesExtraction(\Twig_Node $node, array $expectedMessages)
    {
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0));
        $visitor = new TranslationNodeVisitor();
        $visitor->enable();
        $visitor->enterNode($node, $env);
        $visitor->leaveNode($node, $env);
        $this->assertEquals($expectedMessages, $visitor->getMessages());
    }

    public function testMessageExtractionWithInvalidDomainNode()
    {
        $message = 'new key';

        $node = new \Twig_Node_Expression_Filter(
            new \Twig_Node_Expression_Constant($message, 0),
            new \Twig_Node_Expression_Constant('trans', 0),
            new \Twig_Node(array(
                new \Twig_Node_Expression_Array(array(), 0),
                new \Twig_Node_Expression_Name('variable', 0),
            )),
            0
        );

        $this->testMessagesExtraction($node, array(array($message, TranslationNodeVisitor::UNDEFINED_DOMAIN)));
    }

    public function getMessagesExtractionTestData()
    {
        $message = 'new key';
        $domain = 'domain';

        return array(
            array(TwigNodeProvider::getTransFilter($message), array(array($message, null))),
            array(TwigNodeProvider::getTransChoiceFilter($message), array(array($message, null))),
            array(TwigNodeProvider::getTransTag($message), array(array($message, null))),
            array(TwigNodeProvider::getTransFilter($message, $domain), array(array($message, $domain))),
            array(TwigNodeProvider::getTransChoiceFilter($message, $domain), array(array($message, $domain))),
            array(TwigNodeProvider::getTransTag($message, $domain), array(array($message, $domain))),
        );
    }
}
PK#1[j|$		ETwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\NodeVisitor;

use Symfony\Bridge\Twig\Node\TransDefaultDomainNode;
use Symfony\Bridge\Twig\Node\TransNode;

class TwigNodeProvider
{
    public static function getModule($content)
    {
        return new \Twig_Node_Module(
            new \Twig_Node_Expression_Constant($content, 0),
            null,
            new \Twig_Node_Expression_Array(array(), 0),
            new \Twig_Node_Expression_Array(array(), 0),
            new \Twig_Node_Expression_Array(array(), 0),
            null,
            null
        );
    }

    public static function getTransFilter($message, $domain = null)
    {
        $arguments = $domain ? array(
            new \Twig_Node_Expression_Array(array(), 0),
            new \Twig_Node_Expression_Constant($domain, 0),
        ) : array();

        return new \Twig_Node_Expression_Filter(
            new \Twig_Node_Expression_Constant($message, 0),
            new \Twig_Node_Expression_Constant('trans', 0),
            new \Twig_Node($arguments),
            0
        );
    }

    public static function getTransChoiceFilter($message, $domain = null)
    {
        $arguments = $domain ? array(
            new \Twig_Node_Expression_Constant(0, 0),
            new \Twig_Node_Expression_Array(array(), 0),
            new \Twig_Node_Expression_Constant($domain, 0),
        ) : array();

        return new \Twig_Node_Expression_Filter(
            new \Twig_Node_Expression_Constant($message, 0),
            new \Twig_Node_Expression_Constant('transchoice', 0),
            new \Twig_Node($arguments),
            0
        );
    }

    public static function getTransTag($message, $domain = null)
    {
        return new TransNode(
            new \Twig_Node_Body(array(), array('data' => $message)),
            $domain ? new \Twig_Node_Expression_Constant($domain, 0) : null
        );
    }

    public static function getTransDefaultDomainTag($domain)
    {
        return new TransDefaultDomainNode(
            new \Twig_Node_Expression_Constant($domain, 0)
        );
    }
}
PK#1[�6��!!>TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/ScopeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\NodeVisitor;

use Symfony\Bridge\Twig\NodeVisitor\Scope;

class ScopeTest extends \PHPUnit_Framework_TestCase
{
    public function testScopeInitiation()
    {
        $scope = new Scope();
        $scope->enter();
        $this->assertNull($scope->get('test'));
    }
}
PK#1[#�
�
MTwigBridge/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\TokenParser;

use Symfony\Bridge\Twig\TokenParser\FormThemeTokenParser;
use Symfony\Bridge\Twig\Node\FormThemeNode;

class FormThemeTokenParserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTestsForFormTheme
     */
    public function testCompile($source, $expected)
    {
        $env = new \Twig_Environment(new \Twig_Loader_String(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0));
        $env->addTokenParser(new FormThemeTokenParser());
        $stream = $env->tokenize($source);
        $parser = new \Twig_Parser($env);

        $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0));
    }

    public function getTestsForFormTheme()
    {
        return array(
            array(
                '{% form_theme form "tpl1" %}',
                new FormThemeNode(
                    new \Twig_Node_Expression_Name('form', 1),
                    new \Twig_Node_Expression_Array(array(
                        new \Twig_Node_Expression_Constant(0, 1),
                        new \Twig_Node_Expression_Constant('tpl1', 1),
                    ), 1),
                    1,
                    'form_theme'
                )
            ),
            array(
                '{% form_theme form "tpl1" "tpl2" %}',
                new FormThemeNode(
                    new \Twig_Node_Expression_Name('form', 1),
                    new \Twig_Node_Expression_Array(array(
                        new \Twig_Node_Expression_Constant(0, 1),
                        new \Twig_Node_Expression_Constant('tpl1', 1),
                        new \Twig_Node_Expression_Constant(1, 1),
                        new \Twig_Node_Expression_Constant('tpl2', 1)
                    ), 1),
                    1,
                    'form_theme'
                )
            ),
            array(
                '{% form_theme form with "tpl1" %}',
                new FormThemeNode(
                    new \Twig_Node_Expression_Name('form', 1),
                    new \Twig_Node_Expression_Constant('tpl1', 1),
                    1,
                    'form_theme'
                )
            ),
            array(
                '{% form_theme form with ["tpl1"] %}',
                new FormThemeNode(
                    new \Twig_Node_Expression_Name('form', 1),
                    new \Twig_Node_Expression_Array(array(
                        new \Twig_Node_Expression_Constant(0, 1),
                        new \Twig_Node_Expression_Constant('tpl1', 1),
                    ), 1),
                    1,
                    'form_theme'
                )
            ),
            array(
                '{% form_theme form with ["tpl1", "tpl2"] %}',
                new FormThemeNode(
                    new \Twig_Node_Expression_Name('form', 1),
                    new \Twig_Node_Expression_Array(array(
                        new \Twig_Node_Expression_Constant(0, 1),
                        new \Twig_Node_Expression_Constant('tpl1', 1),
                        new \Twig_Node_Expression_Constant(1, 1),
                        new \Twig_Node_Expression_Constant('tpl2', 1)
                    ), 1),
                    1,
                    'form_theme'
                )
            ),
        );
    }
}
PK#1[��x��GTwigBridge/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\RoutingExtension;

class RoutingExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getEscapingTemplates
     */
    public function testEscaping($template, $mustBeEscaped)
    {
        $twig = new \Twig_Environment(null, array('debug' => true, 'cache' => false, 'autoescape' => true, 'optimizations' => 0));
        $twig->addExtension(new RoutingExtension($this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface')));

        $nodes = $twig->parse($twig->tokenize($template));

        $this->assertSame($mustBeEscaped, $nodes->getNode('body')->getNode(0)->getNode('expr') instanceof \Twig_Node_Expression_Filter);
    }

    public function getEscapingTemplates()
    {
        return array(
            array('{{ path("foo") }}', false),
            array('{{ path("foo", {}) }}', false),
            array('{{ path("foo", { foo: "foo" }) }}', false),
            array('{{ path("foo", foo) }}', true),
            array('{{ path("foo", { foo: foo }) }}', true),
            array('{{ path("foo", { foo: ["foo", "bar"] }) }}', true),
            array('{{ path("foo", { foo: "foo", bar: "bar" }) }}', true),

            array('{{ path(name = "foo", parameters = {}) }}', false),
            array('{{ path(name = "foo", parameters = { foo: "foo" }) }}', false),
            array('{{ path(name = "foo", parameters = foo) }}', true),
            array('{{ path(name = "foo", parameters = { foo: ["foo", "bar"] }) }}', true),
            array('{{ path(name = "foo", parameters = { foo: foo }) }}', true),
            array('{{ path(name = "foo", parameters = { foo: "foo", bar: "bar" }) }}', true),
        );
    }
}
PK#1[:��WWOTwigBridge/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Component\Form\FormView;
use Symfony\Bridge\Twig\Form\TwigRenderer;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Form\Tests\AbstractTableLayoutTest;
use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator;
use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader;

class FormExtensionTableLayoutTest extends AbstractTableLayoutTest
{
    /**
     * @var FormExtension
     */
    protected $extension;

    protected function setUp()
    {
        parent::setUp();

        $rendererEngine = new TwigRendererEngine(array(
            'form_table_layout.html.twig',
            'custom_widgets.html.twig',
        ));
        $renderer = new TwigRenderer($rendererEngine, $this->getMock('Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface'));

        $this->extension = new FormExtension($renderer);

        $loader = new StubFilesystemLoader(array(
            __DIR__.'/../../Resources/views/Form',
            __DIR__,
        ));

        $environment = new \Twig_Environment($loader, array('strict_variables' => true));
        $environment->addExtension(new TranslationExtension(new StubTranslator()));
        $environment->addGlobal('global', '');
        $environment->addExtension($this->extension);

        $this->extension->initRuntime($environment);
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->extension = null;
    }

    protected function renderForm(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form', $vars);
    }

    protected function renderEnctype(FormView $view)
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'enctype');
    }

    protected function renderLabel(FormView $view, $label = null, array $vars = array())
    {
        if ($label !== null) {
            $vars += array('label' => $label);
        }

        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'label', $vars);
    }

    protected function renderErrors(FormView $view)
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'errors');
    }

    protected function renderWidget(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'widget', $vars);
    }

    protected function renderRow(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'row', $vars);
    }

    protected function renderRest(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'rest', $vars);
    }

    protected function renderStart(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form_start', $vars);
    }

    protected function renderEnd(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form_end', $vars);
    }

    protected function setTheme(FormView $view, array $themes)
    {
        $this->extension->renderer->setTheme($view, $themes);
    }
}
PK#1[t�9A
A
JTwigBridge/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\HttpKernelExtension;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Fragment\FragmentHandler;

class HttpKernelExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Twig_Error_Runtime
     */
    public function testFragmentWithError()
    {
        $renderer = $this->getFragmentHandler($this->throwException(new \Exception('foo')));

        $this->renderTemplate($renderer);
    }

    public function testRenderFragment()
    {
        $renderer = $this->getFragmentHandler($this->returnValue(new Response('html')));

        $response = $this->renderTemplate($renderer);

        $this->assertEquals('html', $response);
    }

    public function testUnknownFragmentRenderer()
    {
        $context = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $renderer = new FragmentHandler(array(), false, $context);

        $this->setExpectedException('InvalidArgumentException', 'The "inline" renderer does not exist.');
        $renderer->render('/foo');
    }

    protected function getFragmentHandler($return)
    {
        $strategy = $this->getMock('Symfony\\Component\\HttpKernel\\Fragment\\FragmentRendererInterface');
        $strategy->expects($this->once())->method('getName')->will($this->returnValue('inline'));
        $strategy->expects($this->once())->method('render')->will($return);

        $context = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack')
            ->disableOriginalConstructor()
            ->getMock()
        ;

        $context->expects($this->any())->method('getCurrentRequest')->will($this->returnValue(Request::create('/')));

        $renderer = new FragmentHandler(array($strategy), false, $context);

        return $renderer;
    }

    protected function renderTemplate(FragmentHandler $renderer, $template = '{{ render("foo") }}')
    {
        $loader = new \Twig_Loader_Array(array('index' => $template));
        $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
        $twig->addExtension(new HttpKernelExtension($renderer));

        return $twig->render('index');
    }
}
PK#1[�V�%33MTwigBridge/Symfony/Bridge/Twig/Tests/Extension/page_dynamic_extends.html.twignu�[���{% extends dynamic_template_name ~ '.html.twig' %}
PK#1[�]��PTwigBridge/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension\Fixtures;

class StubFilesystemLoader extends \Twig_Loader_Filesystem
{
    protected function findTemplate($name)
    {
        // strip away bundle name
        $parts = explode(':', $name);

        return parent::findTemplate(end($parts));
    }
}
PK#1[*��n**JTwigBridge/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension\Fixtures;

use Symfony\Component\Translation\TranslatorInterface;

class StubTranslator implements TranslatorInterface
{
    public function trans($id, array $parameters = array(), $domain = null, $locale = null)
    {
        return '[trans]'.$id.'[/trans]';
    }

    public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null)
    {
        return '[trans]'.$id.'[/trans]';
    }

    public function setLocale($locale)
    {
    }

    public function getLocale()
    {
    }
}
PK#1[̙nsBTwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme_use.html.twignu�[���{% use 'form_div_layout.html.twig' %}

{% block form_widget_simple %}
{% spaceless %}
    {% set type = type|default('text') %}
    <input type="{{ type }}" {{ block('widget_attributes') }} value="{{ value }}" rel="theme" />
{% endspaceless %}
{% endblock form_widget_simple %}
PK#1[�+����DTwigBridge/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\CodeExtension;

class CodeExtensionTest extends \PHPUnit_Framework_TestCase
{
    protected $helper;

    public function testFormatFile()
    {
        $expected = sprintf('<a href="txmt://open?url=file://%s&amp;line=25" title="Click to open this file" class="file_link">%s at line 25</a>', __FILE__, __FILE__);
        $this->assertEquals($expected, $this->getExtension()->formatFile(__FILE__, 25));
    }

    /**
     * @dataProvider getClassNameProvider
     */
    public function testGettingClassAbbreviation($class, $abbr)
    {
        $this->assertEquals($this->getExtension()->abbrClass($class), $abbr);
    }

    /**
     * @dataProvider getMethodNameProvider
     */
    public function testGettingMethodAbbreviation($method, $abbr)
    {
        $this->assertEquals($this->getExtension()->abbrMethod($method), $abbr);
    }

    public function getClassNameProvider()
    {
        return array(
            array('F\Q\N\Foo', '<abbr title="F\Q\N\Foo">Foo</abbr>'),
            array('Bare', '<abbr title="Bare">Bare</abbr>'),
        );
    }

    public function getMethodNameProvider()
    {
        return array(
            array('F\Q\N\Foo::Method', '<abbr title="F\Q\N\Foo">Foo</abbr>::Method()'),
            array('Bare::Method', '<abbr title="Bare">Bare</abbr>::Method()'),
            array('Closure', '<abbr title="Closure">Closure</abbr>'),
            array('Method', '<abbr title="Method">Method</abbr>()')
        );
    }

    public function testGetName()
    {
        $this->assertEquals('code', $this->getExtension()->getName());
    }

    protected function getExtension()
    {
        return new CodeExtension('txmt://open?url=file://%f&line=%l', '/root', 'UTF-8');
    }
}
PK#1[%o��	�	ITwigBridge/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\StopwatchExtension;

class StopwatchExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Twig_Error_Syntax
     */
    public function testFailIfStoppingWrongEvent()
    {
        $this->testTiming('{% stopwatch "foo" %}{% endstopwatch "bar" %}', array());
    }

    /**
     * @dataProvider getTimingTemplates
     */
    public function testTiming($template, $events)
    {
        $twig = new \Twig_Environment(new \Twig_Loader_String(), array('debug' => true, 'cache' => false, 'autoescape' => true, 'optimizations' => 0));
        $twig->addExtension(new StopwatchExtension($this->getStopwatch($events)));

        try {
            $nodes = $twig->render($template);
        } catch (\Twig_Error_Runtime $e) {
            throw $e->getPrevious();
        }
    }

    public function getTimingTemplates()
    {
        return array(
            array('{% stopwatch "foo" %}something{% endstopwatch %}', 'foo'),
            array('{% stopwatch "foo" %}symfony2 is fun{% endstopwatch %}{% stopwatch "bar" %}something{% endstopwatch %}', array('foo', 'bar')),
            array('{% set foo = "foo" %}{% stopwatch foo %}something{% endstopwatch %}', 'foo'),
            array('{% set foo = "foo" %}{% stopwatch foo %}something {% set foo = "bar" %}{% endstopwatch %}', 'foo'),
            array('{% stopwatch "foo.bar" %}something{% endstopwatch %}', 'foo.bar'),
            array('{% stopwatch "foo" %}something{% endstopwatch %}{% stopwatch "foo" %}something else{% endstopwatch %}', array('foo', 'foo')),
        );
    }

    protected function getStopwatch($events = array())
    {
        $events = is_array($events) ? $events : array($events);
        $stopwatch = $this->getMock('Symfony\Component\Stopwatch\Stopwatch');

        $i = -1;
        foreach ($events as $eventName) {
            $stopwatch->expects($this->at(++$i))
                ->method('start')
                ->with($this->equalTo($eventName), 'template')
            ;
            $stopwatch->expects($this->at(++$i))
                ->method('stop')
                ->with($this->equalTo($eventName))
            ;
        }

        return $stopwatch;
    }
}
PK#1[��ߋ��JTwigBridge/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\ExpressionExtension;
use Symfony\Component\ExpressionLanguage\Expression;

class ExpressionExtensionTest extends \PHPUnit_Framework_TestCase
{
    protected $helper;

    public function testExpressionCreation()
    {
        $template = "{{ expression('1 == 1') }}";
        $twig = new \Twig_Environment(new \Twig_Loader_String(), array('debug' => true, 'cache' => false, 'autoescape' => true, 'optimizations' => 0));
        $twig->addExtension(new ExpressionExtension());

        $output = $twig->render($template);
        $this->assertEquals('1 == 1', $output);
    }
}
PK#1[��,'KKETwigBridge/Symfony/Bridge/Twig/Tests/Extension/parent_label.html.twignu�[���{% block form_label %}
    <label>parent</label>
{% endblock form_label %}
PK#1[�����KTwigBridge/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader;

class TranslationExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testEscaping()
    {
        $output = $this->getTemplate('{% trans %}Percent: %value%%% (%msg%){% endtrans %}')->render(array('value' => 12, 'msg' => 'approx.'));

        $this->assertEquals('Percent: 12% (approx.)', $output);
    }

    /**
     * @dataProvider getTransTests
     */
    public function testTrans($template, $expected, array $variables = array())
    {
        if ($expected != $this->getTemplate($template)->render($variables)) {
            print $template."\n";
            $loader = new \Twig_Loader_Array(array('index' => $template));
            $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
            $twig->addExtension(new TranslationExtension(new Translator('en', new MessageSelector())));

            echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSource('index'), 'index')))."\n\n";
            $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
        }

        $this->assertEquals($expected, $this->getTemplate($template)->render($variables));
    }

    /**
     * @expectedException        \Twig_Error_Syntax
     * @expectedExceptionMessage Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3.
     */
    public function testTransUnknownKeyword()
    {
        $output = $this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render();
    }

    /**
     * @expectedException        \Twig_Error_Syntax
     * @expectedExceptionMessage A message inside a trans tag must be a simple text in "index" at line 2.
     */
    public function testTransComplexBody()
    {
        $output = $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render();
    }

    /**
     * @expectedException        \Twig_Error_Syntax
     * @expectedExceptionMessage A message inside a transchoice tag must be a simple text in "index" at line 2.
     */
    public function testTransChoiceComplexBody()
    {
        $output = $this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render();
    }

    public function getTransTests()
    {
        return array(
            // trans tag
            array('{% trans %}Hello{% endtrans %}', 'Hello'),
            array('{% trans %}%name%{% endtrans %}', 'Symfony2', array('name' => 'Symfony2')),

            array('{% trans from elsewhere %}Hello{% endtrans %}', 'Hello'),

            array('{% trans %}Hello %name%{% endtrans %}', 'Hello Symfony2', array('name' => 'Symfony2')),
            array('{% trans with { \'%name%\': \'Symfony2\' } %}Hello %name%{% endtrans %}', 'Hello Symfony2'),
            array('{% set vars = { \'%name%\': \'Symfony2\' } %}{% trans with vars %}Hello %name%{% endtrans %}', 'Hello Symfony2'),

            array('{% trans into "fr"%}Hello{% endtrans %}', 'Hello'),

            // transchoice
            array('{% transchoice count from "messages" %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}',
                'There is no apples', array('count' => 0)),
            array('{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}',
                'There is 5 apples', array('count' => 5)),
            array('{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%){% endtranschoice %}',
                'There is 5 apples (Symfony2)', array('count' => 5, 'name' => 'Symfony2')),
            array('{% transchoice count with { \'%name%\': \'Symfony2\' } %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%){% endtranschoice %}',
                'There is 5 apples (Symfony2)', array('count' => 5)),
            array('{% transchoice count into "fr"%}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}',
                'There is no apples', array('count' => 0)),

            // trans filter
            array('{{ "Hello"|trans }}', 'Hello'),
            array('{{ name|trans }}', 'Symfony2', array('name' => 'Symfony2')),
            array('{{ hello|trans({ \'%name%\': \'Symfony2\' }) }}', 'Hello Symfony2', array('hello' => 'Hello %name%')),
            array('{% set vars = { \'%name%\': \'Symfony2\' } %}{{ hello|trans(vars) }}', 'Hello Symfony2', array('hello' => 'Hello %name%')),
            array('{{ "Hello"|trans({}, "messages", "fr") }}', 'Hello'),

            // transchoice filter
            array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count) }}', 'There is 5 apples', array('count' => 5)),
            array('{{ text|transchoice(5, {\'%name%\': \'Symfony2\'}) }}', 'There is 5 apples (Symfony2)', array('text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)')),
            array('{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count, {}, "messages", "fr") }}', 'There is 5 apples', array('count' => 5)),
        );
    }

    public function testDefaultTranslationDomain()
    {
        $templates = array(
            'index' => '
                {%- extends "base" %}

                {%- trans_default_domain "foo" %}

                {%- block content %}
                    {%- trans %}foo{% endtrans %}
                    {%- trans from "custom" %}foo{% endtrans %}
                    {{- "foo"|trans }}
                    {{- "foo"|trans({}, "custom") }}
                    {{- "foo"|transchoice(1) }}
                    {{- "foo"|transchoice(1, {}, "custom") }}
                {% endblock %}
            ',

            'base' => '
                {%- block content "" %}
            ',
        );

        $translator = new Translator('en', new MessageSelector());
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foo (messages)'), 'en');
        $translator->addResource('array', array('foo' => 'foo (custom)'), 'en', 'custom');
        $translator->addResource('array', array('foo' => 'foo (foo)'), 'en', 'foo');

        $template = $this->getTemplate($templates, $translator);

        $this->assertEquals('foo (foo)foo (custom)foo (foo)foo (custom)foo (foo)foo (custom)', trim($template->render(array())));
    }

    protected function getTemplate($template, $translator = null)
    {
        if (null === $translator) {
            $translator = new Translator('en', new MessageSelector());
        }

        if (is_array($template)) {
            $loader = new \Twig_Loader_Array($template);
        } else {
            $loader = new \Twig_Loader_Array(array('index' => $template));
        }
        $twig = new \Twig_Environment($loader, array('debug' => true, 'cache' => false));
        $twig->addExtension(new TranslationExtension($translator));

        return $twig->loadTemplate('index');
    }
}
PK#1[(���>TwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme.html.twignu�[���{% block form_widget_simple %}
{% spaceless %}
    {% set type = type|default('text') %}
    <input type="{{ type }}" {{ block('widget_attributes') }} value="{{ value }}" rel="theme" />
{% endspaceless %}
{% endblock form_widget_simple %}
PK$1[��i�!!MTwigBridge/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Twig\Tests\Extension;

use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRenderer;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Bridge\Twig\Extension\TranslationExtension;
use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator;
use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\Tests\AbstractDivLayoutTest;

class FormExtensionDivLayoutTest extends AbstractDivLayoutTest
{
    /**
     * @var FormExtension
     */
    protected $extension;

    protected function setUp()
    {
        parent::setUp();

        $rendererEngine = new TwigRendererEngine(array(
            'form_div_layout.html.twig',
            'custom_widgets.html.twig',
        ));
        $renderer = new TwigRenderer($rendererEngine, $this->getMock('Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderInterface'));

        $this->extension = new FormExtension($renderer);

        $loader = new StubFilesystemLoader(array(
            __DIR__.'/../../Resources/views/Form',
            __DIR__,
        ));

        $environment = new \Twig_Environment($loader, array('strict_variables' => true));
        $environment->addExtension(new TranslationExtension(new StubTranslator()));
        $environment->addGlobal('global', '');
        // the value can be any template that exists
        $environment->addGlobal('dynamic_template_name', 'child_label');
        $environment->addExtension($this->extension);

        $this->extension->initRuntime($environment);
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->extension = null;
    }

    public function testThemeBlockInheritanceUsingUse()
    {
        $view = $this->factory
            ->createNamed('name', 'email')
            ->createView()
        ;

        $this->setTheme($view, array('theme_use.html.twig'));

        $this->assertMatchesXpath(
            $this->renderWidget($view),
            '/input[@type="email"][@rel="theme"]'
        );
    }

    public function testThemeBlockInheritanceUsingExtend()
    {
        $view = $this->factory
            ->createNamed('name', 'email')
            ->createView()
        ;

        $this->setTheme($view, array('theme_extends.html.twig'));

        $this->assertMatchesXpath(
            $this->renderWidget($view),
            '/input[@type="email"][@rel="theme"]'
        );
    }

    public function testThemeBlockInheritanceUsingDynamicExtend()
    {
        $view = $this->factory
            ->createNamed('name', 'email')
            ->createView()
        ;

        $renderer = $this->extension->renderer;
        $renderer->setTheme($view, array('page_dynamic_extends.html.twig'));
        $renderer->searchAndRenderBlock($view, 'row');
    }

    public function isSelectedChoiceProvider()
    {
        // The commented cases should not be necessary anymore, because the
        // choice lists should assure that both values passed here are always
        // strings
        return array(
//             array(true, 0, 0),
            array(true, '0', '0'),
            array(true, '1', '1'),
//             array(true, false, 0),
//             array(true, true, 1),
            array(true, '', ''),
//             array(true, null, ''),
            array(true, '1.23', '1.23'),
            array(true, 'foo', 'foo'),
            array(true, 'foo10', 'foo10'),
            array(true, 'foo', array(1, 'foo', 'foo10')),

            array(false, 10, array(1, 'foo', 'foo10')),
            array(false, 0, array(1, 'foo', 'foo10')),
        );
    }

    /**
     * @dataProvider isSelectedChoiceProvider
     */
    public function testIsChoiceSelected($expected, $choice, $value)
    {
        $choice = new ChoiceView($choice, $choice, $choice.' label');

        $this->assertSame($expected, $this->extension->isSelectedChoice($choice, $value));
    }

    protected function renderForm(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form', $vars);
    }

    protected function renderEnctype(FormView $view)
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'enctype');
    }

    protected function renderLabel(FormView $view, $label = null, array $vars = array())
    {
        if ($label !== null) {
            $vars += array('label' => $label);
        }

        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'label', $vars);
    }

    protected function renderErrors(FormView $view)
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'errors');
    }

    protected function renderWidget(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'widget', $vars);
    }

    protected function renderRow(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'row', $vars);
    }

    protected function renderRest(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->searchAndRenderBlock($view, 'rest', $vars);
    }

    protected function renderStart(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form_start', $vars);
    }

    protected function renderEnd(FormView $view, array $vars = array())
    {
        return (string) $this->extension->renderer->renderBlock($view, 'form_end', $vars);
    }

    protected function setTheme(FormView $view, array $themes)
    {
        $this->extension->renderer->setTheme($view, $themes);
    }

    public static function themeBlockInheritanceProvider()
    {
        return array(
            array(array('theme.html.twig'))
        );
    }

    public static function themeInheritanceProvider()
    {
        return array(
            array(array('parent_label.html.twig'), array('child_label.html.twig'))
        );
    }
}
PK$1[Һ
�VVDTwigBridge/Symfony/Bridge/Twig/Tests/Extension/child_label.html.twignu�[���{% block form_label %}
    <label>{{ global }}child</label>
{% endblock form_label %}
PK$1[�tdFTwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme_extends.html.twignu�[���{% extends 'form_div_layout.html.twig' %}

{% block form_widget_simple %}
{% spaceless %}
    {% set type = type|default('text') %}
    <input type="{{ type }}" {{ block('widget_attributes') }} value="{{ value }}" rel="theme" />
{% endspaceless %}
{% endblock form_widget_simple %}
PK$1[��b���GTwigBridge/Symfony/Bridge/Twig/Tests/Extension/custom_widgets.html.twignu�[���{% block _text_id_widget %}
{% spaceless %}
    <div id="container">
        {{ form_widget(form) }}
    </div>
{% endspaceless %}
{% endblock _text_id_widget %}

{% block _name_entry_label %}
{% spaceless %}
    {% if label is empty %}
        {% set label = name|humanize %}
    {% endif %}
    <label>Custom label: {{ label|trans({}, translation_domain) }}</label>
{% endspaceless %}
{% endblock _name_entry_label %}
PK$1[Pcc/TwigBridge/Symfony/Bridge/Twig/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Twig Bridge Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK$1[h�9=UUJTranslation/Symfony/Component/Translation/Tests/IdentityTranslatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\IdentityTranslator;

class IdentityTranslatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTransTests
     */
    public function testTrans($expected, $id, $parameters)
    {
        $translator = new IdentityTranslator();

        $this->assertEquals($expected, $translator->trans($id, $parameters));
    }

    /**
     * @dataProvider getTransChoiceTests
     */
    public function testTransChoiceWithExplicitLocale($expected, $id, $number, $parameters)
    {
        $translator = new IdentityTranslator();
        $translator->setLocale('en');

        $this->assertEquals($expected, $translator->transChoice($id, $number, $parameters));
    }

    /**
     * @dataProvider getTransChoiceTests
     */
    public function testTransChoiceWithDefaultLocale($expected, $id, $number, $parameters)
    {
        \Locale::setDefault('en');

        $translator = new IdentityTranslator();

        $this->assertEquals($expected, $translator->transChoice($id, $number, $parameters));
    }

    public function testGetSetLocale()
    {
        $translator = new IdentityTranslator();
        $translator->setLocale('en');

        $this->assertEquals('en', $translator->getLocale());
    }

    public function testGetLocaleReturnsDefaultLocaleIfNotSet()
    {
        $translator = new IdentityTranslator();

        \Locale::setDefault('en');
        $this->assertEquals('en', $translator->getLocale());

        \Locale::setDefault('pt_BR');
        $this->assertEquals('pt_BR', $translator->getLocale());
    }

    public function getTransTests()
    {
        return array(
            array('Symfony2 is great!', 'Symfony2 is great!', array()),
            array('Symfony2 is awesome!', 'Symfony2 is %what%!', array('%what%' => 'awesome')),
        );
    }

    public function getTransChoiceTests()
    {
        return array(
            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0, array('%count%' => 0)),
            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1, array('%count%' => 1)),
            array('There are 10 apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10, array('%count%' => 10)),
            array('There are 0 apples', 'There is 1 apple|There are %count% apples', 0, array('%count%' => 0)),
            array('There is 1 apple', 'There is 1 apple|There are %count% apples', 1, array('%count%' => 1)),
            array('There are 10 apples', 'There is 1 apple|There are %count% apples', 10, array('%count%' => 10)),
            // custom validation messages may be coded with a fixed value
            array('There are 2 apples', 'There are 2 apples', 2, array('%count%' => 2)),
        );
    }
}
PK$1[���*|1|1BTranslation/Symfony/Component/Translation/Tests/TranslatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\ArrayLoader;

class TranslatorTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGetLocale()
    {
        $translator = new Translator('en');

        $this->assertEquals('en', $translator->getLocale());

        $translator->setLocale('fr');
        $this->assertEquals('fr', $translator->getLocale());
    }

    public function testSetFallbackLocales()
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foofoo'), 'en');
        $translator->addResource('array', array('bar' => 'foobar'), 'fr');

        // force catalogue loading
        $translator->trans('bar');

        $translator->setFallbackLocales(array('fr'));
        $this->assertEquals('foobar', $translator->trans('bar'));
    }

    public function testSetFallbackLocalesMultiple()
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foo (en)'), 'en');
        $translator->addResource('array', array('bar' => 'bar (fr)'), 'fr');

        // force catalogue loading
        $translator->trans('bar');

        $translator->setFallbackLocales(array('fr_FR', 'fr'));
        $this->assertEquals('bar (fr)', $translator->trans('bar'));
    }

    public function testTransWithFallbackLocale()
    {
        $translator = new Translator('fr_FR');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foofoo'), 'en_US');
        $translator->addResource('array', array('bar' => 'foobar'), 'en');

        $translator->setFallbackLocales(array('en'));

        $this->assertEquals('foobar', $translator->trans('bar'));
    }

    public function testAddResourceAfterTrans()
    {
        $translator = new Translator('fr');
        $translator->addLoader('array', new ArrayLoader());

        $translator->setFallbackLocale(array('en'));

        $translator->addResource('array', array('foo' => 'foofoo'), 'en');
        $this->assertEquals('foofoo', $translator->trans('foo'));

        $translator->addResource('array', array('bar' => 'foobar'), 'en');
        $this->assertEquals('foobar', $translator->trans('bar'));
    }

    /**
     * @dataProvider      getTransFileTests
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testTransWithoutFallbackLocaleFile($format, $loader)
    {
        $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader;
        $translator = new Translator('en');
        $translator->addLoader($format, new $loaderClass());
        $translator->addResource($format, __DIR__.'/fixtures/non-existing', 'en');
        $translator->addResource($format, __DIR__.'/fixtures/resources.'.$format, 'en');

        // force catalogue loading
        $translator->trans('foo');
    }

    /**
     * @dataProvider getTransFileTests
     */
    public function testTransWithFallbackLocaleFile($format, $loader)
    {
        $loaderClass = 'Symfony\\Component\\Translation\\Loader\\'.$loader;
        $translator = new Translator('en_GB');
        $translator->addLoader($format, new $loaderClass());
        $translator->addResource($format, __DIR__.'/fixtures/non-existing', 'en_GB');
        $translator->addResource($format, __DIR__.'/fixtures/resources.'.$format, 'en', 'resources');

        $this->assertEquals('bar', $translator->trans('foo', array(), 'resources'));
    }

    public function testTransWithFallbackLocaleBis()
    {
        $translator = new Translator('en_US');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foofoo'), 'en_US');
        $translator->addResource('array', array('bar' => 'foobar'), 'en');
        $this->assertEquals('foobar', $translator->trans('bar'));
    }

    public function testTransWithFallbackLocaleTer()
    {
        $translator = new Translator('fr_FR');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('foo' => 'foo (en_US)'), 'en_US');
        $translator->addResource('array', array('bar' => 'bar (en)'), 'en');

        $translator->setFallbackLocales(array('en_US', 'en'));

        $this->assertEquals('foo (en_US)', $translator->trans('foo'));
        $this->assertEquals('bar (en)', $translator->trans('bar'));
    }

    public function testTransNonExistentWithFallback()
    {
        $translator = new Translator('fr');
        $translator->setFallbackLocales(array('en'));
        $translator->addLoader('array', new ArrayLoader());
        $this->assertEquals('non-existent', $translator->trans('non-existent'));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testWhenAResourceHasNoRegisteredLoader()
    {
        $translator = new Translator('en');
        $translator->addResource('array', array('foo' => 'foofoo'), 'en');

        $translator->trans('foo');
    }

    /**
     * @dataProvider getTransTests
     */
    public function testTrans($expected, $id, $translation, $parameters, $locale, $domain)
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array((string) $id => $translation), $locale, $domain);

        $this->assertEquals($expected, $translator->trans($id, $parameters, $domain, $locale));
    }

    /**
     * @dataProvider getFlattenedTransTests
     */
    public function testFlattenedTrans($expected, $messages, $id)
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', $messages, 'fr', '');

        $this->assertEquals($expected, $translator->trans($id, array(), '', 'fr'));
    }

    /**
     * @dataProvider getTransChoiceTests
     */
    public function testTransChoice($expected, $id, $translation, $number, $parameters, $locale, $domain)
    {
        $translator = new Translator('en');
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array((string) $id => $translation), $locale, $domain);

        $this->assertEquals($expected, $translator->transChoice($id, $number, $parameters, $domain, $locale));
    }

    public function getTransFileTests()
    {
        return array(
            array('csv', 'CsvFileLoader'),
            array('ini', 'IniFileLoader'),
            array('mo', 'MoFileLoader'),
            array('po', 'PoFileLoader'),
            array('php', 'PhpFileLoader'),
            array('ts', 'QtFileLoader'),
            array('xlf', 'XliffFileLoader'),
            array('yml', 'YamlFileLoader'),
            array('json', 'JsonFileLoader'),
        );
    }

    public function getTransTests()
    {
        return array(
            array('Symfony2 est super !', 'Symfony2 is great!', 'Symfony2 est super !', array(), 'fr', ''),
            array('Symfony2 est awesome !', 'Symfony2 is %what%!', 'Symfony2 est %what% !', array('%what%' => 'awesome'), 'fr', ''),
            array('Symfony2 est super !', new String('Symfony2 is great!'), 'Symfony2 est super !', array(), 'fr', ''),
        );
    }

    public function getFlattenedTransTests()
    {
        $messages = array(
            'symfony2' => array(
                'is' => array(
                    'great' => 'Symfony2 est super!'
                )
            ),
            'foo' => array(
                'bar' => array(
                    'baz' => 'Foo Bar Baz'
                ),
                'baz' => 'Foo Baz',
            ),
        );

        return array(
            array('Symfony2 est super!', $messages, 'symfony2.is.great'),
            array('Foo Bar Baz', $messages, 'foo.bar.baz'),
            array('Foo Baz', $messages, 'foo.baz'),
        );
    }

    public function getTransChoiceTests()
    {
        return array(
            array('Il y a 0 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, array('%count%' => 0), 'fr', ''),
            array('Il y a 1 pomme', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 1, array('%count%' => 1), 'fr', ''),
            array('Il y a 10 pommes', '{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples', '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 10, array('%count%' => 10), 'fr', ''),

            array('Il y a 0 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 0, array('%count%' => 0), 'fr', ''),
            array('Il y a 1 pomme', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 1, array('%count%' => 1), 'fr', ''),
            array('Il y a 10 pommes', 'There is one apple|There is %count% apples', 'Il y a %count% pomme|Il y a %count% pommes', 10, array('%count%' => 10), 'fr', ''),

            array('Il y a 0 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 0, array('%count%' => 0), 'fr', ''),
            array('Il y a 1 pomme', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 1, array('%count%' => 1), 'fr', ''),
            array('Il y a 10 pommes', 'one: There is one apple|more: There is %count% apples', 'one: Il y a %count% pomme|more: Il y a %count% pommes', 10, array('%count%' => 10), 'fr', ''),

            array('Il n\'y a aucune pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 0, array('%count%' => 0), 'fr', ''),
            array('Il y a 1 pomme', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 1, array('%count%' => 1), 'fr', ''),
            array('Il y a 10 pommes', '{0} There are no apples|one: There is one apple|more: There is %count% apples', '{0} Il n\'y a aucune pomme|one: Il y a %count% pomme|more: Il y a %count% pommes', 10, array('%count%' => 10), 'fr', ''),

            array('Il y a 0 pomme', new String('{0} There are no appless|{1} There is one apple|]1,Inf] There is %count% apples'), '[0,1] Il y a %count% pomme|]1,Inf] Il y a %count% pommes', 0, array('%count%' => 0), 'fr', ''),
        );
    }

    public function testTransChoiceFallback()
    {
        $translator = new Translator('ru');
        $translator->setFallbackLocales(array('en'));
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('some_message2' => 'one thing|%count% things'), 'en');

        $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, array('%count%' => 10)));
    }

    public function testTransChoiceFallbackBis()
    {
        $translator = new Translator('ru');
        $translator->setFallbackLocales(array('en_US', 'en'));
        $translator->addLoader('array', new ArrayLoader());
        $translator->addResource('array', array('some_message2' => 'one thing|%count% things'), 'en_US');

        $this->assertEquals('10 things', $translator->transChoice('some_message2', 10, array('%count%' => 10)));
    }

    public function testTransChoiceFallbackWithNoTranslation()
    {
        $translator = new Translator('ru');
        $translator->setFallbackLocales(array('en'));
        $translator->addLoader('array', new ArrayLoader());

        // consistent behavior with Translator::trans(), which returns the string
        // unchanged if it can't be found
        $this->assertEquals('some_message2', $translator->transChoice('some_message2', 10, array('%count%' => 10)));
    }
}

class String
{
    protected $str;

    public function __construct($str)
    {
        $this->str = $str;
    }

    public function __toString()
    {
        return $this->str;
    }
}
PK$1[l.!���JTranslation/Symfony/Component/Translation/Tests/PluralizationRulesTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\PluralizationRules;

/**
 * Test should cover all languages mentioned on http://translate.sourceforge.net/wiki/l10n/pluralforms
 * and Plural forms mentioned on http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms
 *
 * See also https://developer.mozilla.org/en/Localization_and_Plurals which mentions 15 rules having a maximum of 6 forms.
 * The mozilla code is also interesting to check for.
 *
 * As mentioned by chx http://drupal.org/node/1273968 we can cover all by testing number from 0 to 199
 *
 * The goal to cover all languages is to far fetched so this test case is smaller.
 *
 * @author Clemens Tolboom clemens@build2be.nl
 */
class PluralizationRulesTest  extends \PHPUnit_Framework_TestCase
{

    /**
     * We test failed langcode here.
     *
     * TODO: The languages mentioned in the data provide need to get fixed somehow within PluralizationRules.
     *
     * @dataProvider failingLangcodes
     */
    public function testFailedLangcodes($nplural, $langCodes)
    {
        $matrix = $this->generateTestData($nplural, $langCodes);
        $this->validateMatrix($nplural, $matrix, false);
    }

    /**
     * @dataProvider successLangcodes
     */
    public function testLangcodes($nplural, $langCodes)
    {
        $matrix = $this->generateTestData($nplural, $langCodes);
        $this->validateMatrix($nplural, $matrix);
    }

    /**
     * This array should contain all currently known langcodes.
     *
     * As it is impossible to have this ever complete we should try as hard as possible to have it almost complete.
     *
     * @return type
     */
    public function successLangcodes()
    {
      return array(
        array('1' , array('ay','bo', 'cgg','dz','id', 'ja', 'jbo', 'ka','kk','km','ko','ky')),
        array('2' , array('nl', 'fr', 'en', 'de', 'de_GE')),
        array('3' , array('be','bs','cs','hr')),
        array('4' , array('cy','mt', 'sl')),
        array('5' , array()),
        array('6' , array('ar')),
      );
    }

    /**
     * This array should be at least empty within the near future.
     *
     * This both depends on a complete list trying to add above as understanding
     * the plural rules of the current failing languages.
     *
     * @return array with nplural together with langcodes
     */
    public function failingLangcodes()
    {
      return array(
        array('1' , array('fa')),
        array('2' , array('jbo')),
        array('3' , array('cbs')),
        array('4' , array('gd','kw')),
        array('5' , array('ga')),
        array('6' , array()),
      );
    }

    /**
     * We validate only on the plural coverage. Thus the real rules is not tested.
     *
     * @param string  $nplural       plural expected
     * @param array   $matrix        containing langcodes and their plural index values.
     * @param boolean $expectSuccess
     */
    protected function validateMatrix($nplural, $matrix, $expectSuccess = true)
    {
        foreach ($matrix as $langCode => $data) {
            $indexes = array_flip($data);
            if ($expectSuccess) {
                $this->assertEquals($nplural, count($indexes), "Langcode '$langCode' has '$nplural' plural forms.");
            } else {
                $this->assertNotEquals((int) $nplural, count($indexes), "Langcode '$langCode' has '$nplural' plural forms.");
            }
        }
    }

    protected function generateTestData($plural, $langCodes)
    {
        $matrix = array();
        foreach ($langCodes as $langCode) {
            for ($count=0; $count<200; $count++) {
                $plural = PluralizationRules::get($count, $langCode);
                $matrix[$langCode][$count] = $plural;
            }
        }

        return $matrix;
    }
}
PK$1[�h�l��OTranslation/Symfony/Component/Translation/Tests/Catalogue/DiffOperationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Catalogue;

use Symfony\Component\Translation\Catalogue\DiffOperation;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\MessageCatalogueInterface;

class DiffOperationTest extends AbstractOperationTest
{
    public function testGetMessagesFromSingleDomain()
    {
        $operation = $this->createOperation(
            new MessageCatalogue('en', array('messages' => array('a' => 'old_a', 'b' => 'old_b'))),
            new MessageCatalogue('en', array('messages' => array('a' => 'new_a', 'c' => 'new_c')))
        );

        $this->assertEquals(
            array('a' => 'old_a', 'c' => 'new_c'),
            $operation->getMessages('messages')
        );

        $this->assertEquals(
            array('c' => 'new_c'),
            $operation->getNewMessages('messages')
        );

        $this->assertEquals(
            array('b' => 'old_b'),
            $operation->getObsoleteMessages('messages')
        );
    }

    public function testGetResultFromSingleDomain()
    {
        $this->assertEquals(
            new MessageCatalogue('en', array(
                'messages' => array('a' => 'old_a', 'c' => 'new_c')
            )),
            $this->createOperation(
                new MessageCatalogue('en', array('messages' => array('a' => 'old_a', 'b' => 'old_b'))),
                new MessageCatalogue('en', array('messages' => array('a' => 'new_a', 'c' => 'new_c')))
            )->getResult()
        );
    }

    protected function createOperation(MessageCatalogueInterface $source, MessageCatalogueInterface $target)
    {
        return new DiffOperation($source, $target);
    }
}
PK$1[$͒ϛ�PTranslation/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Catalogue;

use Symfony\Component\Translation\Catalogue\MergeOperation;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\MessageCatalogueInterface;

class MergeOperationTest extends AbstractOperationTest
{
    public function testGetMessagesFromSingleDomain()
    {
        $operation = $this->createOperation(
            new MessageCatalogue('en', array('messages' => array('a' => 'old_a', 'b' => 'old_b'))),
            new MessageCatalogue('en', array('messages' => array('a' => 'new_a', 'c' => 'new_c')))
        );

        $this->assertEquals(
            array('a' => 'old_a', 'b' => 'old_b', 'c' => 'new_c'),
            $operation->getMessages('messages')
        );

        $this->assertEquals(
            array('c' => 'new_c'),
            $operation->getNewMessages('messages')
        );

        $this->assertEquals(
            array(),
            $operation->getObsoleteMessages('messages')
        );
    }

    public function testGetResultFromSingleDomain()
    {
        $this->assertEquals(
            new MessageCatalogue('en', array(
                'messages' => array('a' => 'old_a', 'b' => 'old_b', 'c' => 'new_c')
            )),
            $this->createOperation(
                new MessageCatalogue('en', array('messages' => array('a' => 'old_a', 'b' => 'old_b'))),
                new MessageCatalogue('en', array('messages' => array('a' => 'new_a', 'c' => 'new_c')))
            )->getResult()
        );
    }

    protected function createOperation(MessageCatalogueInterface $source, MessageCatalogueInterface $target)
    {
        return new MergeOperation($source, $target);
    }
}
PK$1[ײ�))STranslation/Symfony/Component/Translation/Tests/Catalogue/AbstractOperationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Catalogue;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\MessageCatalogueInterface;

abstract class AbstractOperationTest extends \PHPUnit_Framework_TestCase
{
    public function testGetEmptyDomains()
    {
        $this->assertEquals(
            array(),
            $this->createOperation(
                new MessageCatalogue('en'),
                new MessageCatalogue('en')
            )->getDomains()
        );
    }

    public function testGetMergedDomains()
    {
        $this->assertEquals(
            array('a', 'b', 'c'),
            $this->createOperation(
                new MessageCatalogue('en', array('a' => array(), 'b' => array())),
                new MessageCatalogue('en', array('b' => array(), 'c' => array()))
            )->getDomains()
        );
    }

    public function testGetMessagesFromUnknownDomain()
    {
        $this->setExpectedException('InvalidArgumentException');
        $this->createOperation(
            new MessageCatalogue('en'),
            new MessageCatalogue('en')
        )->getMessages('domain');
    }

    public function testGetEmptyMessages()
    {
        $this->assertEquals(
            array(),
            $this->createOperation(
                new MessageCatalogue('en', array('a' => array())),
                new MessageCatalogue('en')
            )->getMessages('a')
        );
    }

    public function testGetEmptyResult()
    {
        $this->assertEquals(
            new MessageCatalogue('en'),
            $this->createOperation(
                new MessageCatalogue('en'),
                new MessageCatalogue('en')
            )->getResult()
        );
    }

    abstract protected function createOperation(MessageCatalogueInterface $source, MessageCatalogueInterface $target);
}
PK$1[0�2��@Translation/Symfony/Component/Translation/Tests/IntervalTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\Interval;

class IntervalTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTests
     */
    public function testTest($expected, $number, $interval)
    {
        $this->assertEquals($expected, Interval::test($number, $interval));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTestException()
    {
        Interval::test(1, 'foobar');
    }

    public function getTests()
    {
        return array(
            array(true, 3, '{1,2, 3 ,4}'),
            array(false, 10, '{1,2, 3 ,4}'),
            array(false, 3, '[1,2]'),
            array(true, 1, '[1,2]'),
            array(true, 2, '[1,2]'),
            array(false, 1, ']1,2['),
            array(false, 2, ']1,2['),
            array(true, log(0), '[-Inf,2['),
            array(true, -log(0), '[-2,+Inf]'),
        );
    }
}
PK$1[��V��LTranslation/Symfony/Component/Translation/Tests/Dumper/IniFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\IniFileDumper;

class IniFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new IniFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.ini'), file_get_contents($tempDir.'/messages.en.ini'));

        unlink($tempDir.'/messages.en.ini');
    }
}
PK$1[`��׹�NTranslation/Symfony/Component/Translation/Tests/Dumper/XliffFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\XliffFileDumper;

class XliffFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar', 'key' => ''));

        $tempDir = sys_get_temp_dir();
        $dumper = new XliffFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources-clean.xlf'), file_get_contents($tempDir.'/messages.en.xlf'));

        unlink($tempDir.'/messages.en.xlf');
    }
}
PK$1[����LTranslation/Symfony/Component/Translation/Tests/Dumper/PhpFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\PhpFileDumper;

class PhpFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new PhpFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.php'), file_get_contents($tempDir.'/messages.en.php'));

        unlink($tempDir.'/messages.en.php');
    }
}
PK$1[����MTranslation/Symfony/Component/Translation/Tests/Dumper/YamlFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\YamlFileDumper;

class YamlFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new YamlFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.yml'), file_get_contents($tempDir.'/messages.en.yml'));

        unlink($tempDir.'/messages.en.yml');
    }
}
PK$1[ub/��OTranslation/Symfony/Component/Translation/Tests/Dumper/IcuResFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\IcuResFileDumper;

class IcuResFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('This test requires mbstring to work.');
        }

        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir() . '/IcuResFileDumperTest';
        mkdir($tempDir);
        $dumper = new IcuResFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resourcebundle/res/en.res'), file_get_contents($tempDir.'/messages/en.res'));

        unlink($tempDir.'/messages/en.res');
        rmdir($tempDir.'/messages');
        rmdir($tempDir);
    }
}
PK$1[�����LTranslation/Symfony/Component/Translation/Tests/Dumper/CsvFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\CsvFileDumper;

class CsvFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar', 'bar' => 'foo
foo', 'foo;foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new CsvFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/valid.csv'), file_get_contents($tempDir.'/messages.en.csv'));

        unlink($tempDir.'/messages.en.csv');
    }
}
PK%1[�����KTranslation/Symfony/Component/Translation/Tests/Dumper/MoFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\MoFileDumper;

class MoFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new MoFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));
        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.mo'), file_get_contents($tempDir.'/messages.en.mo'));

        unlink($tempDir.'/messages.en.mo');
    }
}
PK%1[�BY���KTranslation/Symfony/Component/Translation/Tests/Dumper/QtFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\QtFileDumper;

class QtFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'), 'resources');

        $tempDir = sys_get_temp_dir();
        $dumper = new QtFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.ts'), file_get_contents($tempDir.'/resources.en.ts'));

        unlink($tempDir.'/resources.en.ts');
    }
}
PK%1[��IIMTranslation/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\JsonFileDumper;

class JsonFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            $this->markTestIncomplete('PHP below 5.4 doesn\'t support JSON pretty printing');
        }

        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new JsonFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));

        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.json'), file_get_contents($tempDir.'/messages.en.json'));

        unlink($tempDir.'/messages.en.json');
    }
}
PK%1[&��ݙ�KTranslation/Symfony/Component/Translation/Tests/Dumper/PoFileDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Dumper\PoFileDumper;

class PoFileDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDump()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->add(array('foo' => 'bar'));

        $tempDir = sys_get_temp_dir();
        $dumper = new PoFileDumper();
        $dumper->dump($catalogue, array('path' => $tempDir));
        $this->assertEquals(file_get_contents(__DIR__.'/../fixtures/resources.po'), file_get_contents($tempDir.'/messages.en.po'));

        unlink($tempDir.'/messages.en.po');
    }
}
PK%1[8^�k��NTranslation/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class XliffFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new XliffFileLoader();
        $resource = __DIR__.'/../fixtures/resources.xlf';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadWithResname()
    {
        $loader = new XliffFileLoader();
        $catalogue = $loader->load(__DIR__.'/../fixtures/resname.xlf', 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar', 'bar' => 'baz', 'baz' => 'foo'), $catalogue->all('domain1'));
    }

    public function testIncompleteResource()
    {
        $loader = new XliffFileLoader();
        $catalogue = $loader->load(__DIR__.'/../fixtures/resources.xlf', 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar', 'key' => '', 'test' => 'with'), $catalogue->all('domain1'));
        $this->assertFalse($catalogue->has('extra', 'domain1'));
    }

    public function testEncoding()
    {
        if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) {
            $this->markTestSkipped('The iconv and mbstring extensions are not available.');
        }

        $loader = new XliffFileLoader();
        $catalogue = $loader->load(__DIR__.'/../fixtures/encoding.xlf', 'en', 'domain1');

        $this->assertEquals(utf8_decode('föö'), $catalogue->get('bar', 'domain1'));
        $this->assertEquals(utf8_decode('bär'), $catalogue->get('foo', 'domain1'));
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new XliffFileLoader();
        $loader->load(__DIR__.'/../fixtures/resources.php', 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadResourceDoesNotValidate()
    {
        $loader = new XliffFileLoader();
        $loader->load(__DIR__.'/../fixtures/non-valid.xlf', 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new XliffFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.xlf';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfFileNotLocal()
    {
        $loader = new XliffFileLoader();
        $resource = 'http://example.com/resources.xlf';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException        \Symfony\Component\Translation\Exception\InvalidResourceException
     * @expectedExceptionMessage Document types are not allowed.
     */
    public function testDocTypeIsNotAllowed()
    {
        $loader = new XliffFileLoader();
        $loader->load(__DIR__.'/../fixtures/withdoctype.xlf', 'en', 'domain1');
    }

    public function testParseEmptyFile()
    {
        $loader = new XliffFileLoader();
        $resource = __DIR__.'/../fixtures/empty.xlf';
        $this->setExpectedException('Symfony\Component\Translation\Exception\InvalidResourceException', sprintf('Unable to load "%s":', $resource));
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[��|=��KTranslation/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\QtFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class QtFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new QtFileLoader();
        $resource = __DIR__.'/../fixtures/resources.ts';
        $catalogue = $loader->load($resource, 'en', 'resources');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('resources'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new QtFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.ts';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadNonLocalResource()
    {
        $loader = new QtFileLoader();
        $resource = 'http://domain1.com/resources.ts';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new QtFileLoader();
        $resource = __DIR__.'/../fixtures/invalid-xml-resources.xlf';
        $loader->load($resource, 'en', 'domain1');
    }

    public function testLoadEmptyResource()
    {
        $loader = new QtFileLoader();
        $resource = __DIR__.'/../fixtures/empty.xlf';
        $this->setExpectedException('Symfony\Component\Translation\Exception\InvalidResourceException', sprintf('Unable to load "%s".', $resource));
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[���3LTranslation/Symfony/Component/Translation/Tests/Loader/LocalizedTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

abstract class LocalizedTestCase extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('The "intl" extension is not available');
        }
    }
}
PK%1[���LTranslation/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\PhpFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new PhpFileLoader();
        $resource = __DIR__.'/../fixtures/resources.php';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new PhpFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.php';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfFileNotLocal()
    {
        $loader = new PhpFileLoader();
        $resource = 'http://example.com/resources.php';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[~�		MTranslation/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__.'/../fixtures/resources.yml';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__.'/../fixtures/empty.yml';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.yml';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfFileNotLocal()
    {
        $loader = new YamlFileLoader();
        $resource = 'http://example.com/resources.yml';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadThrowsAnExceptionIfNotAnArray()
    {
        $loader = new YamlFileLoader();
        $resource = __DIR__.'/../fixtures/non-valid.yml';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[�$X

KTranslation/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\PoFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class PoFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new PoFileLoader();
        $resource = __DIR__.'/../fixtures/resources.po';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadPlurals()
    {
        $loader = new PoFileLoader();
        $resource = __DIR__.'/../fixtures/plurals.po';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar', 'foos' => 'bar|bars'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new PoFileLoader();
        $resource = __DIR__.'/../fixtures/empty.po';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new PoFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.po';
        $loader->load($resource, 'en', 'domain1');
    }

    public function testLoadEmptyTranslation()
    {
        $loader = new PoFileLoader();
        $resource = __DIR__.'/../fixtures/empty-translation.po';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => ''), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }
}
PK%1[[����LTranslation/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\CsvFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class CsvFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new CsvFileLoader();
        $resource = __DIR__.'/../fixtures/resources.csv';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new CsvFileLoader();
        $resource = __DIR__.'/../fixtures/empty.csv';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new CsvFileLoader();
        $resource = __DIR__.'/../fixtures/not-exists.csv';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadNonLocalResource()
    {
        $loader = new CsvFileLoader();
        $resource = 'http://example.com/resources.csv';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[/�݂�LTranslation/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\IniFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class IniFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new IniFileLoader();
        $resource = __DIR__.'/../fixtures/resources.ini';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new IniFileLoader();
        $resource = __DIR__.'/../fixtures/empty.ini';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new IniFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.ini';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[��j��OTranslation/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\IcuResFileLoader;
use Symfony\Component\Config\Resource\DirectoryResource;

class IcuResFileLoaderTest extends LocalizedTestCase
{
    protected function setUp()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('This test requires intl extension to work.');
        }
    }

    public function testLoad()
    {
        // resource is build using genrb command
        $loader = new IcuResFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/res';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new DirectoryResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new IcuResFileLoader();
        $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new IcuResFileLoader();
        $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted', 'en', 'domain1');
    }
}
PK%1[P�e��MTranslation/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\JsonFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class JsonFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!class_exists('Symfony\Component\Config\Loader\Loader')) {
            $this->markTestSkipped('The "Config" component is not available');
        }
    }

    public function testLoad()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/resources.json';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/empty.json';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array(), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.json';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException           \Symfony\Component\Translation\Exception\InvalidResourceException
     * @expectedExceptionMessage    Error parsing JSON - Syntax error, malformed JSON
     */
    public function testParseException()
    {
        $loader = new JsonFileLoader();
        $resource = __DIR__.'/../fixtures/malformed.json';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[����KTranslation/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\MoFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class MoFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoad()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/resources.mo';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    public function testLoadPlurals()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/plurals.mo';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('foo' => 'bar', 'foos' => '{0} bar|{1} bars'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/non-existing.mo';
        $loader->load($resource, 'en', 'domain1');
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new MoFileLoader();
        $resource = __DIR__.'/../fixtures/empty.mo';
        $loader->load($resource, 'en', 'domain1');
    }
}
PK%1[�)�	�	�	OTranslation/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests\Loader;

use Symfony\Component\Translation\Loader\IcuDatFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class IcuDatFileLoaderTest extends LocalizedTestCase
{
    protected function setUp()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('This test requires intl extension to work.');
        }
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
     */
    public function testLoadInvalidResource()
    {
        $loader = new IcuDatFileLoader();
        $loader->load(__DIR__.'/../fixtures/resourcebundle/corrupted/resources', 'es', 'domain2');
    }

    public function testDatEnglishLoad()
    {
        // bundled resource is build using pkgdata command which at least in ICU 4.2 comes in extremely! buggy form
        // you must specify an temporary build directory which is not the same as current directory and
        // MUST reside on the same partition. pkgdata -p resources -T /srv -d.packagelist.txt
        $loader = new IcuDatFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/dat/resources';
        $catalogue = $loader->load($resource, 'en', 'domain1');

        $this->assertEquals(array('symfony' => 'Symfony 2 is great'), $catalogue->all('domain1'));
        $this->assertEquals('en', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource.'.dat')), $catalogue->getResources());
    }

    public function testDatFrenchLoad()
    {
        $loader = new IcuDatFileLoader();
        $resource = __DIR__.'/../fixtures/resourcebundle/dat/resources';
        $catalogue = $loader->load($resource, 'fr', 'domain1');

        $this->assertEquals(array('symfony' => 'Symfony 2 est génial'), $catalogue->all('domain1'));
        $this->assertEquals('fr', $catalogue->getLocale());
        $this->assertEquals(array(new FileResource($resource.'.dat')), $catalogue->getResources());
    }

    /**
     * @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
     */
    public function testLoadNonExistingResource()
    {
        $loader = new IcuDatFileLoader();
        $loader->load(__DIR__.'/../fixtures/non-existing.txt', 'en', 'domain1');
    }
}
PK%1[M��HTranslation/Symfony/Component/Translation/Tests/MessageCatalogueTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\MessageCatalogue;

class MessageCatalogueTest extends \PHPUnit_Framework_TestCase
{
    public function testGetLocale()
    {
        $catalogue = new MessageCatalogue('en');

        $this->assertEquals('en', $catalogue->getLocale());
    }

    public function testGetDomains()
    {
        $catalogue = new MessageCatalogue('en', array('domain1' => array(), 'domain2' => array()));

        $this->assertEquals(array('domain1', 'domain2'), $catalogue->getDomains());
    }

    public function testAll()
    {
        $catalogue = new MessageCatalogue('en', $messages = array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));

        $this->assertEquals(array('foo' => 'foo'), $catalogue->all('domain1'));
        $this->assertEquals(array(), $catalogue->all('domain88'));
        $this->assertEquals($messages, $catalogue->all());
    }

    public function testHas()
    {
        $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));

        $this->assertTrue($catalogue->has('foo', 'domain1'));
        $this->assertFalse($catalogue->has('bar', 'domain1'));
        $this->assertFalse($catalogue->has('foo', 'domain88'));
    }

    public function testGetSet()
    {
        $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));
        $catalogue->set('foo1', 'foo1', 'domain1');

        $this->assertEquals('foo', $catalogue->get('foo', 'domain1'));
        $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1'));
    }

    public function testAdd()
    {
        $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));
        $catalogue->add(array('foo1' => 'foo1'), 'domain1');

        $this->assertEquals('foo', $catalogue->get('foo', 'domain1'));
        $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1'));

        $catalogue->add(array('foo' => 'bar'), 'domain1');
        $this->assertEquals('bar', $catalogue->get('foo', 'domain1'));
        $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1'));

        $catalogue->add(array('foo' => 'bar'), 'domain88');
        $this->assertEquals('bar', $catalogue->get('foo', 'domain88'));
    }

    public function testReplace()
    {
        $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));
        $catalogue->replace($messages = array('foo1' => 'foo1'), 'domain1');

        $this->assertEquals($messages, $catalogue->all('domain1'));
    }

    public function testAddCatalogue()
    {
        $r = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r->expects($this->any())->method('__toString')->will($this->returnValue('r'));

        $r1 = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r1->expects($this->any())->method('__toString')->will($this->returnValue('r1'));

        $catalogue = new MessageCatalogue('en', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));
        $catalogue->addResource($r);

        $catalogue1 = new MessageCatalogue('en', array('domain1' => array('foo1' => 'foo1')));
        $catalogue1->addResource($r1);

        $catalogue->addCatalogue($catalogue1);

        $this->assertEquals('foo', $catalogue->get('foo', 'domain1'));
        $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1'));

        $this->assertEquals(array($r, $r1), $catalogue->getResources());
    }

    public function testAddFallbackCatalogue()
    {
        $r = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r->expects($this->any())->method('__toString')->will($this->returnValue('r'));

        $r1 = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r1->expects($this->any())->method('__toString')->will($this->returnValue('r1'));

        $catalogue = new MessageCatalogue('en_US', array('domain1' => array('foo' => 'foo'), 'domain2' => array('bar' => 'bar')));
        $catalogue->addResource($r);

        $catalogue1 = new MessageCatalogue('en', array('domain1' => array('foo' => 'bar', 'foo1' => 'foo1')));
        $catalogue1->addResource($r1);

        $catalogue->addFallbackCatalogue($catalogue1);

        $this->assertEquals('foo', $catalogue->get('foo', 'domain1'));
        $this->assertEquals('foo1', $catalogue->get('foo1', 'domain1'));

        $this->assertEquals(array($r, $r1), $catalogue->getResources());
    }

    /**
     * @expectedException \LogicException
     */
    public function testAddFallbackCatalogueWithCircularReference()
    {
        $main = new MessageCatalogue('en_US');
        $fallback = new MessageCatalogue('fr_FR');

        $fallback->addFallbackCatalogue($main);
        $main->addFallbackCatalogue($fallback);
    }

    /**
     * @expectedException \LogicException
     */
    public function testAddCatalogueWhenLocaleIsNotTheSameAsTheCurrentOne()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->addCatalogue(new MessageCatalogue('fr', array()));
    }

    public function testGetAddResource()
    {
        $catalogue = new MessageCatalogue('en');
        $r = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r->expects($this->any())->method('__toString')->will($this->returnValue('r'));
        $catalogue->addResource($r);
        $catalogue->addResource($r);
        $r1 = $this->getMock('Symfony\Component\Config\Resource\ResourceInterface');
        $r1->expects($this->any())->method('__toString')->will($this->returnValue('r1'));
        $catalogue->addResource($r1);

        $this->assertEquals(array($r, $r1), $catalogue->getResources());
    }

    public function testMetadataDelete()
    {
        $catalogue = new MessageCatalogue('en');
        $this->assertEquals(array(), $catalogue->getMetadata('', ''), 'Metadata is empty');
        $catalogue->deleteMetadata('key', 'messages');
        $catalogue->deleteMetadata('', 'messages');
        $catalogue->deleteMetadata();
    }

    public function testMetadataSetGetDelete()
    {
        $catalogue = new MessageCatalogue('en');
        $catalogue->setMetadata('key', 'value');
        $this->assertEquals('value', $catalogue->getMetadata('key', 'messages'), "Metadata 'key' = 'value'");

        $catalogue->setMetadata('key2', array());
        $this->assertEquals(array(), $catalogue->getMetadata('key2', 'messages'), 'Metadata key2 is array');

        $catalogue->deleteMetadata('key2', 'messages');
        $this->assertEquals(null, $catalogue->getMetadata('key2', 'messages'), 'Metadata key2 should is deleted.');

        $catalogue->deleteMetadata('key2', 'domain');
        $this->assertEquals(null, $catalogue->getMetadata('key2', 'domain'), 'Metadata key2 should is deleted.');
    }

    public function testMetadataMerge()
    {
        $cat1 = new MessageCatalogue('en');
        $cat1->setMetadata('a', 'b');
        $this->assertEquals(array('messages' => array('a' => 'b')), $cat1->getMetadata('', ''), 'Cat1 contains messages metadata.');

        $cat2 = new MessageCatalogue('en');
        $cat2->setMetadata('b', 'c', 'domain');
        $this->assertEquals(array('domain' => array('b' => 'c')), $cat2->getMetadata('', ''), 'Cat2 contains domain metadata.');

        $cat1->addCatalogue($cat2);
        $this->assertEquals(array('messages' => array('a' => 'b'), 'domain' => array('b' => 'c')), $cat1->getMetadata('', ''), 'Cat1 contains merged metadata.');
    }
}
PK%1[���  GTranslation/Symfony/Component/Translation/Tests/MessageSelectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Translation\Tests;

use Symfony\Component\Translation\MessageSelector;

class MessageSelectorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getChooseTests
     */
    public function testChoose($expected, $id, $number)
    {
        $selector = new MessageSelector();

        $this->assertEquals($expected, $selector->choose($id, $number, 'en'));
    }

    public function testReturnMessageIfExactlyOneStandardRuleIsGiven()
    {
        $selector = new MessageSelector();

        $this->assertEquals('There are two apples', $selector->choose('There are two apples', 2, 'en'));
    }

    /**
     * @dataProvider getNonMatchingMessages
     * @expectedException \InvalidArgumentException
     */
    public function testThrowExceptionIfMatchingMessageCannotBeFound($id, $number)
    {
        $selector = new MessageSelector();

        $selector->choose($id, $number, 'en');
    }

    public function getNonMatchingMessages()
    {
        return array(
            array('{0} There are no apples|{1} There is one apple', 2),
            array('{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('{1} There is one apple|]2,Inf] There are %count% apples', 2),
            array('{0} There are no apples|There is one apple', 2),
        );
    }

    public function getChooseTests()
    {
        return array(
            array('There are no apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('There are no apples', '{0}     There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('There are no apples', '{0}There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 0),

            array('There is one apple', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 1),

            array('There are %count% apples', '{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples', 10),
            array('There are %count% apples', '{0} There are no apples|{1} There is one apple|]1,Inf]There are %count% apples', 10),
            array('There are %count% apples', '{0} There are no apples|{1} There is one apple|]1,Inf]     There are %count% apples', 10),

            array('There are %count% apples', 'There is one apple|There are %count% apples', 0),
            array('There is one apple', 'There is one apple|There are %count% apples', 1),
            array('There are %count% apples', 'There is one apple|There are %count% apples', 10),

            array('There are %count% apples', 'one: There is one apple|more: There are %count% apples', 0),
            array('There is one apple', 'one: There is one apple|more: There are %count% apples', 1),
            array('There are %count% apples', 'one: There is one apple|more: There are %count% apples', 10),

            array('There are no apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 0),
            array('There is one apple', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 1),
            array('There are %count% apples', '{0} There are no apples|one: There is one apple|more: There are %count% apples', 10),

            array('', '{0}|{1} There is one apple|]1,Inf] There are %count% apples', 0),
            array('', '{0} There are no apples|{1}|]1,Inf] There are %count% apples', 1),

            // Indexed only tests which are Gettext PoFile* compatible strings.
            array('There are %count% apples', 'There is one apple|There are %count% apples', 0),
            array('There is one apple', 'There is one apple|There are %count% apples', 1),
            array('There are %count% apples', 'There is one apple|There are %count% apples', 2),

            // Tests for float numbers
            array('There is almost one apple', '{0} There are no apples|]0,1[ There is almost one apple|{1} There is one apple|[1,Inf] There is more than one apple', 0.7),
            array('There is one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1),
            array('There is more than one apple', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 1.7),
            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
            array('There are no apples', '{0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0.0),
            array('There are no apples', '{0.0} There are no apples|]0,1[There are %count% apples|{1} There is one apple|[1,Inf] There is more than one apple', 0),
        );
    }
}
PK%1[��W44ETranslation/Symfony/Component/Translation/Tests/fixtures/resources.monu�[�����$,-1foobarPK%1[!f����ETranslation/Symfony/Component/Translation/Tests/fixtures/resources.ponu�[���msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: en\n"

msgid "foo"
msgstr "bar"PK%1[=BsMTranslation/Symfony/Component/Translation/Tests/fixtures/empty-translation.ponu�[���msgid "foo"
msgstr ""

PK%1[BTranslation/Symfony/Component/Translation/Tests/fixtures/empty.ininu�[���PK%1[YڸCLTranslation/Symfony/Component/Translation/Tests/fixtures/resources-clean.xlfnu�[���<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file source-language="en" datatype="plaintext" original="file.ext">
    <body>
      <trans-unit id="acbd18db4cc2f85cedef654fccc4a4d8" resname="foo">
        <source>foo</source>
        <target>bar</target>
      </trans-unit>
      <trans-unit id="3c6e0b8a9c15224a8228b9a98ca1531d" resname="key">
        <source>key</source>
        <target></target>
      </trans-unit>
    </body>
  </file>
</xliff>
PK%1[�:�++FTranslation/Symfony/Component/Translation/Tests/fixtures/resources.phpnu�[���<?php

return array (
  'foo' => 'bar',
);
PK%1[BTranslation/Symfony/Component/Translation/Tests/fixtures/empty.ymlnu�[���PK%1[CTranslation/Symfony/Component/Translation/Tests/fixtures/empty.jsonnu�[���PK%1[Y���44DTranslation/Symfony/Component/Translation/Tests/fixtures/resname.xlfnu�[���<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file source-language="en" datatype="plaintext" original="file.ext">
    <body>
      <trans-unit id="1" resname="foo">
        <source></source>
        <target>bar</target>
      </trans-unit>
      <trans-unit id="2" resname="bar">
        <source>bar source</source>
        <target>baz</target>
      </trans-unit>
      <trans-unit id="3">
        <source>baz</source>
        <target>foo</target>
      </trans-unit>
    </body>
  </file>
</xliff>
PK%1[BTranslation/Symfony/Component/Translation/Tests/fixtures/empty.xlfnu�[���PK%1[;.�BBCTranslation/Symfony/Component/Translation/Tests/fixtures/plurals.ponu�[���msgid "foo"
msgid_plural "foos"
msgstr[0] "bar"
msgstr[1] "bars"

PK%1[�ߞGTranslation/Symfony/Component/Translation/Tests/fixtures/malformed.jsonnu�[���{
    "foo": "bar" "
}PK%1[�.�zzFTranslation/Symfony/Component/Translation/Tests/fixtures/resources.xlfnu�[���<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file source-language="en" datatype="plaintext" original="file.ext">
    <body>
      <trans-unit id="1">
        <source>foo</source>
        <target>bar</target>
      </trans-unit>
      <trans-unit id="2">
        <source>extra</source>
      </trans-unit>
      <trans-unit id="3">
        <source>key</source>
        <target></target>
      </trans-unit>
      <trans-unit id="4">
        <source>test</source>
        <target>with</target>
        <note>note</note>
      </trans-unit>
    </body>
  </file>
</xliff>
PK%1[�e2~FTranslation/Symfony/Component/Translation/Tests/fixtures/non-valid.ymlnu�[���foo
PK%1[�'�F

FTranslation/Symfony/Component/Translation/Tests/fixtures/resources.ininu�[���foo="bar"
PK%1[� TTFTranslation/Symfony/Component/Translation/Tests/fixtures/non-valid.xlfnu�[���<?xml version="1.0"?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit>
                <source>foo</source>
                <target>bar</target>
            </trans-unit>
        </body>
    </file>
</xliff>
PK%1[ATranslation/Symfony/Component/Translation/Tests/fixtures/empty.ponu�[���PK%1[BTranslation/Symfony/Component/Translation/Tests/fixtures/empty.csvnu�[���PK%1[*֔�JJCTranslation/Symfony/Component/Translation/Tests/fixtures/plurals.monu�[�����$,8AfoofoosbarbarsPK%1[+�L�TTRTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/res/en.resnu�[��� �'ResB 

foobarPK%1[w˦(||RTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/fr.resnu�[��� �'ResB 	symfonySymfony 2 est g�nial��	PK%1[X��**RTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/fr.txtnu�[���fr{
    symfony{"Symfony 2 est génial"}
}PK%1[rQ�``YTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/resources.datnu�[��� �'CmnD@%�resources/en.resresources/fr.res���������� �'ResB 	symfonySymfony 2 is great��	�������� �'ResB 	symfonySymfony 2 est g�nial��	����PK%1[�M�RxxRTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/en.resnu�[��� �'ResB 	symfonySymfony 2 is great��	PK&1[�g.�[Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/packagelist.txtnu�[���en.res
fr.res
PK&1[�25�''RTranslation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/en.txtnu�[���en{
    symfony{"Symfony 2 is great"}
}PK&1[��<�_Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/corrupted/resources.datnu�[���XXXPK&1[ATranslation/Symfony/Component/Translation/Tests/fixtures/empty.monu�[���PK&1[��jjHTranslation/Symfony/Component/Translation/Tests/fixtures/withdoctype.xlfnu�[���<?xml version="1.0"?>
<!DOCTYPE foo>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="1">
                <source>foo</source>
                <target>bar</target>
            </trans-unit>
        </body>
    </file>
</xliff>
PK&1[̉^2��ETranslation/Symfony/Component/Translation/Tests/fixtures/encoding.xlfnu�[���<?xml version="1.0" encoding="ISO-8859-1"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
  <file source-language="en" datatype="plaintext" original="file.ext">
    <body>
      <trans-unit id="1" resname="foo">
        <source>foo</source>
        <target>b�r</target>
      </trans-unit>
      <trans-unit id="2" resname="bar">
        <source>bar</source>
        <target>f��</target>
      </trans-unit>
    </body>
  </file>
</xliff>
PK&1[�B$$BTranslation/Symfony/Component/Translation/Tests/fixtures/valid.csvnu�[���foo;bar
bar;"foo
foo"
"foo;foo";bar
PK&1[����GTranslation/Symfony/Component/Translation/Tests/fixtures/resources.jsonnu�[���{
    "foo": "bar"
}PK&1[�C(���ETranslation/Symfony/Component/Translation/Tests/fixtures/resources.tsnu�[���<?xml version="1.0" encoding="utf-8"?>
<TS>
  <context>
    <name>resources</name>
    <message>
      <source>foo</source>
      <translation>bar</translation>
    </message>
  </context>
</TS>
PK&1[/�
��RTranslation/Symfony/Component/Translation/Tests/fixtures/invalid-xml-resources.xlfnu�[���<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
    <file source-language="en" datatype="plaintext" original="file.ext">
        <body>
            <trans-unit id="1">
                <source>foo</source>
                <target>bar
            </trans-unit>
            <trans-unit id="2">
                <source>extra</source>
            </trans-unit>
            <trans-unit id="3">
                <source>key</source>
                <target></target>
            </trans-unit>
            <trans-unit id="4">
                <source>test</source>
                <target>with</target>
                <note>note</note>
            </trans-unit>
        </body>
    </file>
</xliff>
PK&1[���		FTranslation/Symfony/Component/Translation/Tests/fixtures/resources.ymlnu�[���foo: bar
PK&1[�D��``FTranslation/Symfony/Component/Translation/Tests/fixtures/resources.csvnu�[���"foo"; "bar"
#"bar"; "foo"
"incorrect"; "number"; "columns"; "will"; "be"; "ignored"
"incorrect"PK&1[^C�	:::Translation/Symfony/Component/Translation/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Translation Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK&1[���LL@Routing/Symfony/Component/Routing/Tests/Annotation/RouteTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Annotation;

use Symfony\Component\Routing\Annotation\Route;

class RouteTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \BadMethodCallException
     */
    public function testInvalidRouteParameter()
    {
        $route = new Route(array('foo' => 'bar'));
    }

    /**
     * @dataProvider getValidParameters
     */
    public function testRouteParameters($parameter, $value, $getter)
    {
        $route = new Route(array($parameter => $value));
        $this->assertEquals($route->$getter(), $value);
    }

    public function getValidParameters()
    {
        return array(
            array('value', '/Blog', 'getPattern'),
            array('value', '/Blog', 'getPath'),
            array('requirements', array('_method' => 'GET'), 'getRequirements'),
            array('options', array('compiler_class' => 'RouteCompiler'), 'getOptions'),
            array('name', 'blog_index', 'getName'),
            array('defaults', array('_controller' => 'MyBlogBundle:Blog:index'), 'getDefaults'),
            array('schemes', array('https'), 'getSchemes'),
            array('methods', array('GET', 'POST'), 'getMethods'),
            array('host', array('{locale}.example.com'), 'getHost'),
            array('condition', array('context.getMethod() == "GET"'), 'getCondition'),
        );
    }
}
PK&1[�%��])])=Routing/Symfony/Component/Routing/Tests/RouteCompilerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\Routing\Route;

class RouteCompilerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideCompileData
     */
    public function testCompile($name, $arguments, $prefix, $regex, $variables, $tokens)
    {
        $r = new \ReflectionClass('Symfony\\Component\\Routing\\Route');
        $route = $r->newInstanceArgs($arguments);

        $compiled = $route->compile();
        $this->assertEquals($prefix, $compiled->getStaticPrefix(), $name.' (static prefix)');
        $this->assertEquals($regex, $compiled->getRegex(), $name.' (regex)');
        $this->assertEquals($variables, $compiled->getVariables(), $name.' (variables)');
        $this->assertEquals($tokens, $compiled->getTokens(), $name.' (tokens)');
    }

    public function provideCompileData()
    {
        return array(
            array(
                'Static route',
                array('/foo'),
                '/foo', '#^/foo$#s', array(), array(
                    array('text', '/foo'),
                )),

            array(
                'Route with a variable',
                array('/foo/{bar}'),
                '/foo', '#^/foo/(?P<bar>[^/]++)$#s', array('bar'), array(
                    array('variable', '/', '[^/]++', 'bar'),
                    array('text', '/foo'),
                )),

            array(
                'Route with a variable that has a default value',
                array('/foo/{bar}', array('bar' => 'bar')),
                '/foo', '#^/foo(?:/(?P<bar>[^/]++))?$#s', array('bar'), array(
                    array('variable', '/', '[^/]++', 'bar'),
                    array('text', '/foo'),
                )),

            array(
                'Route with several variables',
                array('/foo/{bar}/{foobar}'),
                '/foo', '#^/foo/(?P<bar>[^/]++)/(?P<foobar>[^/]++)$#s', array('bar', 'foobar'), array(
                    array('variable', '/', '[^/]++', 'foobar'),
                    array('variable', '/', '[^/]++', 'bar'),
                    array('text', '/foo'),
                )),

            array(
                'Route with several variables that have default values',
                array('/foo/{bar}/{foobar}', array('bar' => 'bar', 'foobar' => '')),
                '/foo', '#^/foo(?:/(?P<bar>[^/]++)(?:/(?P<foobar>[^/]++))?)?$#s', array('bar', 'foobar'), array(
                    array('variable', '/', '[^/]++', 'foobar'),
                    array('variable', '/', '[^/]++', 'bar'),
                    array('text', '/foo'),
                )),

            array(
                'Route with several variables but some of them have no default values',
                array('/foo/{bar}/{foobar}', array('bar' => 'bar')),
                '/foo', '#^/foo/(?P<bar>[^/]++)/(?P<foobar>[^/]++)$#s', array('bar', 'foobar'), array(
                    array('variable', '/', '[^/]++', 'foobar'),
                    array('variable', '/', '[^/]++', 'bar'),
                    array('text', '/foo'),
                )),

            array(
                'Route with an optional variable as the first segment',
                array('/{bar}', array('bar' => 'bar')),
                '', '#^/(?P<bar>[^/]++)?$#s', array('bar'), array(
                    array('variable', '/', '[^/]++', 'bar'),
                )),

            array(
                'Route with a requirement of 0',
                array('/{bar}', array('bar' => null), array('bar' => '0')),
                '', '#^/(?P<bar>0)?$#s', array('bar'), array(
                    array('variable', '/', '0', 'bar'),
                )),

            array(
                'Route with an optional variable as the first segment with requirements',
                array('/{bar}', array('bar' => 'bar'), array('bar' => '(foo|bar)')),
                '', '#^/(?P<bar>(foo|bar))?$#s', array('bar'), array(
                    array('variable', '/', '(foo|bar)', 'bar'),
                )),

            array(
                'Route with only optional variables',
                array('/{foo}/{bar}', array('foo' => 'foo', 'bar' => 'bar')),
                '', '#^/(?P<foo>[^/]++)?(?:/(?P<bar>[^/]++))?$#s', array('foo', 'bar'), array(
                    array('variable', '/', '[^/]++', 'bar'),
                    array('variable', '/', '[^/]++', 'foo'),
                )),

            array(
                'Route with a variable in last position',
                array('/foo-{bar}'),
                '/foo', '#^/foo\-(?P<bar>[^/]++)$#s', array('bar'), array(
                array('variable', '-', '[^/]++', 'bar'),
                array('text', '/foo'),
            )),

            array(
                'Route with nested placeholders',
                array('/{static{var}static}'),
                '/{static', '#^/\{static(?P<var>[^/]+)static\}$#s', array('var'), array(
                array('text', 'static}'),
                array('variable', '', '[^/]+', 'var'),
                array('text', '/{static'),
            )),

            array(
                'Route without separator between variables',
                array('/{w}{x}{y}{z}.{_format}', array('z' => 'default-z', '_format' => 'html'), array('y' => '(y|Y)')),
                '', '#^/(?P<w>[^/\.]+)(?P<x>[^/\.]+)(?P<y>(y|Y))(?:(?P<z>[^/\.]++)(?:\.(?P<_format>[^/]++))?)?$#s', array('w', 'x', 'y', 'z', '_format'), array(
                array('variable', '.', '[^/]++', '_format'),
                array('variable', '', '[^/\.]++', 'z'),
                array('variable', '', '(y|Y)', 'y'),
                array('variable', '', '[^/\.]+', 'x'),
                array('variable', '/', '[^/\.]+', 'w'),
            )),

            array(
                'Route with a format',
                array('/foo/{bar}.{_format}'),
                '/foo', '#^/foo/(?P<bar>[^/\.]++)\.(?P<_format>[^/]++)$#s', array('bar', '_format'), array(
                array('variable', '.', '[^/]++', '_format'),
                array('variable', '/', '[^/\.]++', 'bar'),
                array('text', '/foo'),
            )),
        );
    }

    /**
     * @expectedException \LogicException
     */
    public function testRouteWithSameVariableTwice()
    {
        $route = new Route('/{name}/{name}');

        $compiled = $route->compile();
    }

    /**
     * @dataProvider getNumericVariableNames
     * @expectedException \DomainException
     */
    public function testRouteWithNumericVariableName($name)
    {
        $route = new Route('/{'. $name.'}');
        $route->compile();
    }

    public function getNumericVariableNames()
    {
        return array(
           array('09'),
           array('123'),
           array('1e2')
        );
    }

    /**
     * @dataProvider provideCompileWithHostData
     */
    public function testCompileWithHost($name, $arguments, $prefix, $regex, $variables, $pathVariables, $tokens, $hostRegex, $hostVariables, $hostTokens)
    {
        $r = new \ReflectionClass('Symfony\\Component\\Routing\\Route');
        $route = $r->newInstanceArgs($arguments);

        $compiled = $route->compile();
        $this->assertEquals($prefix, $compiled->getStaticPrefix(), $name.' (static prefix)');
        $this->assertEquals($regex, str_replace(array("\n", ' '), '', $compiled->getRegex()), $name.' (regex)');
        $this->assertEquals($variables, $compiled->getVariables(), $name.' (variables)');
        $this->assertEquals($pathVariables, $compiled->getPathVariables(), $name.' (path variables)');
        $this->assertEquals($tokens, $compiled->getTokens(), $name.' (tokens)');
        $this->assertEquals($hostRegex, str_replace(array("\n", ' '), '', $compiled->getHostRegex()), $name.' (host regex)');
        $this->assertEquals($hostVariables, $compiled->getHostVariables(), $name.' (host variables)');
        $this->assertEquals($hostTokens, $compiled->getHostTokens(), $name.' (host tokens)');
    }

    public function provideCompileWithHostData()
    {
        return array(
            array(
                'Route with host pattern',
                array('/hello', array(), array(), array(), 'www.example.com'),
                '/hello', '#^/hello$#s', array(), array(), array(
                    array('text', '/hello'),
                ),
                '#^www\.example\.com$#s', array(), array(
                    array('text', 'www.example.com'),
                ),
            ),
            array(
                'Route with host pattern and some variables',
                array('/hello/{name}', array(), array(), array(), 'www.example.{tld}'),
                '/hello', '#^/hello/(?P<name>[^/]++)$#s', array('tld', 'name'), array('name'), array(
                    array('variable', '/', '[^/]++', 'name'),
                    array('text', '/hello'),
                ),
                '#^www\.example\.(?P<tld>[^\.]++)$#s', array('tld'), array(
                    array('variable', '.', '[^\.]++', 'tld'),
                    array('text', 'www.example'),
                ),
            ),
            array(
                'Route with variable at beginning of host',
                array('/hello', array(), array(), array(), '{locale}.example.{tld}'),
                '/hello', '#^/hello$#s', array('locale', 'tld'), array(), array(
                    array('text', '/hello'),
                ),
                '#^(?P<locale>[^\.]++)\.example\.(?P<tld>[^\.]++)$#s', array('locale', 'tld'), array(
                    array('variable', '.', '[^\.]++', 'tld'),
                    array('text', '.example'),
                    array('variable', '', '[^\.]++', 'locale'),
                ),
            ),
            array(
                'Route with host variables that has a default value',
                array('/hello', array('locale' => 'a', 'tld' => 'b'), array(), array(), '{locale}.example.{tld}'),
                '/hello', '#^/hello$#s', array('locale', 'tld'), array(), array(
                    array('text', '/hello'),
                ),
                '#^(?P<locale>[^\.]++)\.example\.(?P<tld>[^\.]++)$#s', array('locale', 'tld'), array(
                    array('variable', '.', '[^\.]++', 'tld'),
                    array('text', '.example'),
                    array('variable', '', '[^\.]++', 'locale'),
                ),
            ),
        );
    }
}
PK&1[1�d	nnHRouting/Symfony/Component/Routing/Tests/Fixtures/CustomXmlFileLoader.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Fixtures;

use Symfony\Component\Routing\Loader\XmlFileLoader;
use Symfony\Component\Config\Util\XmlUtils;

/**
 * XmlFileLoader with schema validation turned off
 */
class CustomXmlFileLoader extends XmlFileLoader
{
    protected function loadFile($file)
    {
        return XmlUtils::loadFile($file, function () { return true; });
    }
}
PK&1[>Routing/Symfony/Component/Routing/Tests/Fixtures/annotated.phpnu�[���PK&1[:Routing/Symfony/Component/Routing/Tests/Fixtures/empty.ymlnu�[���PK&1[�/���ARouting/Symfony/Component/Routing/Tests/Fixtures/validpattern.ymlnu�[���blog_show:
    path:         /blog/{slug}
    defaults:     { _controller: "MyBundle:Blog:show" }
    host:         "{locale}.example.com"
    requirements: { 'locale': '\w+' }
    methods:      ['GET','POST','put','OpTiOnS']
    schemes:      ['https']
    condition:    'context.getMethod() == "GET"'
    options:
        compiler_class: RouteCompiler

blog_show_legacy:
    pattern:      /blog/{slug}
    defaults:     { _controller: "MyBundle:Blog:show" }
    host:         "{locale}.example.com"
    requirements: { '_method': 'GET|POST|put|OpTiOnS', _scheme: https, 'locale': '\w+' }
    condition:    'context.getMethod() == "GET"'
    options:
        compiler_class: RouteCompiler

blog_show_inherited:
    path:      /blog/{slug}
PK&1[�M��ARouting/Symfony/Component/Routing/Tests/Fixtures/validpattern.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="blog_show" path="/blog/{slug}" host="{locale}.example.com" methods="GET|POST  put,OpTiOnS" schemes="hTTps">
        <default key="_controller">MyBundle:Blog:show</default>
        <requirement key="locale">\w+</requirement>
        <option key="compiler_class">RouteCompiler</option>
        <condition>context.getMethod() == "GET"</condition>
    </route>

    <route id="blog_show_legacy" pattern="/blog/{slug}" host="{locale}.example.com">
        <default key="_controller">MyBundle:Blog:show</default>
        <default key="slug" xsi:nil="true" />
        <requirement key="_method">GET|POST|put|OpTiOnS</requirement>
        <requirement key="_scheme">hTTps</requirement>
        <requirement key="locale">\w+</requirement>
        <option key="compiler_class">RouteCompiler</option>
        <condition>context.getMethod() == "GET"</condition>
    </route>

    <route id="blog_show_inherited" path="/blog/{slug}" />
</routes>
PK&1[�/�$>>QRouting/Symfony/Component/Routing/Tests/Fixtures/nonesense_resource_plus_path.ymlnu�[���blog_show:
    resource: validpattern.yml
    path:     /test
PK&1[��==ARouting/Symfony/Component/Routing/Tests/Fixtures/nonvalidkeys.ymlnu�[���someroute:
  resource: path/to/some.yml
  name_prefix: test_
PK&1[�ie��DRouting/Symfony/Component/Routing/Tests/Fixtures/namespaceprefix.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<r:routes xmlns:r="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <r:route id="blog_show" path="/blog/{slug}" host="{_locale}.example.com">
        <r:default key="_controller">MyBundle:Blog:show</r:default>
        <requirement xmlns="http://symfony.com/schema/routing" key="slug">\w+</requirement>
        <r2:requirement xmlns:r2="http://symfony.com/schema/routing" key="_locale">en|fr|de</r2:requirement>
        <r:option key="compiler_class">RouteCompiler</r:option>
    </r:route>
</r:routes>
PK&1[#q��//?Routing/Symfony/Component/Routing/Tests/Fixtures/missing_id.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route path="/test"></route>
</routes>
PK&1[x'�	11@Routing/Symfony/Component/Routing/Tests/Fixtures/withdoctype.xmlnu�[���<?xml version="1.0"?>
<!DOCTYPE foo>
<foo></foo>
PK&1[�;h�%%KRouting/Symfony/Component/Routing/Tests/Fixtures/RedirectableUrlMatcher.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Fixtures;

use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
{
    public function redirect($path, $route, $scheme = null)
    {
        return array(
            '_controller' => 'Some controller reference...',
            'path'        => $path,
            'scheme'      => $scheme,
        );
    }
}
PK&1[s��[//ARouting/Symfony/Component/Routing/Tests/Fixtures/missing_path.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="myroute"></route>
</routes>
PK'1[�e2~=Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid.ymlnu�[���foo
PK'1[ix��77ARouting/Symfony/Component/Routing/Tests/Fixtures/validpattern.phpnu�[���<?php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

$collection = new RouteCollection();
$collection->add('blog_show', new Route(
    '/blog/{slug}',
    array('_controller' => 'MyBlogBundle:Blog:show'),
    array('locale' => '\w+'),
    array('compiler_class' => 'RouteCompiler'),
    '{locale}.example.com',
    array('https'),
    array('GET','POST','put','OpTiOnS'),
    'context.getMethod() == "GET"'
));
$collection->add('blog_show_legacy', new Route(
    '/blog/{slug}',
    array('_controller' => 'MyBlogBundle:Blog:show'),
    array('_method' => 'GET|POST|put|OpTiOnS', '_scheme' => 'https', 'locale' => '\w+',),
    array('compiler_class' => 'RouteCompiler'),
    '{locale}.example.com',
    array(),
    array(),
    'context.getMethod() == "GET"'
));

return $collection;
PK'1[�G�V,+,+HRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.phpnu�[���<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * ProjectUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        // foo
        if (0 === strpos($pathinfo, '/foo') && preg_match('#^/foo/(?P<bar>baz|symfony)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo')), array (  'def' => 'test',));
        }

        if (0 === strpos($pathinfo, '/bar')) {
            // bar
            if (preg_match('#^/bar/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_bar;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar')), array ());
            }
            not_bar:

            // barhead
            if (0 === strpos($pathinfo, '/barhead') && preg_match('#^/barhead/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_barhead;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'barhead')), array ());
            }
            not_barhead:

        }

        if (0 === strpos($pathinfo, '/test')) {
            if (0 === strpos($pathinfo, '/test/baz')) {
                // baz
                if ($pathinfo === '/test/baz') {
                    return array('_route' => 'baz');
                }

                // baz2
                if ($pathinfo === '/test/baz.html') {
                    return array('_route' => 'baz2');
                }

                // baz3
                if ($pathinfo === '/test/baz3/') {
                    return array('_route' => 'baz3');
                }

            }

            // baz4
            if (preg_match('#^/test/(?P<foo>[^/]++)/$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz4')), array ());
            }

            // baz5
            if (preg_match('#^/test/(?P<foo>[^/]++)/$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'POST') {
                    $allow[] = 'POST';
                    goto not_baz5;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz5')), array ());
            }
            not_baz5:

            // baz.baz6
            if (preg_match('#^/test/(?P<foo>[^/]++)/$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'PUT') {
                    $allow[] = 'PUT';
                    goto not_bazbaz6;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz.baz6')), array ());
            }
            not_bazbaz6:

        }

        // foofoo
        if ($pathinfo === '/foofoo') {
            return array (  'def' => 'test',  '_route' => 'foofoo',);
        }

        // quoter
        if (preg_match('#^/(?P<quoter>[\']+)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'quoter')), array ());
        }

        // space
        if ($pathinfo === '/spa ce') {
            return array('_route' => 'space');
        }

        if (0 === strpos($pathinfo, '/a')) {
            if (0 === strpos($pathinfo, '/a/b\'b')) {
                // foo1
                if (preg_match('#^/a/b\'b/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo1')), array ());
                }

                // bar1
                if (preg_match('#^/a/b\'b/(?P<bar>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar1')), array ());
                }

            }

            // overridden
            if (preg_match('#^/a/(?P<var>.*)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'overridden')), array ());
            }

            if (0 === strpos($pathinfo, '/a/b\'b')) {
                // foo2
                if (preg_match('#^/a/b\'b/(?P<foo1>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo2')), array ());
                }

                // bar2
                if (preg_match('#^/a/b\'b/(?P<bar1>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar2')), array ());
                }

            }

        }

        if (0 === strpos($pathinfo, '/multi')) {
            // helloWorld
            if (0 === strpos($pathinfo, '/multi/hello') && preg_match('#^/multi/hello(?:/(?P<who>[^/]++))?$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'helloWorld')), array (  'who' => 'World!',));
            }

            // overridden2
            if ($pathinfo === '/multi/new') {
                return array('_route' => 'overridden2');
            }

            // hey
            if ($pathinfo === '/multi/hey/') {
                return array('_route' => 'hey');
            }

        }

        // foo3
        if (preg_match('#^/(?P<_locale>[^/]++)/b/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo3')), array ());
        }

        // bar3
        if (preg_match('#^/(?P<_locale>[^/]++)/b/(?P<bar>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar3')), array ());
        }

        if (0 === strpos($pathinfo, '/aba')) {
            // ababa
            if ($pathinfo === '/ababa') {
                return array('_route' => 'ababa');
            }

            // foo4
            if (preg_match('#^/aba/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo4')), array ());
            }

        }

        $host = $this->context->getHost();

        if (preg_match('#^a\\.example\\.com$#s', $host, $hostMatches)) {
            // route1
            if ($pathinfo === '/route1') {
                return array('_route' => 'route1');
            }

            // route2
            if ($pathinfo === '/c2/route2') {
                return array('_route' => 'route2');
            }

        }

        if (preg_match('#^b\\.example\\.com$#s', $host, $hostMatches)) {
            // route3
            if ($pathinfo === '/c2/route3') {
                return array('_route' => 'route3');
            }

        }

        if (preg_match('#^a\\.example\\.com$#s', $host, $hostMatches)) {
            // route4
            if ($pathinfo === '/route4') {
                return array('_route' => 'route4');
            }

        }

        if (preg_match('#^c\\.example\\.com$#s', $host, $hostMatches)) {
            // route5
            if ($pathinfo === '/route5') {
                return array('_route' => 'route5');
            }

        }

        // route6
        if ($pathinfo === '/route6') {
            return array('_route' => 'route6');
        }

        if (preg_match('#^(?P<var1>[^\\.]++)\\.example\\.com$#s', $host, $hostMatches)) {
            if (0 === strpos($pathinfo, '/route1')) {
                // route11
                if ($pathinfo === '/route11') {
                    return $this->mergeDefaults(array_replace($hostMatches, array('_route' => 'route11')), array ());
                }

                // route12
                if ($pathinfo === '/route12') {
                    return $this->mergeDefaults(array_replace($hostMatches, array('_route' => 'route12')), array (  'var1' => 'val',));
                }

                // route13
                if (0 === strpos($pathinfo, '/route13') && preg_match('#^/route13/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($hostMatches, $matches, array('_route' => 'route13')), array ());
                }

                // route14
                if (0 === strpos($pathinfo, '/route14') && preg_match('#^/route14/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($hostMatches, $matches, array('_route' => 'route14')), array (  'var1' => 'val',));
                }

            }

        }

        if (preg_match('#^c\\.example\\.com$#s', $host, $hostMatches)) {
            // route15
            if (0 === strpos($pathinfo, '/route15') && preg_match('#^/route15/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'route15')), array ());
            }

        }

        if (0 === strpos($pathinfo, '/route1')) {
            // route16
            if (0 === strpos($pathinfo, '/route16') && preg_match('#^/route16/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'route16')), array (  'var1' => 'val',));
            }

            // route17
            if ($pathinfo === '/route17') {
                return array('_route' => 'route17');
            }

        }

        if (0 === strpos($pathinfo, '/a')) {
            // a
            if ($pathinfo === '/a/a...') {
                return array('_route' => 'a');
            }

            if (0 === strpos($pathinfo, '/a/b')) {
                // b
                if (preg_match('#^/a/b/(?P<var>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'b')), array ());
                }

                // c
                if (0 === strpos($pathinfo, '/a/b/c') && preg_match('#^/a/b/c/(?P<var>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'c')), array ());
                }

            }

        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}
PK'1[T����HRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher3.phpnu�[���<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * ProjectUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class ProjectUrlMatcher extends Symfony\Component\Routing\Matcher\UrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        if (0 === strpos($pathinfo, '/rootprefix')) {
            // static
            if ($pathinfo === '/rootprefix/test') {
                return array('_route' => 'static');
            }

            // dynamic
            if (preg_match('#^/rootprefix/(?P<var>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'dynamic')), array ());
            }

        }

        // with-condition
        if ($pathinfo === '/with-condition' && ($context->getMethod() == "GET")) {
            return array('_route' => 'with-condition');
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}
PK'1[@4��KRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.apachenu�[���# skip "real" requests
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [QSA,L]

# foo
RewriteCond %{REQUEST_URI} ^/foo/(baz|symfony)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:foo,E=_ROUTING_param_bar:%1,E=_ROUTING_default_def:test]

# foobar
RewriteCond %{REQUEST_URI} ^/foo(?:/([^/]++))?$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:foobar,E=_ROUTING_param_bar:%1,E=_ROUTING_default_bar:toto]

# bar
RewriteCond %{REQUEST_URI} ^/bar/([^/]++)$
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [NC]
RewriteRule .* - [S=1,E=_ROUTING_allow_GET:1,E=_ROUTING_allow_HEAD:1]
RewriteCond %{REQUEST_URI} ^/bar/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:bar,E=_ROUTING_param_foo:%1]

# baragain
RewriteCond %{REQUEST_URI} ^/baragain/([^/]++)$
RewriteCond %{REQUEST_METHOD} !^(GET|POST|HEAD)$ [NC]
RewriteRule .* - [S=1,E=_ROUTING_allow_GET:1,E=_ROUTING_allow_POST:1,E=_ROUTING_allow_HEAD:1]
RewriteCond %{REQUEST_URI} ^/baragain/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baragain,E=_ROUTING_param_foo:%1]

# baz
RewriteCond %{REQUEST_URI} ^/test/baz$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz]

# baz2
RewriteCond %{REQUEST_URI} ^/test/baz\.html$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz2]

# baz3
RewriteCond %{REQUEST_URI} ^/test/baz3$
RewriteRule .* $0/ [QSA,L,R=301]
RewriteCond %{REQUEST_URI} ^/test/baz3/$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz3]

# baz4
RewriteCond %{REQUEST_URI} ^/test/([^/]++)$
RewriteRule .* $0/ [QSA,L,R=301]
RewriteCond %{REQUEST_URI} ^/test/([^/]++)/$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz4,E=_ROUTING_param_foo:%1]

# baz5
RewriteCond %{REQUEST_URI} ^/test/([^/]++)/$
RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [NC]
RewriteRule .* - [S=2,E=_ROUTING_allow_GET:1,E=_ROUTING_allow_HEAD:1]
RewriteCond %{REQUEST_URI} ^/test/([^/]++)$
RewriteRule .* $0/ [QSA,L,R=301]
RewriteCond %{REQUEST_URI} ^/test/([^/]++)/$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz5,E=_ROUTING_param_foo:%1]

# baz5unsafe
RewriteCond %{REQUEST_URI} ^/testunsafe/([^/]++)/$
RewriteCond %{REQUEST_METHOD} !^(POST)$ [NC]
RewriteRule .* - [S=1,E=_ROUTING_allow_POST:1]
RewriteCond %{REQUEST_URI} ^/testunsafe/([^/]++)/$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz5unsafe,E=_ROUTING_param_foo:%1]

# baz6
RewriteCond %{REQUEST_URI} ^/test/baz$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz6,E=_ROUTING_default_foo:bar\ baz]

# baz7
RewriteCond %{REQUEST_URI} ^/te\ st/baz$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz7]

# baz8
RewriteCond %{REQUEST_URI} ^/te\\\ st/baz$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz8]

# baz9
RewriteCond %{REQUEST_URI} ^/test/(te\\\ st)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:baz9,E=_ROUTING_param_baz:%1]

RewriteCond %{HTTP:Host} ^a\.example\.com$
RewriteRule .? - [E=__ROUTING_host_1:1]

# route1
RewriteCond %{ENV:__ROUTING_host_1} =1
RewriteCond %{REQUEST_URI} ^/route1$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route1]

# route2
RewriteCond %{ENV:__ROUTING_host_1} =1
RewriteCond %{REQUEST_URI} ^/c2/route2$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route2]

RewriteCond %{HTTP:Host} ^b\.example\.com$
RewriteRule .? - [E=__ROUTING_host_2:1]

# route3
RewriteCond %{ENV:__ROUTING_host_2} =1
RewriteCond %{REQUEST_URI} ^/c2/route3$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route3]

RewriteCond %{HTTP:Host} ^a\.example\.com$
RewriteRule .? - [E=__ROUTING_host_3:1]

# route4
RewriteCond %{ENV:__ROUTING_host_3} =1
RewriteCond %{REQUEST_URI} ^/route4$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route4]

RewriteCond %{HTTP:Host} ^c\.example\.com$
RewriteRule .? - [E=__ROUTING_host_4:1]

# route5
RewriteCond %{ENV:__ROUTING_host_4} =1
RewriteCond %{REQUEST_URI} ^/route5$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route5]

# route6
RewriteCond %{REQUEST_URI} ^/route6$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route6]

RewriteCond %{HTTP:Host} ^([^\.]++)\.example\.com$
RewriteRule .? - [E=__ROUTING_host_5:1,E=__ROUTING_host_5_var1:%1]

# route11
RewriteCond %{ENV:__ROUTING_host_5} =1
RewriteCond %{REQUEST_URI} ^/route11$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route11,E=_ROUTING_param_var1:%{ENV:__ROUTING_host_5_var1}]

# route12
RewriteCond %{ENV:__ROUTING_host_5} =1
RewriteCond %{REQUEST_URI} ^/route12$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route12,E=_ROUTING_param_var1:%{ENV:__ROUTING_host_5_var1},E=_ROUTING_default_var1:val]

# route13
RewriteCond %{ENV:__ROUTING_host_5} =1
RewriteCond %{REQUEST_URI} ^/route13/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route13,E=_ROUTING_param_var1:%{ENV:__ROUTING_host_5_var1},E=_ROUTING_param_name:%1]

# route14
RewriteCond %{ENV:__ROUTING_host_5} =1
RewriteCond %{REQUEST_URI} ^/route14/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route14,E=_ROUTING_param_var1:%{ENV:__ROUTING_host_5_var1},E=_ROUTING_param_name:%1,E=_ROUTING_default_var1:val]

RewriteCond %{HTTP:Host} ^c\.example\.com$
RewriteRule .? - [E=__ROUTING_host_6:1]

# route15
RewriteCond %{ENV:__ROUTING_host_6} =1
RewriteCond %{REQUEST_URI} ^/route15/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route15,E=_ROUTING_param_name:%1]

# route16
RewriteCond %{REQUEST_URI} ^/route16/([^/]++)$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route16,E=_ROUTING_param_name:%1,E=_ROUTING_default_var1:val]

# route17
RewriteCond %{REQUEST_URI} ^/route17$
RewriteRule .* app.php [QSA,L,E=_ROUTING_route:route17]

# 405 Method Not Allowed
RewriteCond %{ENV:_ROUTING__allow_GET} =1 [OR]
RewriteCond %{ENV:_ROUTING__allow_HEAD} =1 [OR]
RewriteCond %{ENV:_ROUTING__allow_POST} =1
RewriteRule .* app.php [QSA,L]
PK'1[Bx�6��KRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.apachenu�[���# skip "real" requests
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .* - [QSA,L]

# foo
RewriteCond %{REQUEST_URI} ^/foo$
RewriteRule .* ap\ p_d\ ev.php [QSA,L,E=_ROUTING_route:foo]
PK'1[n�k�//HRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.phpnu�[���<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * ProjectUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class ProjectUrlMatcher extends Symfony\Component\Routing\Tests\Fixtures\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        // foo
        if (0 === strpos($pathinfo, '/foo') && preg_match('#^/foo/(?P<bar>baz|symfony)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo')), array (  'def' => 'test',));
        }

        if (0 === strpos($pathinfo, '/bar')) {
            // bar
            if (preg_match('#^/bar/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_bar;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar')), array ());
            }
            not_bar:

            // barhead
            if (0 === strpos($pathinfo, '/barhead') && preg_match('#^/barhead/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_barhead;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'barhead')), array ());
            }
            not_barhead:

        }

        if (0 === strpos($pathinfo, '/test')) {
            if (0 === strpos($pathinfo, '/test/baz')) {
                // baz
                if ($pathinfo === '/test/baz') {
                    return array('_route' => 'baz');
                }

                // baz2
                if ($pathinfo === '/test/baz.html') {
                    return array('_route' => 'baz2');
                }

                // baz3
                if (rtrim($pathinfo, '/') === '/test/baz3') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', 'baz3');
                    }

                    return array('_route' => 'baz3');
                }

            }

            // baz4
            if (preg_match('#^/test/(?P<foo>[^/]++)/?$#s', $pathinfo, $matches)) {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'baz4');
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz4')), array ());
            }

            // baz5
            if (preg_match('#^/test/(?P<foo>[^/]++)/$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'POST') {
                    $allow[] = 'POST';
                    goto not_baz5;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz5')), array ());
            }
            not_baz5:

            // baz.baz6
            if (preg_match('#^/test/(?P<foo>[^/]++)/$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'PUT') {
                    $allow[] = 'PUT';
                    goto not_bazbaz6;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'baz.baz6')), array ());
            }
            not_bazbaz6:

        }

        // foofoo
        if ($pathinfo === '/foofoo') {
            return array (  'def' => 'test',  '_route' => 'foofoo',);
        }

        // quoter
        if (preg_match('#^/(?P<quoter>[\']+)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'quoter')), array ());
        }

        // space
        if ($pathinfo === '/spa ce') {
            return array('_route' => 'space');
        }

        if (0 === strpos($pathinfo, '/a')) {
            if (0 === strpos($pathinfo, '/a/b\'b')) {
                // foo1
                if (preg_match('#^/a/b\'b/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo1')), array ());
                }

                // bar1
                if (preg_match('#^/a/b\'b/(?P<bar>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar1')), array ());
                }

            }

            // overridden
            if (preg_match('#^/a/(?P<var>.*)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'overridden')), array ());
            }

            if (0 === strpos($pathinfo, '/a/b\'b')) {
                // foo2
                if (preg_match('#^/a/b\'b/(?P<foo1>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo2')), array ());
                }

                // bar2
                if (preg_match('#^/a/b\'b/(?P<bar1>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar2')), array ());
                }

            }

        }

        if (0 === strpos($pathinfo, '/multi')) {
            // helloWorld
            if (0 === strpos($pathinfo, '/multi/hello') && preg_match('#^/multi/hello(?:/(?P<who>[^/]++))?$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'helloWorld')), array (  'who' => 'World!',));
            }

            // overridden2
            if ($pathinfo === '/multi/new') {
                return array('_route' => 'overridden2');
            }

            // hey
            if (rtrim($pathinfo, '/') === '/multi/hey') {
                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'hey');
                }

                return array('_route' => 'hey');
            }

        }

        // foo3
        if (preg_match('#^/(?P<_locale>[^/]++)/b/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo3')), array ());
        }

        // bar3
        if (preg_match('#^/(?P<_locale>[^/]++)/b/(?P<bar>[^/]++)$#s', $pathinfo, $matches)) {
            return $this->mergeDefaults(array_replace($matches, array('_route' => 'bar3')), array ());
        }

        if (0 === strpos($pathinfo, '/aba')) {
            // ababa
            if ($pathinfo === '/ababa') {
                return array('_route' => 'ababa');
            }

            // foo4
            if (preg_match('#^/aba/(?P<foo>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'foo4')), array ());
            }

        }

        $host = $this->context->getHost();

        if (preg_match('#^a\\.example\\.com$#s', $host, $hostMatches)) {
            // route1
            if ($pathinfo === '/route1') {
                return array('_route' => 'route1');
            }

            // route2
            if ($pathinfo === '/c2/route2') {
                return array('_route' => 'route2');
            }

        }

        if (preg_match('#^b\\.example\\.com$#s', $host, $hostMatches)) {
            // route3
            if ($pathinfo === '/c2/route3') {
                return array('_route' => 'route3');
            }

        }

        if (preg_match('#^a\\.example\\.com$#s', $host, $hostMatches)) {
            // route4
            if ($pathinfo === '/route4') {
                return array('_route' => 'route4');
            }

        }

        if (preg_match('#^c\\.example\\.com$#s', $host, $hostMatches)) {
            // route5
            if ($pathinfo === '/route5') {
                return array('_route' => 'route5');
            }

        }

        // route6
        if ($pathinfo === '/route6') {
            return array('_route' => 'route6');
        }

        if (preg_match('#^(?P<var1>[^\\.]++)\\.example\\.com$#s', $host, $hostMatches)) {
            if (0 === strpos($pathinfo, '/route1')) {
                // route11
                if ($pathinfo === '/route11') {
                    return $this->mergeDefaults(array_replace($hostMatches, array('_route' => 'route11')), array ());
                }

                // route12
                if ($pathinfo === '/route12') {
                    return $this->mergeDefaults(array_replace($hostMatches, array('_route' => 'route12')), array (  'var1' => 'val',));
                }

                // route13
                if (0 === strpos($pathinfo, '/route13') && preg_match('#^/route13/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($hostMatches, $matches, array('_route' => 'route13')), array ());
                }

                // route14
                if (0 === strpos($pathinfo, '/route14') && preg_match('#^/route14/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($hostMatches, $matches, array('_route' => 'route14')), array (  'var1' => 'val',));
                }

            }

        }

        if (preg_match('#^c\\.example\\.com$#s', $host, $hostMatches)) {
            // route15
            if (0 === strpos($pathinfo, '/route15') && preg_match('#^/route15/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'route15')), array ());
            }

        }

        if (0 === strpos($pathinfo, '/route1')) {
            // route16
            if (0 === strpos($pathinfo, '/route16') && preg_match('#^/route16/(?P<name>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => 'route16')), array (  'var1' => 'val',));
            }

            // route17
            if ($pathinfo === '/route17') {
                return array('_route' => 'route17');
            }

        }

        if (0 === strpos($pathinfo, '/a')) {
            // a
            if ($pathinfo === '/a/a...') {
                return array('_route' => 'a');
            }

            if (0 === strpos($pathinfo, '/a/b')) {
                // b
                if (preg_match('#^/a/b/(?P<var>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'b')), array ());
                }

                // c
                if (0 === strpos($pathinfo, '/a/b/c') && preg_match('#^/a/b/c/(?P<var>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'c')), array ());
                }

            }

        }

        // secure
        if ($pathinfo === '/secure') {
            if ($this->context->getScheme() !== 'https') {
                return $this->redirect($pathinfo, 'secure', 'https');
            }

            return array('_route' => 'secure');
        }

        // nonsecure
        if ($pathinfo === '/nonsecure') {
            if ($this->context->getScheme() !== 'http') {
                return $this->redirect($pathinfo, 'nonsecure', 'http');
            }

            return array('_route' => 'nonsecure');
        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}
PK'1[�p��=Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="blog_show" path="/blog/{slug}">
        <default key="_controller">MyBundle:Blog:show</default>
        <requirement key="_method">GET</requirement>
    <!-- </route> -->
</routes>
PK'1[ͼ�n!!ARouting/Symfony/Component/Routing/Tests/Fixtures/nonvalidnode.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <foo>bar</foo>
</routes>
PK'1[T��NRouting/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/BarClass.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses;

class BarClass
{
    public function routeAction($arg1, $arg2 = 'defaultValue2', $arg3 = 'defaultValue3')
    {
    }
}
PK'1[���GGNRouting/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/FooClass.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses;

class FooClass
{
}
PK'1[�zUUSRouting/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/AbstractClass.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses;

abstract class AbstractClass
{
}
PK'1[�M�t>Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid2.ymlnu�[���route: string
PK'1[�b�BRouting/Symfony/Component/Routing/Tests/Fixtures/validresource.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <import resource="validpattern.xml" prefix="/{foo}" host="">
        <default key="foo">123</default>
        <requirement key="foo">\d+</requirement>
        <option key="foo">bar</option>
        <condition>context.getMethod() == "POST"</condition>
    </import>
</routes>
PK'1[��q�BRouting/Symfony/Component/Routing/Tests/Fixtures/nonvalidroute.xmlnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="blog_show" path="/blog/{slug}">
        <default key="_controller">MyBundle:Blog:show</default>
        <requirement key="_method">GET</requirement>
        <option key="compiler_class">RouteCompiler</option>
        <foo key="bar">baz</foo>
    </route>
</routes>
PK'1[��ϮBB?Routing/Symfony/Component/Routing/Tests/Fixtures/incomplete.ymlnu�[���blog_show:
    defaults:  { _controller: MyBlogBundle:Blog:show }
PK'1[�J?�GRouting/Symfony/Component/Routing/Tests/Fixtures/special_route_name.ymlnu�[���"#$péß^a|":
    path: "true"
PK(1[�q�99TRouting/Symfony/Component/Routing/Tests/Fixtures/nonesense_type_without_resource.ymlnu�[���blog_show:
    path:    /blog/{slug}
    type:    custom
PK(1[jX���BRouting/Symfony/Component/Routing/Tests/Fixtures/validresource.ymlnu�[���_blog:
    resource:     validpattern.yml
    prefix:       /{foo}
    defaults:     { 'foo': '123' }
    requirements: { 'foo': '\d+' }
    options:      { 'foo': 'bar' }
    host:         ""
    condition:    'context.getMethod() == "POST"'
PK(1[9Routing/Symfony/Component/Routing/Tests/Fixtures/foo1.xmlnu�[���PK(1[8Routing/Symfony/Component/Routing/Tests/Fixtures/foo.xmlnu�[���PK(1[��/��
�
>Routing/Symfony/Component/Routing/Tests/RequestContextTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;

class RequestContextTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $requestContext = new RequestContext(
            'foo',
            'post',
            'foo.bar',
            'HTTPS',
            8080,
            444,
            '/baz',
            'bar=foobar'
        );

        $this->assertEquals('foo', $requestContext->getBaseUrl());
        $this->assertEquals('POST', $requestContext->getMethod());
        $this->assertEquals('foo.bar', $requestContext->getHost());
        $this->assertEquals('https', $requestContext->getScheme());
        $this->assertSame(8080, $requestContext->getHttpPort());
        $this->assertSame(444, $requestContext->getHttpsPort());
        $this->assertEquals('/baz', $requestContext->getPathInfo());
        $this->assertEquals('bar=foobar', $requestContext->getQueryString());
    }

    public function testFromRequest()
    {
        $request = Request::create('https://test.com:444/foo?bar=baz');
        $requestContext = new RequestContext();
        $requestContext->setHttpPort(123);
        $requestContext->fromRequest($request);

        $this->assertEquals('', $requestContext->getBaseUrl());
        $this->assertEquals('GET', $requestContext->getMethod());
        $this->assertEquals('test.com', $requestContext->getHost());
        $this->assertEquals('https', $requestContext->getScheme());
        $this->assertEquals('/foo', $requestContext->getPathInfo());
        $this->assertEquals('bar=baz', $requestContext->getQueryString());
        $this->assertSame(123, $requestContext->getHttpPort());
        $this->assertSame(444, $requestContext->getHttpsPort());

        $request = Request::create('http://test.com:8080/foo?bar=baz');
        $requestContext = new RequestContext();
        $requestContext->setHttpsPort(567);
        $requestContext->fromRequest($request);

        $this->assertSame(8080, $requestContext->getHttpPort());
        $this->assertSame(567, $requestContext->getHttpsPort());
    }

    public function testGetParameters()
    {
        $requestContext = new RequestContext();
        $this->assertEquals(array(), $requestContext->getParameters());

        $requestContext->setParameters(array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $requestContext->getParameters());
    }

    public function testHasParameter()
    {
        $requestContext = new RequestContext();
        $requestContext->setParameters(array('foo' => 'bar'));

        $this->assertTrue($requestContext->hasParameter('foo'));
        $this->assertFalse($requestContext->hasParameter('baz'));
    }

    public function testGetParameter()
    {
        $requestContext = new RequestContext();
        $requestContext->setParameters(array('foo' => 'bar'));

        $this->assertEquals('bar', $requestContext->getParameter('foo'));
        $this->assertNull($requestContext->getParameter('baz'));
    }

    public function testSetParameter()
    {
        $requestContext = new RequestContext();
        $requestContext->setParameter('foo', 'bar');

        $this->assertEquals('bar', $requestContext->getParameter('foo'));
    }
}
PK(1[���
�
KRouting/Symfony/Component/Routing/Tests/Matcher/TraceableUrlMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\TraceableUrlMatcher;

class TraceableUrlMatcherTest extends \PHPUnit_Framework_TestCase
{
    public function test()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', array(), array('_method' => 'POST')));
        $coll->add('bar', new Route('/bar/{id}', array(), array('id' => '\d+')));
        $coll->add('bar1', new Route('/bar/{name}', array(), array('id' => '\w+', '_method' => 'POST')));
        $coll->add('bar2', new Route('/foo', array(), array(), array(), 'baz'));
        $coll->add('bar3', new Route('/foo1', array(), array(), array(), 'baz'));
        $coll->add('bar4', new Route('/foo2', array(), array(), array(), 'baz', array(), array(), 'context.getMethod() == "GET"'));

        $context = new RequestContext();
        $context->setHost('baz');

        $matcher = new TraceableUrlMatcher($coll, $context);
        $traces = $matcher->getTraces('/babar');
        $this->assertEquals(array(0, 0, 0, 0, 0, 0), $this->getLevels($traces));

        $traces = $matcher->getTraces('/foo');
        $this->assertEquals(array(1, 0, 0, 2), $this->getLevels($traces));

        $traces = $matcher->getTraces('/bar/12');
        $this->assertEquals(array(0, 2), $this->getLevels($traces));

        $traces = $matcher->getTraces('/bar/dd');
        $this->assertEquals(array(0, 1, 1, 0, 0, 0), $this->getLevels($traces));

        $traces = $matcher->getTraces('/foo1');
        $this->assertEquals(array(0, 0, 0, 0, 2), $this->getLevels($traces));

        $context->setMethod('POST');
        $traces = $matcher->getTraces('/foo');
        $this->assertEquals(array(2), $this->getLevels($traces));

        $traces = $matcher->getTraces('/bar/dd');
        $this->assertEquals(array(0, 1, 2), $this->getLevels($traces));

        $traces = $matcher->getTraces('/foo2');
        $this->assertEquals(array(0, 0, 0, 0, 0, 1), $this->getLevels($traces));
    }

    public function testMatchRouteOnMultipleHosts()
    {
        $routes = new RouteCollection();
        $routes->add('first', new Route(
            '/mypath/',
            array('_controller' => 'MainBundle:Info:first'),
            array(),
            array(),
            'some.example.com'
        ));

        $routes->add('second', new Route(
            '/mypath/',
            array('_controller' => 'MainBundle:Info:second'),
            array(),
            array(),
            'another.example.com'
        ));

        $context = new RequestContext();
        $context->setHost('baz');

        $matcher = new TraceableUrlMatcher($routes, $context);

        $traces = $matcher->getTraces('/mypath/');
        $this->assertEquals(
            array(TraceableUrlMatcher::ROUTE_ALMOST_MATCHES, TraceableUrlMatcher::ROUTE_ALMOST_MATCHES),
            $this->getLevels($traces)
        );
    }

    public function getLevels($traces)
    {
        $levels = array();
        foreach ($traces as $trace) {
            $levels[] = $trace['level'];
        }

        return $levels;
    }
}
PK(1[t�kT�B�BBRouting/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher;

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;

class UrlMatcherTest extends \PHPUnit_Framework_TestCase
{
    public function testNoMethodSoAllowed()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo'));

        $matcher = new UrlMatcher($coll, new RequestContext());
        $matcher->match('/foo');
    }

    public function testMethodNotAllowed()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', array(), array('_method' => 'post')));

        $matcher = new UrlMatcher($coll, new RequestContext());

        try {
            $matcher->match('/foo');
            $this->fail();
        } catch (MethodNotAllowedException $e) {
            $this->assertEquals(array('POST'), $e->getAllowedMethods());
        }
    }

    public function testHeadAllowedWhenRequirementContainsGet()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', array(), array('_method' => 'get')));

        $matcher = new UrlMatcher($coll, new RequestContext('', 'head'));
        $matcher->match('/foo');
    }

    public function testMethodNotAllowedAggregatesAllowedMethods()
    {
        $coll = new RouteCollection();
        $coll->add('foo1', new Route('/foo', array(), array('_method' => 'post')));
        $coll->add('foo2', new Route('/foo', array(), array('_method' => 'put|delete')));

        $matcher = new UrlMatcher($coll, new RequestContext());

        try {
            $matcher->match('/foo');
            $this->fail();
        } catch (MethodNotAllowedException $e) {
            $this->assertEquals(array('POST', 'PUT', 'DELETE'), $e->getAllowedMethods());
        }
    }

    public function testMatch()
    {
        // test the patterns are matched and parameters are returned
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo/{bar}'));
        $matcher = new UrlMatcher($collection, new RequestContext());
        try {
            $matcher->match('/no-match');
            $this->fail();
        } catch (ResourceNotFoundException $e) {}
        $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz'), $matcher->match('/foo/baz'));

        // test that defaults are merged
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo/{bar}', array('def' => 'test')));
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'foo', 'bar' => 'baz', 'def' => 'test'), $matcher->match('/foo/baz'));

        // test that route "method" is ignored if no method is given in the context
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo', array(), array('_method' => 'GET|head')));
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertInternalType('array', $matcher->match('/foo'));

        // route does not match with POST method context
        $matcher = new UrlMatcher($collection, new RequestContext('', 'post'));
        try {
            $matcher->match('/foo');
            $this->fail();
        } catch (MethodNotAllowedException $e) {}

        // route does match with GET or HEAD method context
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertInternalType('array', $matcher->match('/foo'));
        $matcher = new UrlMatcher($collection, new RequestContext('', 'head'));
        $this->assertInternalType('array', $matcher->match('/foo'));

        // route with an optional variable as the first segment
        $collection = new RouteCollection();
        $collection->add('bar', new Route('/{bar}/foo', array('bar' => 'bar'), array('bar' => 'foo|bar')));
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'bar', 'bar' => 'bar'), $matcher->match('/bar/foo'));
        $this->assertEquals(array('_route' => 'bar', 'bar' => 'foo'), $matcher->match('/foo/foo'));

        $collection = new RouteCollection();
        $collection->add('bar', new Route('/{bar}', array('bar' => 'bar'), array('bar' => 'foo|bar')));
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'bar', 'bar' => 'foo'), $matcher->match('/foo'));
        $this->assertEquals(array('_route' => 'bar', 'bar' => 'bar'), $matcher->match('/'));

        // route with only optional variables
        $collection = new RouteCollection();
        $collection->add('bar', new Route('/{foo}/{bar}', array('foo' => 'foo', 'bar' => 'bar'), array()));
        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'bar', 'foo' => 'foo', 'bar' => 'bar'), $matcher->match('/'));
        $this->assertEquals(array('_route' => 'bar', 'foo' => 'a', 'bar' => 'bar'), $matcher->match('/a'));
        $this->assertEquals(array('_route' => 'bar', 'foo' => 'a', 'bar' => 'b'), $matcher->match('/a/b'));
    }

    public function testMatchWithPrefixes()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{foo}'));
        $collection->addPrefix('/b');
        $collection->addPrefix('/a');

        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'foo', 'foo' => 'foo'), $matcher->match('/a/b/foo'));
    }

    public function testMatchWithDynamicPrefix()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{foo}'));
        $collection->addPrefix('/b');
        $collection->addPrefix('/{_locale}');

        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_locale' => 'fr', '_route' => 'foo', 'foo' => 'foo'), $matcher->match('/fr/b/foo'));
    }

    public function testMatchSpecialRouteName()
    {
        $collection = new RouteCollection();
        $collection->add('$péß^a|', new Route('/bar'));

        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => '$péß^a|'), $matcher->match('/bar'));
    }

    public function testMatchNonAlpha()
    {
        $collection = new RouteCollection();
        $chars = '!"$%éà &\'()*+,./:;<=>@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\[]^_`abcdefghijklmnopqrstuvwxyz{|}~-';
        $collection->add('foo', new Route('/{foo}/bar', array(), array('foo' => '['.preg_quote($chars).']+')));

        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'foo', 'foo' => $chars), $matcher->match('/'.rawurlencode($chars).'/bar'));
        $this->assertEquals(array('_route' => 'foo', 'foo' => $chars), $matcher->match('/'.strtr($chars, array('%' => '%25')).'/bar'));
    }

    public function testMatchWithDotMetacharacterInRequirements()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{foo}/bar', array(), array('foo' => '.+')));

        $matcher = new UrlMatcher($collection, new RequestContext());
        $this->assertEquals(array('_route' => 'foo', 'foo' => "\n"), $matcher->match('/'.urlencode("\n").'/bar'), 'linefeed character is matched');
    }

    public function testMatchOverriddenRoute()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('foo', new Route('/foo1'));

        $collection->addCollection($collection1);

        $matcher = new UrlMatcher($collection, new RequestContext());

        $this->assertEquals(array('_route' => 'foo'), $matcher->match('/foo1'));
        $this->setExpectedException('Symfony\Component\Routing\Exception\ResourceNotFoundException');
        $this->assertEquals(array(), $matcher->match('/foo'));
    }

    public function testMatchRegression()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/{foo}'));
        $coll->add('bar', new Route('/foo/bar/{foo}'));

        $matcher = new UrlMatcher($coll, new RequestContext());
        $this->assertEquals(array('foo' => 'bar', '_route' => 'bar'), $matcher->match('/foo/bar/bar'));

        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{bar}'));
        $matcher = new UrlMatcher($collection, new RequestContext());
        try {
            $matcher->match('/');
            $this->fail();
        } catch (ResourceNotFoundException $e) {
        }
    }

    public function testDefaultRequirementForOptionalVariables()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{page}.{_format}', array('page' => 'index', '_format' => 'html')));

        $matcher = new UrlMatcher($coll, new RequestContext());
        $this->assertEquals(array('page' => 'my-page', '_format' => 'xml', '_route' => 'test'), $matcher->match('/my-page.xml'));
    }

    public function testMatchingIsEager()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{foo}-{bar}-', array(), array('foo' => '.+', 'bar' => '.+')));

        $matcher = new UrlMatcher($coll, new RequestContext());
        $this->assertEquals(array('foo' => 'text1-text2-text3', 'bar' => 'text4', '_route' => 'test'), $matcher->match('/text1-text2-text3-text4-'));
    }

    public function testAdjacentVariables()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{w}{x}{y}{z}.{_format}', array('z' => 'default-z', '_format' => 'html'), array('y' => 'y|Y')));

        $matcher = new UrlMatcher($coll, new RequestContext());
        // 'w' eagerly matches as much as possible and the other variables match the remaining chars.
        // This also shows that the variables w-z must all exclude the separating char (the dot '.' in this case) by default requirement.
        // Otherwise they would also consume '.xml' and _format would never match as it's an optional variable.
        $this->assertEquals(array('w' => 'wwwww', 'x' => 'x', 'y' => 'Y', 'z' => 'Z','_format' => 'xml', '_route' => 'test'), $matcher->match('/wwwwwxYZ.xml'));
        // As 'y' has custom requirement and can only be of value 'y|Y', it will leave  'ZZZ' to variable z.
        // So with carefully chosen requirements adjacent variables, can be useful.
        $this->assertEquals(array('w' => 'wwwww', 'x' => 'x', 'y' => 'y', 'z' => 'ZZZ','_format' => 'html', '_route' => 'test'), $matcher->match('/wwwwwxyZZZ'));
        // z and _format are optional.
        $this->assertEquals(array('w' => 'wwwww', 'x' => 'x', 'y' => 'y', 'z' => 'default-z','_format' => 'html', '_route' => 'test'), $matcher->match('/wwwwwxy'));

        $this->setExpectedException('Symfony\Component\Routing\Exception\ResourceNotFoundException');
        $matcher->match('/wxy.html');
    }

    public function testOptionalVariableWithNoRealSeparator()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/get{what}', array('what' => 'All')));
        $matcher = new UrlMatcher($coll, new RequestContext());

        $this->assertEquals(array('what' => 'All', '_route' => 'test'), $matcher->match('/get'));
        $this->assertEquals(array('what' => 'Sites', '_route' => 'test'), $matcher->match('/getSites'));

        // Usually the character in front of an optional parameter can be left out, e.g. with pattern '/get/{what}' just '/get' would match.
        // But here the 't' in 'get' is not a separating character, so it makes no sense to match without it.
        $this->setExpectedException('Symfony\Component\Routing\Exception\ResourceNotFoundException');
        $matcher->match('/ge');
    }

    public function testRequiredVariableWithNoRealSeparator()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/get{what}Suffix'));
        $matcher = new UrlMatcher($coll, new RequestContext());

        $this->assertEquals(array('what' => 'Sites', '_route' => 'test'), $matcher->match('/getSitesSuffix'));
    }

    public function testDefaultRequirementOfVariable()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{page}.{_format}'));
        $matcher = new UrlMatcher($coll, new RequestContext());

        $this->assertEquals(array('page' => 'index', '_format' => 'mobile.html', '_route' => 'test'), $matcher->match('/index.mobile.html'));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testDefaultRequirementOfVariableDisallowsSlash()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{page}.{_format}'));
        $matcher = new UrlMatcher($coll, new RequestContext());

        $matcher->match('/index.sl/ash');
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testDefaultRequirementOfVariableDisallowsNextSeparator()
    {
        $coll = new RouteCollection();
        $coll->add('test', new Route('/{page}.{_format}', array(), array('_format' => 'html|xml')));
        $matcher = new UrlMatcher($coll, new RequestContext());

        $matcher->match('/do.t.html');
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testSchemeRequirement()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', array(), array('_scheme' => 'https')));
        $matcher = new UrlMatcher($coll, new RequestContext());
        $matcher->match('/foo');
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testCondition()
    {
        $coll = new RouteCollection();
        $route = new Route('/foo');
        $route->setCondition('context.getMethod() == "POST"');
        $coll->add('foo', $route);
        $matcher = new UrlMatcher($coll, new RequestContext());
        $matcher->match('/foo');
    }

    public function testDecodeOnce()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/{foo}'));

        $matcher = new UrlMatcher($coll, new RequestContext());
        $this->assertEquals(array('foo' => 'bar%23', '_route' => 'foo'), $matcher->match('/foo/bar%2523'));
    }

    public function testCannotRelyOnPrefix()
    {
        $coll = new RouteCollection();

        $subColl = new RouteCollection();
        $subColl->add('bar', new Route('/bar'));
        $subColl->addPrefix('/prefix');
        // overwrite the pattern, so the prefix is not valid anymore for this route in the collection
        $subColl->get('bar')->setPattern('/new');

        $coll->addCollection($subColl);

        $matcher = new UrlMatcher($coll, new RequestContext());
        $this->assertEquals(array('_route' => 'bar'), $matcher->match('/new'));
    }

    public function testWithHost()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/{foo}', array(), array(), array(), '{locale}.example.com'));

        $matcher = new UrlMatcher($coll, new RequestContext('', 'GET', 'en.example.com'));
        $this->assertEquals(array('foo' => 'bar', '_route' => 'foo', 'locale' => 'en'), $matcher->match('/foo/bar'));
    }

    public function testWithHostOnRouteCollection()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/{foo}'));
        $coll->add('bar', new Route('/bar/{foo}', array(), array(), array(), '{locale}.example.net'));
        $coll->setHost('{locale}.example.com');

        $matcher = new UrlMatcher($coll, new RequestContext('', 'GET', 'en.example.com'));
        $this->assertEquals(array('foo' => 'bar', '_route' => 'foo', 'locale' => 'en'), $matcher->match('/foo/bar'));

        $matcher = new UrlMatcher($coll, new RequestContext('', 'GET', 'en.example.com'));
        $this->assertEquals(array('foo' => 'bar', '_route' => 'bar', 'locale' => 'en'), $matcher->match('/bar/bar'));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testWithOutHostHostDoesNotMatch()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/{foo}', array(), array(), array(), '{locale}.example.com'));

        $matcher = new UrlMatcher($coll, new RequestContext('', 'GET', 'example.com'));
        $matcher->match('/foo/bar');
    }
}
PK(1[ȁ@���URouting/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperPrefixCollectionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher\Dumper;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Matcher\Dumper\DumperPrefixCollection;
use Symfony\Component\Routing\Matcher\Dumper\DumperRoute;
use Symfony\Component\Routing\Matcher\Dumper\DumperCollection;

class DumperPrefixCollectionTest extends \PHPUnit_Framework_TestCase
{
    public function testAddPrefixRoute()
    {
        $coll = new DumperPrefixCollection();
        $coll->setPrefix('');

        $route = new DumperRoute('bar', new Route('/foo/bar'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('bar2', new Route('/foo/bar'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('qux', new Route('/foo/qux'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('bar3', new Route('/foo/bar'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('bar4', new Route(''));
        $result = $coll->addPrefixRoute($route);

        $expect = <<<'EOF'
            |-coll /
            | |-coll /f
            | | |-coll /fo
            | | | |-coll /foo
            | | | | |-coll /foo/
            | | | | | |-coll /foo/b
            | | | | | | |-coll /foo/ba
            | | | | | | | |-coll /foo/bar
            | | | | | | | | |-route bar /foo/bar
            | | | | | | | | |-route bar2 /foo/bar
            | | | | | |-coll /foo/q
            | | | | | | |-coll /foo/qu
            | | | | | | | |-coll /foo/qux
            | | | | | | | | |-route qux /foo/qux
            | | | | | |-coll /foo/b
            | | | | | | |-coll /foo/ba
            | | | | | | | |-coll /foo/bar
            | | | | | | | | |-route bar3 /foo/bar
            | |-route bar4 /

EOF;

        $this->assertSame($expect, $this->collectionToString($result->getRoot(), '            '));
    }

    public function testMergeSlashNodes()
    {
        $coll = new DumperPrefixCollection();
        $coll->setPrefix('');

        $route = new DumperRoute('bar', new Route('/foo/bar'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('bar2', new Route('/foo/bar'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('qux', new Route('/foo/qux'));
        $coll = $coll->addPrefixRoute($route);

        $route = new DumperRoute('bar3', new Route('/foo/bar'));
        $result = $coll->addPrefixRoute($route);

        $result->getRoot()->mergeSlashNodes();

        $expect = <<<'EOF'
            |-coll /f
            | |-coll /fo
            | | |-coll /foo
            | | | |-coll /foo/b
            | | | | |-coll /foo/ba
            | | | | | |-coll /foo/bar
            | | | | | | |-route bar /foo/bar
            | | | | | | |-route bar2 /foo/bar
            | | | |-coll /foo/q
            | | | | |-coll /foo/qu
            | | | | | |-coll /foo/qux
            | | | | | | |-route qux /foo/qux
            | | | |-coll /foo/b
            | | | | |-coll /foo/ba
            | | | | | |-coll /foo/bar
            | | | | | | |-route bar3 /foo/bar

EOF;

        $this->assertSame($expect, $this->collectionToString($result->getRoot(), '            '));
    }

    private function collectionToString(DumperCollection $collection, $prefix)
    {
        $string = '';
        foreach ($collection as $route) {
            if ($route instanceof DumperCollection) {
                $string .= sprintf("%s|-coll %s\n", $prefix, $route->getPrefix());
                $string .= $this->collectionToString($route, $prefix.'| ');
            } else {
                $string .= sprintf("%s|-route %s %s\n", $prefix, $route->getName(), $route->getRoute()->getPath());
            }
        }

        return $string;
    }
}
PK(1[)�#0%%ORouting/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher\Dumper;

use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class PhpMatcherDumperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     */
    public function testDumpWhenSchemeIsUsedWithoutAProperDumper()
    {
        $collection = new RouteCollection();
        $collection->add('secure', new Route(
            '/secure',
            array(),
            array('_scheme' => 'https')
        ));
        $dumper = new PhpMatcherDumper($collection);
        $dumper->dump();
    }

    /**
     * @dataProvider getRouteCollections
     */
    public function testDump(RouteCollection $collection, $fixture, $options = array())
    {
        $basePath = __DIR__.'/../../Fixtures/dumper/';

        $dumper = new PhpMatcherDumper($collection);
        $this->assertStringEqualsFile($basePath.$fixture, $dumper->dump($options), '->dump() correctly dumps routes as optimized PHP code.');
    }

    public function getRouteCollections()
    {
        /* test case 1 */

        $collection = new RouteCollection();

        $collection->add('overridden', new Route('/overridden'));

        // defaults and requirements
        $collection->add('foo', new Route(
            '/foo/{bar}',
            array('def' => 'test'),
            array('bar' => 'baz|symfony')
        ));
        // method requirement
        $collection->add('bar', new Route(
            '/bar/{foo}',
            array(),
            array('_method' => 'GET|head')
        ));
        // GET method requirement automatically adds HEAD as valid
        $collection->add('barhead', new Route(
            '/barhead/{foo}',
            array(),
            array('_method' => 'GET')
        ));
        // simple
        $collection->add('baz', new Route(
            '/test/baz'
        ));
        // simple with extension
        $collection->add('baz2', new Route(
            '/test/baz.html'
        ));
        // trailing slash
        $collection->add('baz3', new Route(
            '/test/baz3/'
        ));
        // trailing slash with variable
        $collection->add('baz4', new Route(
            '/test/{foo}/'
        ));
        // trailing slash and method
        $collection->add('baz5', new Route(
            '/test/{foo}/',
            array(),
            array('_method' => 'post')
        ));
        // complex name
        $collection->add('baz.baz6', new Route(
            '/test/{foo}/',
            array(),
            array('_method' => 'put')
        ));
        // defaults without variable
        $collection->add('foofoo', new Route(
            '/foofoo',
            array('def' => 'test')
        ));
        // pattern with quotes
        $collection->add('quoter', new Route(
            '/{quoter}',
            array(),
            array('quoter' => '[\']+')
        ));
        // space in pattern
        $collection->add('space', new Route(
            '/spa ce'
        ));

        // prefixes
        $collection1 = new RouteCollection();
        $collection1->add('overridden', new Route('/overridden1'));
        $collection1->add('foo1', new Route('/{foo}'));
        $collection1->add('bar1', new Route('/{bar}'));
        $collection1->addPrefix('/b\'b');
        $collection2 = new RouteCollection();
        $collection2->addCollection($collection1);
        $collection2->add('overridden', new Route('/{var}', array(), array('var' => '.*')));
        $collection1 = new RouteCollection();
        $collection1->add('foo2', new Route('/{foo1}'));
        $collection1->add('bar2', new Route('/{bar1}'));
        $collection1->addPrefix('/b\'b');
        $collection2->addCollection($collection1);
        $collection2->addPrefix('/a');
        $collection->addCollection($collection2);

        // overridden through addCollection() and multiple sub-collections with no own prefix
        $collection1 = new RouteCollection();
        $collection1->add('overridden2', new Route('/old'));
        $collection1->add('helloWorld', new Route('/hello/{who}', array('who' => 'World!')));
        $collection2 = new RouteCollection();
        $collection3 = new RouteCollection();
        $collection3->add('overridden2', new Route('/new'));
        $collection3->add('hey', new Route('/hey/'));
        $collection2->addCollection($collection3);
        $collection1->addCollection($collection2);
        $collection1->addPrefix('/multi');
        $collection->addCollection($collection1);

        // "dynamic" prefix
        $collection1 = new RouteCollection();
        $collection1->add('foo3', new Route('/{foo}'));
        $collection1->add('bar3', new Route('/{bar}'));
        $collection1->addPrefix('/b');
        $collection1->addPrefix('{_locale}');
        $collection->addCollection($collection1);

        // route between collections
        $collection->add('ababa', new Route('/ababa'));

        // collection with static prefix but only one route
        $collection1 = new RouteCollection();
        $collection1->add('foo4', new Route('/{foo}'));
        $collection1->addPrefix('/aba');
        $collection->addCollection($collection1);

        // prefix and host

        $collection1 = new RouteCollection();

        $route1 = new Route('/route1', array(), array(), array(), 'a.example.com');
        $collection1->add('route1', $route1);

        $collection2 = new RouteCollection();

        $route2 = new Route('/c2/route2', array(), array(), array(), 'a.example.com');
        $collection1->add('route2', $route2);

        $route3 = new Route('/c2/route3', array(), array(), array(), 'b.example.com');
        $collection1->add('route3', $route3);

        $route4 = new Route('/route4', array(), array(), array(), 'a.example.com');
        $collection1->add('route4', $route4);

        $route5 = new Route('/route5', array(), array(), array(), 'c.example.com');
        $collection1->add('route5', $route5);

        $route6 = new Route('/route6', array(), array(), array(), null);
        $collection1->add('route6', $route6);

        $collection->addCollection($collection1);

        // host and variables

        $collection1 = new RouteCollection();

        $route11 = new Route('/route11', array(), array(), array(), '{var1}.example.com');
        $collection1->add('route11', $route11);

        $route12 = new Route('/route12', array('var1' => 'val'), array(), array(), '{var1}.example.com');
        $collection1->add('route12', $route12);

        $route13 = new Route('/route13/{name}', array(), array(), array(), '{var1}.example.com');
        $collection1->add('route13', $route13);

        $route14 = new Route('/route14/{name}', array('var1' => 'val'), array(), array(), '{var1}.example.com');
        $collection1->add('route14', $route14);

        $route15 = new Route('/route15/{name}', array(), array(), array(), 'c.example.com');
        $collection1->add('route15', $route15);

        $route16 = new Route('/route16/{name}', array('var1' => 'val'), array(), array(), null);
        $collection1->add('route16', $route16);

        $route17 = new Route('/route17', array(), array(), array(), null);
        $collection1->add('route17', $route17);

        $collection->addCollection($collection1);

        // multiple sub-collections with a single route and a prefix each
        $collection1 = new RouteCollection();
        $collection1->add('a', new Route('/a...'));
        $collection2 = new RouteCollection();
        $collection2->add('b', new Route('/{var}'));
        $collection3 = new RouteCollection();
        $collection3->add('c', new Route('/{var}'));
        $collection3->addPrefix('/c');
        $collection2->addCollection($collection3);
        $collection2->addPrefix('/b');
        $collection1->addCollection($collection2);
        $collection1->addPrefix('/a');
        $collection->addCollection($collection1);

        /* test case 2 */

        $redirectCollection = clone $collection;

        // force HTTPS redirection
        $redirectCollection->add('secure', new Route(
            '/secure',
            array(),
            array('_scheme' => 'https')
        ));

        // force HTTP redirection
        $redirectCollection->add('nonsecure', new Route(
            '/nonsecure',
            array(),
            array('_scheme' => 'http')
        ));

        /* test case 3 */

        $rootprefixCollection = new RouteCollection();
        $rootprefixCollection->add('static', new Route('/test'));
        $rootprefixCollection->add('dynamic', new Route('/{var}'));
        $rootprefixCollection->addPrefix('rootprefix');
        $route = new Route('/with-condition');
        $route->setCondition('context.getMethod() == "GET"');
        $rootprefixCollection->add('with-condition', $route);

        return array(
           array($collection, 'url_matcher1.php', array()),
           array($redirectCollection, 'url_matcher2.php', array('base_class' => 'Symfony\Component\Routing\Tests\Fixtures\RedirectableUrlMatcher')),
           array($rootprefixCollection, 'url_matcher3.php', array())
        );
    }
}
PK(1[U���ORouting/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperCollectionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher\Dumper;

use Symfony\Component\Routing\Matcher\Dumper\DumperCollection;

class DumperCollectionTest extends \PHPUnit_Framework_TestCase
{
    public function testGetRoot()
    {
        $a = new DumperCollection();

        $b = new DumperCollection();
        $a->add($b);

        $c = new DumperCollection();
        $b->add($c);

        $d = new DumperCollection();
        $c->add($d);

        $this->assertSame($a, $c->getRoot());
    }
}
PK(1[�IQ��RRouting/Symfony/Component/Routing/Tests/Matcher/Dumper/ApacheMatcherDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher\Dumper;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Matcher\Dumper\ApacheMatcherDumper;

class ApacheMatcherDumperTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../../Fixtures/');
    }

    public function testDump()
    {
        $dumper = new ApacheMatcherDumper($this->getRouteCollection());

        $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher1.apache', $dumper->dump(), '->dump() dumps basic routes to the correct apache format.');
    }

    /**
     * @dataProvider provideEscapeFixtures
     */
    public function testEscapePattern($src, $dest, $char, $with, $message)
    {
        $r = new \ReflectionMethod(new ApacheMatcherDumper($this->getRouteCollection()), 'escape');
        $r->setAccessible(true);
        $this->assertEquals($dest, $r->invoke(null, $src, $char, $with), $message);
    }

    public function provideEscapeFixtures()
    {
        return array(
            array('foo', 'foo', ' ', '-', 'Preserve string that should not be escaped'),
            array('fo-o', 'fo-o', ' ', '-', 'Preserve string that should not be escaped'),
            array('fo o', 'fo- o', ' ', '-', 'Escape special characters'),
            array('fo-- o', 'fo--- o', ' ', '-', 'Escape special characters'),
            array('fo- o', 'fo- o', ' ', '-', 'Do not escape already escaped string'),
        );
    }

    public function testEscapeScriptName()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));
        $dumper = new ApacheMatcherDumper($collection);
        $this->assertStringEqualsFile(self::$fixturesPath.'/dumper/url_matcher2.apache', $dumper->dump(array('script_name' => 'ap p_d\ ev.php')));
    }

    private function getRouteCollection()
    {
        $collection = new RouteCollection();

        // defaults and requirements
        $collection->add('foo', new Route(
            '/foo/{bar}',
            array('def' => 'test'),
            array('bar' => 'baz|symfony')
        ));
        // defaults parameters in pattern
        $collection->add('foobar', new Route(
            '/foo/{bar}',
            array('bar' => 'toto')
        ));
        // method requirement
        $collection->add('bar', new Route(
            '/bar/{foo}',
            array(),
            array('_method' => 'GET|head')
        ));
        // method requirement (again)
        $collection->add('baragain', new Route(
            '/baragain/{foo}',
            array(),
            array('_method' => 'get|post')
        ));
        // simple
        $collection->add('baz', new Route(
            '/test/baz'
        ));
        // simple with extension
        $collection->add('baz2', new Route(
            '/test/baz.html'
        ));
        // trailing slash
        $collection->add('baz3', new Route(
            '/test/baz3/'
        ));
        // trailing slash with variable
        $collection->add('baz4', new Route(
            '/test/{foo}/'
        ));
        // trailing slash and safe method
        $collection->add('baz5', new Route(
            '/test/{foo}/',
            array(),
            array('_method' => 'get')
        ));
        // trailing slash and unsafe method
        $collection->add('baz5unsafe', new Route(
            '/testunsafe/{foo}/',
            array(),
            array('_method' => 'post')
        ));
        // complex
        $collection->add('baz6', new Route(
            '/test/baz',
            array('foo' => 'bar baz')
        ));
        // space in path
        $collection->add('baz7', new Route(
            '/te st/baz'
        ));
        // space preceded with \ in path
        $collection->add('baz8', new Route(
            '/te\\ st/baz'
        ));
        // space preceded with \ in requirement
        $collection->add('baz9', new Route(
            '/test/{baz}',
            array(),
            array(
                'baz' => 'te\\\\ st',
            )
        ));

        $collection1 = new RouteCollection();

        $route1 = new Route('/route1', array(), array(), array(), 'a.example.com');
        $collection1->add('route1', $route1);

        $collection2 = new RouteCollection();

        $route2 = new Route('/route2', array(), array(), array(), 'a.example.com');
        $collection2->add('route2', $route2);

        $route3 = new Route('/route3', array(), array(), array(), 'b.example.com');
        $collection2->add('route3', $route3);

        $collection2->addPrefix('/c2');
        $collection1->addCollection($collection2);

        $route4 = new Route('/route4', array(), array(), array(), 'a.example.com');
        $collection1->add('route4', $route4);

        $route5 = new Route('/route5', array(), array(), array(), 'c.example.com');
        $collection1->add('route5', $route5);

        $route6 = new Route('/route6', array(), array(), array(), null);
        $collection1->add('route6', $route6);

        $collection->addCollection($collection1);

        // host and variables

        $collection1 = new RouteCollection();

        $route11 = new Route('/route11', array(), array(), array(), '{var1}.example.com');
        $collection1->add('route11', $route11);

        $route12 = new Route('/route12', array('var1' => 'val'), array(), array(), '{var1}.example.com');
        $collection1->add('route12', $route12);

        $route13 = new Route('/route13/{name}', array(), array(), array(), '{var1}.example.com');
        $collection1->add('route13', $route13);

        $route14 = new Route('/route14/{name}', array('var1' => 'val'), array(), array(), '{var1}.example.com');
        $collection1->add('route14', $route14);

        $route15 = new Route('/route15/{name}', array(), array(), array(), 'c.example.com');
        $collection1->add('route15', $route15);

        $route16 = new Route('/route16/{name}', array('var1' => 'val'), array(), array(), null);
        $collection1->add('route16', $route16);

        $route17 = new Route('/route17', array(), array(), array(), null);
        $collection1->add('route17', $route17);

        $collection->addCollection($collection1);

        return $collection;
    }
}
PK(1[�̼�aaHRouting/Symfony/Component/Routing/Tests/Matcher/ApacheUrlMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Matcher\ApacheUrlMatcher;

class ApacheUrlMatcherTest extends \PHPUnit_Framework_TestCase
{
    protected $server;

    protected function setUp()
    {
        $this->server = $_SERVER;
    }

    protected function tearDown()
    {
        $_SERVER = $this->server;
    }

    /**
     * @dataProvider getMatchData
     */
    public function testMatch($name, $pathinfo, $server, $expect)
    {
        $collection = new RouteCollection();
        $context = new RequestContext();
        $matcher = new ApacheUrlMatcher($collection, $context);

        $_SERVER = $server;

        $result = $matcher->match($pathinfo, $server);
        $this->assertSame(var_export($expect, true), var_export($result, true));
    }

    public function getMatchData()
    {
        return array(
            array(
                'Simple route',
                '/hello/world',
                array(
                    '_ROUTING_route' => 'hello',
                    '_ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    '_ROUTING_param_name' => 'world',
                ),
                array(
                    '_controller' => 'AcmeBundle:Default:index',
                    'name' => 'world',
                    '_route' => 'hello',
                ),
            ),
            array(
                'Route with params and defaults',
                '/hello/hugo',
                array(
                    '_ROUTING_route' => 'hello',
                    '_ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    '_ROUTING_param_name' => 'hugo',
                    '_ROUTING_default_name' => 'world',
                ),
                array(
                    'name' => 'hugo',
                    '_controller' => 'AcmeBundle:Default:index',
                    '_route' => 'hello',
                ),
            ),
            array(
                'Route with defaults only',
                '/hello',
                array(
                    '_ROUTING_route' => 'hello',
                    '_ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    '_ROUTING_default_name' => 'world',
                ),
                array(
                    'name' => 'world',
                    '_controller' => 'AcmeBundle:Default:index',
                    '_route' => 'hello',
                ),
            ),
            array(
                'Redirect with many ignored attributes',
                '/legacy/{cat1}/{cat2}/{id}.html',
                array(
                    '_ROUTING_route' => 'product_view',
                    '_ROUTING_param__controller' => 'FrameworkBundle:Redirect:redirect',
                    '_ROUTING_default_ignoreAttributes[0]' => 'attr_a',
                    '_ROUTING_default_ignoreAttributes[1]' => 'attr_b',
                ),
                array(
                    'ignoreAttributes' => array('attr_a', 'attr_b'),
                    '_controller' => 'FrameworkBundle:Redirect:redirect',
                    '_route' => 'product_view',
                )
            ),
            array(
                'REDIRECT_ envs',
                '/hello/world',
                array(
                    'REDIRECT__ROUTING_route' => 'hello',
                    'REDIRECT__ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    'REDIRECT__ROUTING_param_name' => 'world',
                ),
                array(
                    '_controller' => 'AcmeBundle:Default:index',
                    'name' => 'world',
                    '_route' => 'hello',
                ),
            ),
            array(
                'REDIRECT_REDIRECT_ envs',
                '/hello/world',
                array(
                    'REDIRECT_REDIRECT__ROUTING_route' => 'hello',
                    'REDIRECT_REDIRECT__ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    'REDIRECT_REDIRECT__ROUTING_param_name' => 'world',
                ),
                array(
                    '_controller' => 'AcmeBundle:Default:index',
                    'name' => 'world',
                    '_route' => 'hello',
                ),
            ),
            array(
                'REDIRECT_REDIRECT_ envs',
                '/hello/world',
                array(
                    'REDIRECT_REDIRECT__ROUTING_route' => 'hello',
                    'REDIRECT_REDIRECT__ROUTING_param__controller' => 'AcmeBundle:Default:index',
                    'REDIRECT_REDIRECT__ROUTING_param_name' => 'world',
                ),
                array(
                    '_controller' => 'AcmeBundle:Default:index',
                    'name' => 'world',
                    '_route' => 'hello',
                ),
            )
        );
    }
}
PK(1[A ���NRouting/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Matcher;

use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;

class RedirectableUrlMatcherTest extends \PHPUnit_Framework_TestCase
{
    public function testRedirectWhenNoSlash()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/'));

        $matcher = $this->getMockForAbstractClass('Symfony\Component\Routing\Matcher\RedirectableUrlMatcher', array($coll, new RequestContext()));
        $matcher->expects($this->once())->method('redirect');
        $matcher->match('/foo');
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException
     */
    public function testRedirectWhenNoSlashForNonSafeMethod()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo/'));

        $context = new RequestContext();
        $context->setMethod('POST');
        $matcher = $this->getMockForAbstractClass('Symfony\Component\Routing\Matcher\RedirectableUrlMatcher', array($coll, $context));
        $matcher->match('/foo');
    }

    public function testSchemeRedirect()
    {
        $coll = new RouteCollection();
        $coll->add('foo', new Route('/foo', array(), array('_scheme' => 'https')));

        $matcher = $this->getMockForAbstractClass('Symfony\Component\Routing\Matcher\RedirectableUrlMatcher', array($coll, new RequestContext()));
        $matcher
            ->expects($this->once())
            ->method('redirect')
            ->with('/foo', 'foo', 'https')
            ->will($this->returnValue(array('_route' => 'foo')))
        ;
        $matcher->match('/foo');
    }
}
PK(1[%"�?7?7?Routing/Symfony/Component/Routing/Tests/RouteCollectionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Config\Resource\FileResource;

class RouteCollectionTest extends \PHPUnit_Framework_TestCase
{
    public function testRoute()
    {
        $collection = new RouteCollection();
        $route = new Route('/foo');
        $collection->add('foo', $route);
        $this->assertEquals(array('foo' => $route), $collection->all(), '->add() adds a route');
        $this->assertEquals($route, $collection->get('foo'), '->get() returns a route by name');
        $this->assertNull($collection->get('bar'), '->get() returns null if a route does not exist');
    }

    public function testOverriddenRoute()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));
        $collection->add('foo', new Route('/foo1'));

        $this->assertEquals('/foo1', $collection->get('foo')->getPath());
    }

    public function testDeepOverriddenRoute()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('foo', new Route('/foo1'));

        $collection2 = new RouteCollection();
        $collection2->add('foo', new Route('/foo2'));

        $collection1->addCollection($collection2);
        $collection->addCollection($collection1);

        $this->assertEquals('/foo2', $collection1->get('foo')->getPath());
        $this->assertEquals('/foo2', $collection->get('foo')->getPath());
    }

    public function testIterator()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('bar', $bar = new Route('/bar'));
        $collection1->add('foo', $foo = new Route('/foo-new'));
        $collection->addCollection($collection1);
        $collection->add('last', $last = new Route('/last'));

        $this->assertInstanceOf('\ArrayIterator', $collection->getIterator());
        $this->assertSame(array('bar' => $bar, 'foo' => $foo, 'last' => $last), $collection->getIterator()->getArrayCopy());
    }

    public function testCount()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('bar', new Route('/bar'));
        $collection->addCollection($collection1);

        $this->assertCount(2, $collection);
    }

    public function testAddCollection()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('bar', $bar = new Route('/bar'));
        $collection1->add('foo', $foo = new Route('/foo-new'));

        $collection2 = new RouteCollection();
        $collection2->add('grandchild', $grandchild = new Route('/grandchild'));

        $collection1->addCollection($collection2);
        $collection->addCollection($collection1);
        $collection->add('last', $last = new Route('/last'));

        $this->assertSame(array('bar' => $bar, 'foo' => $foo, 'grandchild' => $grandchild, 'last' => $last), $collection->all(),
            '->addCollection() imports routes of another collection, overrides if necessary and adds them at the end');
    }

    public function testAddCollectionWithResources()
    {
        $collection = new RouteCollection();
        $collection->addResource($foo = new FileResource(__DIR__.'/Fixtures/foo.xml'));
        $collection1 = new RouteCollection();
        $collection1->addResource($foo1 = new FileResource(__DIR__.'/Fixtures/foo1.xml'));
        $collection->addCollection($collection1);
        $this->assertEquals(array($foo, $foo1), $collection->getResources(), '->addCollection() merges resources');
    }

    public function testAddDefaultsAndRequirementsAndOptions()
    {
        $collection = new RouteCollection();
        $collection->add('foo', new Route('/{placeholder}'));
        $collection1 = new RouteCollection();
        $collection1->add('bar', new Route('/{placeholder}',
            array('_controller' => 'fixed', 'placeholder' => 'default'), array('placeholder' => '.+'), array('option' => 'value'))
        );
        $collection->addCollection($collection1);

        $collection->addDefaults(array('placeholder' => 'new-default'));
        $this->assertEquals(array('placeholder' => 'new-default'), $collection->get('foo')->getDefaults(), '->addDefaults() adds defaults to all routes');
        $this->assertEquals(array('_controller' => 'fixed', 'placeholder' => 'new-default'), $collection->get('bar')->getDefaults(),
            '->addDefaults() adds defaults to all routes and overwrites existing ones');

        $collection->addRequirements(array('placeholder' => '\d+'));
        $this->assertEquals(array('placeholder' => '\d+'), $collection->get('foo')->getRequirements(), '->addRequirements() adds requirements to all routes');
        $this->assertEquals(array('placeholder' => '\d+'), $collection->get('bar')->getRequirements(),
            '->addRequirements() adds requirements to all routes and overwrites existing ones');

        $collection->addOptions(array('option' => 'new-value'));
        $this->assertEquals(
            array('option' => 'new-value', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'),
            $collection->get('bar')->getOptions(), '->addOptions() adds options to all routes and overwrites existing ones'
        );
    }

    public function testAddPrefix()
    {
        $collection = new RouteCollection();
        $collection->add('foo', $foo = new Route('/foo'));
        $collection2 = new RouteCollection();
        $collection2->add('bar', $bar = new Route('/bar'));
        $collection->addCollection($collection2);
        $collection->addPrefix(' / ');
        $this->assertSame('/foo', $collection->get('foo')->getPattern(), '->addPrefix() trims the prefix and a single slash has no effect');
        $collection->addPrefix('/{admin}', array('admin' => 'admin'), array('admin' => '\d+'));
        $this->assertEquals('/{admin}/foo', $collection->get('foo')->getPath(), '->addPrefix() adds a prefix to all routes');
        $this->assertEquals('/{admin}/bar', $collection->get('bar')->getPath(), '->addPrefix() adds a prefix to all routes');
        $this->assertEquals(array('admin' => 'admin'), $collection->get('foo')->getDefaults(), '->addPrefix() adds defaults to all routes');
        $this->assertEquals(array('admin' => 'admin'), $collection->get('bar')->getDefaults(), '->addPrefix() adds defaults to all routes');
        $this->assertEquals(array('admin' => '\d+'), $collection->get('foo')->getRequirements(), '->addPrefix() adds requirements to all routes');
        $this->assertEquals(array('admin' => '\d+'), $collection->get('bar')->getRequirements(), '->addPrefix() adds requirements to all routes');
        $collection->addPrefix('0');
        $this->assertEquals('/0/{admin}/foo', $collection->get('foo')->getPattern(), '->addPrefix() ensures a prefix must start with a slash and must not end with a slash');
        $collection->addPrefix('/ /');
        $this->assertSame('/ /0/{admin}/foo', $collection->get('foo')->getPath(), '->addPrefix() can handle spaces if desired');
        $this->assertSame('/ /0/{admin}/bar', $collection->get('bar')->getPath(), 'the route pattern of an added collection is in synch with the added prefix');
    }

    public function testAddPrefixOverridesDefaultsAndRequirements()
    {
        $collection = new RouteCollection();
        $collection->add('foo', $foo = new Route('/foo'));
        $collection->add('bar', $bar = new Route('/bar', array(), array('_scheme' => 'http')));
        $collection->addPrefix('/admin', array(), array('_scheme' => 'https'));

        $this->assertEquals('https', $collection->get('foo')->getRequirement('_scheme'), '->addPrefix() overrides existing requirements');
        $this->assertEquals('https', $collection->get('bar')->getRequirement('_scheme'), '->addPrefix() overrides existing requirements');
    }

    public function testResource()
    {
        $collection = new RouteCollection();
        $collection->addResource($foo = new FileResource(__DIR__.'/Fixtures/foo.xml'));
        $collection->addResource($bar = new FileResource(__DIR__.'/Fixtures/bar.xml'));
        $collection->addResource(new FileResource(__DIR__.'/Fixtures/foo.xml'));

        $this->assertEquals(array($foo, $bar), $collection->getResources(),
            '->addResource() adds a resource and getResources() only returns unique ones by comparing the string representation');
    }

    public function testUniqueRouteWithGivenName()
    {
        $collection1 = new RouteCollection();
        $collection1->add('foo', new Route('/old'));
        $collection2 = new RouteCollection();
        $collection3 = new RouteCollection();
        $collection3->add('foo', $new = new Route('/new'));

        $collection2->addCollection($collection3);
        $collection1->addCollection($collection2);

        $this->assertSame($new, $collection1->get('foo'), '->get() returns new route that overrode previous one');
        // size of 1 because collection1 contains /new but not /old anymore
        $this->assertCount(1, $collection1->getIterator(), '->addCollection() removes previous routes when adding new routes with the same name');
    }

    public function testGet()
    {
        $collection1 = new RouteCollection();
        $collection1->add('a', $a = new Route('/a'));
        $collection2 = new RouteCollection();
        $collection2->add('b', $b = new Route('/b'));
        $collection1->addCollection($collection2);
        $collection1->add('$péß^a|', $c = new Route('/special'));

        $this->assertSame($b, $collection1->get('b'), '->get() returns correct route in child collection');
        $this->assertSame($c, $collection1->get('$péß^a|'), '->get() can handle special characters');
        $this->assertNull($collection2->get('a'), '->get() does not return the route defined in parent collection');
        $this->assertNull($collection1->get('non-existent'), '->get() returns null when route does not exist');
        $this->assertNull($collection1->get(0), '->get() does not disclose internal child RouteCollection');
    }

    public function testRemove()
    {
        $collection = new RouteCollection();
        $collection->add('foo', $foo = new Route('/foo'));

        $collection1 = new RouteCollection();
        $collection1->add('bar', $bar = new Route('/bar'));
        $collection->addCollection($collection1);
        $collection->add('last', $last = new Route('/last'));

        $collection->remove('foo');
        $this->assertSame(array('bar' => $bar, 'last' => $last), $collection->all(), '->remove() can remove a single route');
        $collection->remove(array('bar', 'last'));
        $this->assertSame(array(), $collection->all(), '->remove() accepts an array and can remove multiple routes at once');
    }

    public function testSetHost()
    {
        $collection = new RouteCollection();
        $routea = new Route('/a');
        $routeb = new Route('/b', array(), array(), array(), '{locale}.example.net');
        $collection->add('a', $routea);
        $collection->add('b', $routeb);

        $collection->setHost('{locale}.example.com');

        $this->assertEquals('{locale}.example.com', $routea->getHost());
        $this->assertEquals('{locale}.example.com', $routeb->getHost());
    }

    public function testSetCondition()
    {
        $collection = new RouteCollection();
        $routea = new Route('/a');
        $routeb = new Route('/b', array(), array(), array(), '{locale}.example.net', array(), array(), 'context.getMethod() == "GET"');
        $collection->add('a', $routea);
        $collection->add('b', $routeb);

        $collection->setCondition('context.getMethod() == "POST"');

        $this->assertEquals('context.getMethod() == "POST"', $routea->getCondition());
        $this->assertEquals('context.getMethod() == "POST"', $routeb->getCondition());
    }

    public function testClone()
    {
        $collection = new RouteCollection();
        $collection->add('a', new Route('/a'));
        $collection->add('b', new Route('/b', array('placeholder' => 'default'), array('placeholder' => '.+')));

        $clonedCollection = clone $collection;

        $this->assertCount(2, $clonedCollection);
        $this->assertEquals($collection->get('a'), $clonedCollection->get('a'));
        $this->assertNotSame($collection->get('a'), $clonedCollection->get('a'));
        $this->assertEquals($collection->get('b'), $clonedCollection->get('b'));
        $this->assertNotSame($collection->get('b'), $clonedCollection->get('b'));
    }

    public function testSetSchemes()
    {
        $collection = new RouteCollection();
        $routea = new Route('/a', array(), array(), array(), '', 'http');
        $routeb = new Route('/b');
        $collection->add('a', $routea);
        $collection->add('b', $routeb);

        $collection->setSchemes(array('http', 'https'));

        $this->assertEquals(array('http', 'https'), $routea->getSchemes());
        $this->assertEquals(array('http', 'https'), $routeb->getSchemes());
    }

    public function testSetMethods()
    {
        $collection = new RouteCollection();
        $routea = new Route('/a', array(), array(), array(), '', array(), array('GET', 'POST'));
        $routeb = new Route('/b');
        $collection->add('a', $routea);
        $collection->add('b', $routeb);

        $collection->setMethods('PUT');

        $this->assertEquals(array('PUT'), $routea->getMethods());
        $this->assertEquals(array('PUT'), $routeb->getMethods());
    }
}
PK(1[ kl�g�gFRouting/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Generator;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;

class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
{
    public function testAbsoluteUrlWithPort80()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes)->generate('test', array(), true);

        $this->assertEquals('http://localhost/app.php/testing', $url);
    }

    public function testAbsoluteSecureUrlWithPort443()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes, array('scheme' => 'https'))->generate('test', array(), true);

        $this->assertEquals('https://localhost/app.php/testing', $url);
    }

    public function testAbsoluteUrlWithNonStandardPort()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes, array('httpPort' => 8080))->generate('test', array(), true);

        $this->assertEquals('http://localhost:8080/app.php/testing', $url);
    }

    public function testAbsoluteSecureUrlWithNonStandardPort()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes, array('httpsPort' => 8080, 'scheme' => 'https'))->generate('test', array(), true);

        $this->assertEquals('https://localhost:8080/app.php/testing', $url);
    }

    public function testRelativeUrlWithoutParameters()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes)->generate('test', array(), false);

        $this->assertEquals('/app.php/testing', $url);
    }

    public function testRelativeUrlWithParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
        $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false);

        $this->assertEquals('/app.php/testing/bar', $url);
    }

    public function testRelativeUrlWithNullParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing.{format}', array('format' => null)));
        $url = $this->getGenerator($routes)->generate('test', array(), false);

        $this->assertEquals('/app.php/testing', $url);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testRelativeUrlWithNullParameterButNotOptional()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}/bar', array('foo' => null)));
        // This must raise an exception because the default requirement for "foo" is "[^/]+" which is not met with these params.
        // Generating path "/testing//bar" would be wrong as matching this route would fail.
        $this->getGenerator($routes)->generate('test', array(), false);
    }

    public function testRelativeUrlWithOptionalZeroParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{page}'));
        $url = $this->getGenerator($routes)->generate('test', array('page' => 0), false);

        $this->assertEquals('/app.php/testing/0', $url);
    }

    public function testNotPassedOptionalParameterInBetween()
    {
        $routes = $this->getRoutes('test', new Route('/{slug}/{page}', array('slug' => 'index', 'page' => 0)));
        $this->assertSame('/app.php/index/1', $this->getGenerator($routes)->generate('test', array('page' => 1)));
        $this->assertSame('/app.php/', $this->getGenerator($routes)->generate('test'));
    }

    public function testRelativeUrlWithExtraParameters()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), false);

        $this->assertEquals('/app.php/testing?foo=bar', $url);
    }

    public function testAbsoluteUrlWithExtraParameters()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);

        $this->assertEquals('http://localhost/app.php/testing?foo=bar', $url);
    }

    public function testUrlWithNullExtraParameters()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $url = $this->getGenerator($routes)->generate('test', array('foo' => null), true);

        $this->assertEquals('http://localhost/app.php/testing', $url);
    }

    public function testUrlWithExtraParametersFromGlobals()
    {
        $routes = $this->getRoutes('test', new Route('/testing'));
        $generator = $this->getGenerator($routes);
        $context = new RequestContext('/app.php');
        $context->setParameter('bar', 'bar');
        $generator->setContext($context);
        $url = $generator->generate('test', array('foo' => 'bar'));

        $this->assertEquals('/app.php/testing?foo=bar', $url);
    }

    public function testUrlWithGlobalParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
        $generator = $this->getGenerator($routes);
        $context = new RequestContext('/app.php');
        $context->setParameter('foo', 'bar');
        $generator->setContext($context);
        $url = $generator->generate('test', array());

        $this->assertEquals('/app.php/testing/bar', $url);
    }

    public function testGlobalParameterHasHigherPriorityThanDefault()
    {
        $routes = $this->getRoutes('test', new Route('/{_locale}', array('_locale' => 'en')));
        $generator = $this->getGenerator($routes);
        $context = new RequestContext('/app.php');
        $context->setParameter('_locale', 'de');
        $generator->setContext($context);
        $url = $generator->generate('test', array());

        $this->assertSame('/app.php/de', $url);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException
     */
    public function testGenerateWithoutRoutes()
    {
        $routes = $this->getRoutes('foo', new Route('/testing/{foo}'));
        $this->getGenerator($routes)->generate('test', array(), true);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\MissingMandatoryParametersException
     */
    public function testGenerateForRouteWithoutMandatoryParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
        $this->getGenerator($routes)->generate('test', array(), true);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testGenerateForRouteWithInvalidOptionalParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')));
        $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testGenerateForRouteWithInvalidParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array(), array('foo' => '1|2')));
        $this->getGenerator($routes)->generate('test', array('foo' => '0'), true);
    }

    public function testGenerateForRouteWithInvalidOptionalParameterNonStrict()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')));
        $generator = $this->getGenerator($routes);
        $generator->setStrictRequirements(false);
        $this->assertNull($generator->generate('test', array('foo' => 'bar'), true));
    }

    public function testGenerateForRouteWithInvalidOptionalParameterNonStrictWithLogger()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')));
        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->once())
            ->method('error');
        $generator = $this->getGenerator($routes, array(), $logger);
        $generator->setStrictRequirements(false);
        $this->assertNull($generator->generate('test', array('foo' => 'bar'), true));
    }

    public function testGenerateForRouteWithInvalidParameterButDisabledRequirementsCheck()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array('foo' => '1'), array('foo' => 'd+')));
        $generator = $this->getGenerator($routes);
        $generator->setStrictRequirements(null);
        $this->assertSame('/app.php/testing/bar', $generator->generate('test', array('foo' => 'bar')));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testGenerateForRouteWithInvalidMandatoryParameter()
    {
        $routes = $this->getRoutes('test', new Route('/testing/{foo}', array(), array('foo' => 'd+')));
        $this->getGenerator($routes)->generate('test', array('foo' => 'bar'), true);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testRequiredParamAndEmptyPassed()
    {
        $routes = $this->getRoutes('test', new Route('/{slug}', array(), array('slug' => '.+')));
        $this->getGenerator($routes)->generate('test', array('slug' => ''));
    }

    public function testSchemeRequirementDoesNothingIfSameCurrentScheme()
    {
        $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http')));
        $this->assertEquals('/app.php/', $this->getGenerator($routes)->generate('test'));

        $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https')));
        $this->assertEquals('/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test'));
    }

    public function testSchemeRequirementForcesAbsoluteUrl()
    {
        $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'https')));
        $this->assertEquals('https://localhost/app.php/', $this->getGenerator($routes)->generate('test'));

        $routes = $this->getRoutes('test', new Route('/', array(), array('_scheme' => 'http')));
        $this->assertEquals('http://localhost/app.php/', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test'));
    }

    public function testPathWithTwoStartingSlashes()
    {
        $routes = $this->getRoutes('test', new Route('//path-and-not-domain'));

        // this must not generate '//path-and-not-domain' because that would be a network path
        $this->assertSame('/path-and-not-domain', $this->getGenerator($routes, array('BaseUrl' => ''))->generate('test'));
    }

    public function testNoTrailingSlashForMultipleOptionalParameters()
    {
        $routes = $this->getRoutes('test', new Route('/category/{slug1}/{slug2}/{slug3}', array('slug2' => null, 'slug3' => null)));

        $this->assertEquals('/app.php/category/foo', $this->getGenerator($routes)->generate('test', array('slug1' => 'foo')));
    }

    public function testWithAnIntegerAsADefaultValue()
    {
        $routes = $this->getRoutes('test', new Route('/{default}', array('default' => 0)));

        $this->assertEquals('/app.php/foo', $this->getGenerator($routes)->generate('test', array('default' => 'foo')));
    }

    public function testNullForOptionalParameterIsIgnored()
    {
        $routes = $this->getRoutes('test', new Route('/test/{default}', array('default' => 0)));

        $this->assertEquals('/app.php/test', $this->getGenerator($routes)->generate('test', array('default' => null)));
    }

    public function testQueryParamSameAsDefault()
    {
        $routes = $this->getRoutes('test', new Route('/test', array('default' => 'value')));

        $this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('default' => 'foo')));
        $this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test', array('default' => 'value')));
        $this->assertSame('/app.php/test', $this->getGenerator($routes)->generate('test'));
    }

    public function testGenerateWithSpecialRouteName()
    {
        $routes = $this->getRoutes('$péß^a|', new Route('/bar'));

        $this->assertSame('/app.php/bar', $this->getGenerator($routes)->generate('$péß^a|'));
    }

    public function testUrlEncoding()
    {
        // This tests the encoding of reserved characters that are used for delimiting of URI components (defined in RFC 3986)
        // and other special ASCII chars. These chars are tested as static text path, variable path and query param.
        $chars = '@:[]/()*\'" +,;-._~&$<>|{}%\\^`!?foo=bar#id';
        $routes = $this->getRoutes('test', new Route("/$chars/{varpath}", array(), array('varpath' => '.+')));
        $this->assertSame('/app.php/@:%5B%5D/%28%29*%27%22%20+,;-._~%26%24%3C%3E|%7B%7D%25%5C%5E%60!%3Ffoo=bar%23id'
           .'/@:%5B%5D/%28%29*%27%22%20+,;-._~%26%24%3C%3E|%7B%7D%25%5C%5E%60!%3Ffoo=bar%23id'
           .'?query=%40%3A%5B%5D%2F%28%29%2A%27%22+%2B%2C%3B-._%7E%26%24%3C%3E%7C%7B%7D%25%5C%5E%60%21%3Ffoo%3Dbar%23id',
            $this->getGenerator($routes)->generate('test', array(
                'varpath' => $chars,
                'query' => $chars
            ))
        );
    }

    public function testEncodingOfRelativePathSegments()
    {
        $routes = $this->getRoutes('test', new Route('/dir/../dir/..'));
        $this->assertSame('/app.php/dir/%2E%2E/dir/%2E%2E', $this->getGenerator($routes)->generate('test'));
        $routes = $this->getRoutes('test', new Route('/dir/./dir/.'));
        $this->assertSame('/app.php/dir/%2E/dir/%2E', $this->getGenerator($routes)->generate('test'));
        $routes = $this->getRoutes('test', new Route('/a./.a/a../..a/...'));
        $this->assertSame('/app.php/a./.a/a../..a/...', $this->getGenerator($routes)->generate('test'));
    }

    public function testAdjacentVariables()
    {
        $routes = $this->getRoutes('test', new Route('/{x}{y}{z}.{_format}', array('z' => 'default-z', '_format' => 'html'), array('y' => '\d+')));
        $generator = $this->getGenerator($routes);
        $this->assertSame('/app.php/foo123', $generator->generate('test', array('x' => 'foo', 'y' => '123')));
        $this->assertSame('/app.php/foo123bar.xml', $generator->generate('test', array('x' => 'foo', 'y' => '123', 'z' => 'bar', '_format' => 'xml')));

        // The default requirement for 'x' should not allow the separator '.' in this case because it would otherwise match everything
        // and following optional variables like _format could never match.
        $this->setExpectedException('Symfony\Component\Routing\Exception\InvalidParameterException');
        $generator->generate('test', array('x' => 'do.t', 'y' => '123', 'z' => 'bar', '_format' => 'xml'));
    }

    public function testOptionalVariableWithNoRealSeparator()
    {
        $routes = $this->getRoutes('test', new Route('/get{what}', array('what' => 'All')));
        $generator = $this->getGenerator($routes);

        $this->assertSame('/app.php/get', $generator->generate('test'));
        $this->assertSame('/app.php/getSites', $generator->generate('test', array('what' => 'Sites')));
    }

    public function testRequiredVariableWithNoRealSeparator()
    {
        $routes = $this->getRoutes('test', new Route('/get{what}Suffix'));
        $generator = $this->getGenerator($routes);

        $this->assertSame('/app.php/getSitesSuffix', $generator->generate('test', array('what' => 'Sites')));
    }

    public function testDefaultRequirementOfVariable()
    {
        $routes = $this->getRoutes('test', new Route('/{page}.{_format}'));
        $generator = $this->getGenerator($routes);

        $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', array('page' => 'index', '_format' => 'mobile.html')));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testDefaultRequirementOfVariableDisallowsSlash()
    {
        $routes = $this->getRoutes('test', new Route('/{page}.{_format}'));
        $this->getGenerator($routes)->generate('test', array('page' => 'index', '_format' => 'sl/ash'));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testDefaultRequirementOfVariableDisallowsNextSeparator()
    {
        $routes = $this->getRoutes('test', new Route('/{page}.{_format}'));
        $this->getGenerator($routes)->generate('test', array('page' => 'do.t', '_format' => 'html'));
    }

    public function testWithHostDifferentFromContext()
    {
        $routes = $this->getRoutes('test', new Route('/{name}', array(), array(), array(), '{locale}.example.com'));

        $this->assertEquals('//fr.example.com/app.php/Fabien', $this->getGenerator($routes)->generate('test', array('name' =>'Fabien', 'locale' => 'fr')));
    }

    public function testWithHostSameAsContext()
    {
        $routes = $this->getRoutes('test', new Route('/{name}', array(), array(), array(), '{locale}.example.com'));

        $this->assertEquals('/app.php/Fabien', $this->getGenerator($routes, array('host' => 'fr.example.com'))->generate('test', array('name' =>'Fabien', 'locale' => 'fr')));
    }

    public function testWithHostSameAsContextAndAbsolute()
    {
        $routes = $this->getRoutes('test', new Route('/{name}', array(), array(), array(), '{locale}.example.com'));

        $this->assertEquals('http://fr.example.com/app.php/Fabien', $this->getGenerator($routes, array('host' => 'fr.example.com'))->generate('test', array('name' =>'Fabien', 'locale' => 'fr'), true));
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testUrlWithInvalidParameterInHost()
    {
        $routes = $this->getRoutes('test', new Route('/', array(), array('foo' => 'bar'), array(), '{foo}.example.com'));
        $this->getGenerator($routes)->generate('test', array('foo' => 'baz'), false);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testUrlWithInvalidParameterInHostWhenParamHasADefaultValue()
    {
        $routes = $this->getRoutes('test', new Route('/', array('foo' => 'bar'), array('foo' => 'bar'), array(), '{foo}.example.com'));
        $this->getGenerator($routes)->generate('test', array('foo' => 'baz'), false);
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
     */
    public function testUrlWithInvalidParameterEqualsDefaultValueInHost()
    {
        $routes = $this->getRoutes('test', new Route('/', array('foo' => 'baz'), array('foo' => 'bar'), array(), '{foo}.example.com'));
        $this->getGenerator($routes)->generate('test', array('foo' => 'baz'), false);
    }

    public function testUrlWithInvalidParameterInHostInNonStrictMode()
    {
        $routes = $this->getRoutes('test', new Route('/', array(), array('foo' => 'bar'), array(), '{foo}.example.com'));
        $generator = $this->getGenerator($routes);
        $generator->setStrictRequirements(false);
        $this->assertNull($generator->generate('test', array('foo' => 'baz'), false));
    }

    public function testGenerateNetworkPath()
    {
        $routes = $this->getRoutes('test', new Route('/{name}', array(), array('_scheme' => 'http'), array(), '{locale}.example.com'));

        $this->assertSame('//fr.example.com/app.php/Fabien', $this->getGenerator($routes)->generate('test',
            array('name' =>'Fabien', 'locale' => 'fr'), UrlGeneratorInterface::NETWORK_PATH), 'network path with different host'
        );
        $this->assertSame('//fr.example.com/app.php/Fabien?query=string', $this->getGenerator($routes, array('host' => 'fr.example.com'))->generate('test',
            array('name' =>'Fabien', 'locale' => 'fr', 'query' => 'string'), UrlGeneratorInterface::NETWORK_PATH), 'network path although host same as context'
        );
        $this->assertSame('http://fr.example.com/app.php/Fabien', $this->getGenerator($routes, array('scheme' => 'https'))->generate('test',
            array('name' =>'Fabien', 'locale' => 'fr'), UrlGeneratorInterface::NETWORK_PATH), 'absolute URL because scheme requirement does not match context'
        );
        $this->assertSame('http://fr.example.com/app.php/Fabien', $this->getGenerator($routes)->generate('test',
            array('name' =>'Fabien', 'locale' => 'fr'), UrlGeneratorInterface::ABSOLUTE_URL), 'absolute URL with same scheme because it is requested'
        );
    }

    public function testGenerateRelativePath()
    {
        $routes = new RouteCollection();
        $routes->add('article', new Route('/{author}/{article}/'));
        $routes->add('comments', new Route('/{author}/{article}/comments'));
        $routes->add('host', new Route('/{article}', array(), array(), array(), '{author}.example.com'));
        $routes->add('scheme', new Route('/{author}', array(), array('_scheme' => 'https')));
        $routes->add('unrelated', new Route('/about'));

        $generator = $this->getGenerator($routes, array('host' => 'example.com', 'pathInfo' => '/fabien/symfony-is-great/'));

        $this->assertSame('comments', $generator->generate('comments',
            array('author' =>'fabien', 'article' => 'symfony-is-great'), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('comments?page=2', $generator->generate('comments',
            array('author' =>'fabien', 'article' => 'symfony-is-great', 'page' => 2), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('../twig-is-great/', $generator->generate('article',
            array('author' =>'fabien', 'article' => 'twig-is-great'), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('../../bernhard/forms-are-great/', $generator->generate('article',
            array('author' =>'bernhard', 'article' => 'forms-are-great'), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('//bernhard.example.com/app.php/forms-are-great', $generator->generate('host',
            array('author' =>'bernhard', 'article' => 'forms-are-great'), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('https://example.com/app.php/bernhard', $generator->generate('scheme',
            array('author' =>'bernhard'), UrlGeneratorInterface::RELATIVE_PATH)
        );
        $this->assertSame('../../about', $generator->generate('unrelated',
            array(), UrlGeneratorInterface::RELATIVE_PATH)
        );
    }

    /**
     * @dataProvider provideRelativePaths
     */
    public function testGetRelativePath($sourcePath, $targetPath, $expectedPath)
    {
        $this->assertSame($expectedPath, UrlGenerator::getRelativePath($sourcePath, $targetPath));
    }

    public function provideRelativePaths()
    {
        return array(
            array(
                '/same/dir/',
                '/same/dir/',
                ''
            ),
            array(
                '/same/file',
                '/same/file',
                ''
            ),
            array(
                '/',
                '/file',
                'file'
            ),
            array(
                '/',
                '/dir/file',
                'dir/file'
            ),
            array(
                '/dir/file.html',
                '/dir/different-file.html',
                'different-file.html'
            ),
            array(
                '/same/dir/extra-file',
                '/same/dir/',
                './'
            ),
            array(
                '/parent/dir/',
                '/parent/',
                '../'
            ),
            array(
                '/parent/dir/extra-file',
                '/parent/',
                '../'
            ),
            array(
                '/a/b/',
                '/x/y/z/',
                '../../x/y/z/'
            ),
            array(
                '/a/b/c/d/e',
                '/a/c/d',
                '../../../c/d'
            ),
            array(
                '/a/b/c//',
                '/a/b/c/',
                '../'
            ),
            array(
                '/a/b/c/',
                '/a/b/c//',
                './/'
            ),
            array(
                '/root/a/b/c/',
                '/root/x/b/c/',
                '../../../x/b/c/'
            ),
            array(
                '/a/b/c/d/',
                '/a',
                '../../../../a'
            ),
            array(
                '/special-chars/sp%20ce/1€/mäh/e=mc²',
                '/special-chars/sp%20ce/1€/<µ>/e=mc²',
                '../<µ>/e=mc²'
            ),
            array(
                'not-rooted',
                'dir/file',
                'dir/file'
            ),
            array(
                '//dir/',
                '',
                '../../'
            ),
            array(
                '/dir/',
                '/dir/file:with-colon',
                './file:with-colon'
            ),
            array(
                '/dir/',
                '/dir/subdir/file:with-colon',
                'subdir/file:with-colon'
            ),
            array(
                '/dir/',
                '/dir/:subdir/',
                './:subdir/'
            ),
        );
    }

    protected function getGenerator(RouteCollection $routes, array $parameters = array(), $logger = null)
    {
        $context = new RequestContext('/app.php');
        foreach ($parameters as $key => $value) {
            $method = 'set'.$key;
            $context->$method($value);
        }
        $generator = new UrlGenerator($routes, $context, $logger);

        return $generator;
    }

    protected function getRoutes($name, Route $route)
    {
        $routes = new RouteCollection();
        $routes->add($name, $route);

        return $routes;
    }
}
PK(1[������SRouting/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Generator\Dumper;

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper;
use Symfony\Component\Routing\RequestContext;

class PhpGeneratorDumperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var RouteCollection
     */
    private $routeCollection;

    /**
     * @var PhpGeneratorDumper
     */
    private $generatorDumper;

    /**
     * @var string
     */
    private $testTmpFilepath;

    protected function setUp()
    {
        parent::setUp();

        $this->routeCollection = new RouteCollection();
        $this->generatorDumper = new PhpGeneratorDumper($this->routeCollection);
        $this->testTmpFilepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'php_generator.php';
        @unlink($this->testTmpFilepath);
    }

    protected function tearDown()
    {
        parent::tearDown();

        @unlink($this->testTmpFilepath);

        $this->routeCollection = null;
        $this->generatorDumper = null;
        $this->testTmpFilepath = null;
    }

    public function testDumpWithRoutes()
    {
        $this->routeCollection->add('Test', new Route('/testing/{foo}'));
        $this->routeCollection->add('Test2', new Route('/testing2'));

        file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump());
        include ($this->testTmpFilepath);

        $projectUrlGenerator = new \ProjectUrlGenerator(new RequestContext('/app.php'));

        $absoluteUrlWithParameter    = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), true);
        $absoluteUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), true);
        $relativeUrlWithParameter    = $projectUrlGenerator->generate('Test', array('foo' => 'bar'), false);
        $relativeUrlWithoutParameter = $projectUrlGenerator->generate('Test2', array(), false);

        $this->assertEquals($absoluteUrlWithParameter, 'http://localhost/app.php/testing/bar');
        $this->assertEquals($absoluteUrlWithoutParameter, 'http://localhost/app.php/testing2');
        $this->assertEquals($relativeUrlWithParameter, '/app.php/testing/bar');
        $this->assertEquals($relativeUrlWithoutParameter, '/app.php/testing2');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testDumpWithoutRoutes()
    {
        file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'WithoutRoutesUrlGenerator')));
        include ($this->testTmpFilepath);

        $projectUrlGenerator = new \WithoutRoutesUrlGenerator(new RequestContext('/app.php'));

        $projectUrlGenerator->generate('Test', array());
    }

    /**
     * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException
     */
    public function testGenerateNonExistingRoute()
    {
        $this->routeCollection->add('Test', new Route('/test'));

        file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'NonExistingRoutesUrlGenerator')));
        include ($this->testTmpFilepath);

        $projectUrlGenerator = new \NonExistingRoutesUrlGenerator(new RequestContext());
        $url = $projectUrlGenerator->generate('NonExisting', array());
    }

    public function testDumpForRouteWithDefaults()
    {
        $this->routeCollection->add('Test', new Route('/testing/{foo}', array('foo' => 'bar')));

        file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(array('class' => 'DefaultRoutesUrlGenerator')));
        include ($this->testTmpFilepath);

        $projectUrlGenerator = new \DefaultRoutesUrlGenerator(new RequestContext());
        $url = $projectUrlGenerator->generate('Test', array());

        $this->assertEquals($url, '/testing');
    }
}
PK(1[8!!&GG=Routing/Symfony/Component/Routing/Tests/CompiledRouteTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\Routing\CompiledRoute;

class CompiledRouteTest extends \PHPUnit_Framework_TestCase
{
    public function testAccessors()
    {
        $compiled = new CompiledRoute('prefix', 'regex', array('tokens'), array(), array(), array(), array(), array('variables'));
        $this->assertEquals('prefix', $compiled->getStaticPrefix(), '__construct() takes a static prefix as its second argument');
        $this->assertEquals('regex', $compiled->getRegex(), '__construct() takes a regexp as its third argument');
        $this->assertEquals(array('tokens'), $compiled->getTokens(), '__construct() takes an array of tokens as its fourth argument');
        $this->assertEquals(array('variables'), $compiled->getVariables(), '__construct() takes an array of variables as its ninth argument');
    }
}
PK(1[���k��DRouting/Symfony/Component/Routing/Tests/Loader/ClosureLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Routing\Loader\ClosureLoader;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;

class ClosureLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $loader = new ClosureLoader();

        $closure = function () {};

        $this->assertTrue($loader->supports($closure), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($loader->supports($closure, 'closure'), '->supports() checks the resource type if specified');
        $this->assertFalse($loader->supports($closure, 'foo'), '->supports() checks the resource type if specified');
    }

    public function testLoad()
    {
        $loader = new ClosureLoader();

        $route = new Route('/');
        $routes = $loader->load(function () use ($route) {
            $routes = new RouteCollection();

            $routes->add('foo', $route);

            return $routes;
        });

        $this->assertEquals($route, $routes->get('foo'), '->load() loads a \Closure resource');
    }
}
PK(1[�����LRouting/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Routing\Annotation\Route;

class AnnotationClassLoaderTest extends AbstractAnnotationLoaderTest
{
    protected $loader;

    protected function setUp()
    {
        parent::setUp();

        $this->reader = $this->getReader();
        $this->loader = $this->getClassLoader($this->reader);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLoadMissingClass()
    {
        $this->loader->load('MissingClass');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLoadAbstractClass()
    {
        $this->loader->load('Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\AbstractClass');
    }

    /**
     * @dataProvider provideTestSupportsChecksResource
     */
    public function testSupportsChecksResource($resource, $expectedSupports)
    {
        $this->assertSame($expectedSupports, $this->loader->supports($resource), '->supports() returns true if the resource is loadable');
    }

    public function provideTestSupportsChecksResource()
    {
        return array(
            array('class', true),
            array('\fully\qualified\class\name', true),
            array('namespaced\class\without\leading\slash', true),
            array('ÿClassWithLegalSpecialCharacters', true),
            array('5', false),
            array('foo.foo', false),
            array(null, false),
        );
    }

    public function testSupportsChecksTypeIfSpecified()
    {
        $this->assertTrue($this->loader->supports('class', 'annotation'), '->supports() checks the resource type if specified');
        $this->assertFalse($this->loader->supports('class', 'foo'), '->supports() checks the resource type if specified');
    }

    public function getLoadTests()
    {
        return array(
            array(
                'Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\BarClass',
                array('name' => 'route1'),
                array('arg2' => 'defaultValue2', 'arg3' => 'defaultValue3')
            ),
            array(
                'Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\BarClass',
                array('name' => 'route1', 'defaults' => array('arg2' => 'foo')),
                array('arg2' => 'defaultValue2', 'arg3' => 'defaultValue3')
            ),
            array(
                'Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\BarClass',
                array('name' => 'route1', 'defaults' => array('arg2' => 'foobar')),
                array('arg2' => 'defaultValue2', 'arg3' =>'defaultValue3')
            ),
            array(
                'Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\BarClass',
                array('name' => 'route1', 'defaults' => array('arg2' => 'foo'), 'condition' => 'context.getMethod() == "GET"'),
                array('arg2' => 'defaultValue2', 'arg3' =>'defaultValue3')
            ),
        );
    }

    /**
     * @dataProvider getLoadTests
     */
    public function testLoad($className, $routeDatas = array(), $methodArgs = array())
    {
        $routeDatas = array_replace(array(
            'name'         => 'route',
            'path'         => '/',
            'requirements' => array(),
            'options'      => array(),
            'defaults'     => array(),
            'schemes'      => array(),
            'methods'      => array(),
            'condition'    => null,
        ), $routeDatas);

        $this->reader
            ->expects($this->once())
            ->method('getMethodAnnotations')
            ->will($this->returnValue(array($this->getAnnotatedRoute($routeDatas))))
        ;
        $routeCollection = $this->loader->load($className);
        $route = $routeCollection->get($routeDatas['name']);

        $this->assertSame($routeDatas['path'], $route->getPath(), '->load preserves path annotation');
        $this->assertSame($routeDatas['requirements'],$route->getRequirements(), '->load preserves requirements annotation');
        $this->assertCount(0, array_intersect($route->getOptions(), $routeDatas['options']), '->load preserves options annotation');
        $this->assertSame(array_replace($methodArgs, $routeDatas['defaults']), $route->getDefaults(), '->load preserves defaults annotation');
        $this->assertEquals($routeDatas['condition'], $route->getCondition(), '->load preserves condition annotation');
    }

    private function getAnnotatedRoute($datas)
    {
        return new Route($datas);
    }
}
PK(1[g�U��DRouting/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\PhpFileLoader;

class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $loader = new PhpFileLoader($this->getMock('Symfony\Component\Config\FileLocator'));

        $this->assertTrue($loader->supports('foo.php'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($loader->supports('foo.php', 'php'), '->supports() checks the resource type if specified');
        $this->assertFalse($loader->supports('foo.php', 'foo'), '->supports() checks the resource type if specified');
    }

    public function testLoadWithRoute()
    {
        $loader = new PhpFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('validpattern.php');
        $routes = $routeCollection->all();

        $this->assertCount(2, $routes, 'Two routes are loaded');
        $this->assertContainsOnly('Symfony\Component\Routing\Route', $routes);

        foreach ($routes as $route) {
            $this->assertSame('/blog/{slug}', $route->getPath());
            $this->assertSame('MyBlogBundle:Blog:show', $route->getDefault('_controller'));
            $this->assertSame('{locale}.example.com', $route->getHost());
            $this->assertSame('RouteCompiler', $route->getOption('compiler_class'));
            $this->assertEquals(array('GET', 'POST', 'PUT', 'OPTIONS'), $route->getMethods());
            $this->assertEquals(array('https'), $route->getSchemes());
        }
    }
}
PK(1[{��t��ERouting/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Config\Resource\FileResource;

class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $loader = new YamlFileLoader($this->getMock('Symfony\Component\Config\FileLocator'));

        $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($loader->supports('foo.yml', 'yaml'), '->supports() checks the resource type if specified');
        $this->assertFalse($loader->supports('foo.yml', 'foo'), '->supports() checks the resource type if specified');
    }

    public function testLoadDoesNothingIfEmpty()
    {
        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $collection = $loader->load('empty.yml');

        $this->assertEquals(array(), $collection->all());
        $this->assertEquals(array(new FileResource(realpath(__DIR__.'/../Fixtures/empty.yml'))), $collection->getResources());
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getPathsToInvalidFiles
     */
    public function testLoadThrowsExceptionWithInvalidFile($filePath)
    {
        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $loader->load($filePath);
    }

    public function getPathsToInvalidFiles()
    {
        return array(array('nonvalid.yml'), array('nonvalid2.yml'), array('incomplete.yml'), array('nonvalidkeys.yml'), array('nonesense_resource_plus_path.yml'), array('nonesense_type_without_resource.yml'));
    }

    public function testLoadSpecialRouteName()
    {
        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('special_route_name.yml');
        $route = $routeCollection->get('#$péß^a|');

        $this->assertInstanceOf('Symfony\Component\Routing\Route', $route);
        $this->assertSame('/true', $route->getPath());
    }

    public function testLoadWithRoute()
    {
        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('validpattern.yml');
        $routes = $routeCollection->all();

        $this->assertCount(3, $routes, 'Three routes are loaded');
        $this->assertContainsOnly('Symfony\Component\Routing\Route', $routes);

        $identicalRoutes = array_slice($routes, 0, 2);

        foreach ($identicalRoutes as $route) {
            $this->assertSame('/blog/{slug}', $route->getPath());
            $this->assertSame('{locale}.example.com', $route->getHost());
            $this->assertSame('MyBundle:Blog:show', $route->getDefault('_controller'));
            $this->assertSame('\w+', $route->getRequirement('locale'));
            $this->assertSame('RouteCompiler', $route->getOption('compiler_class'));
            $this->assertEquals(array('GET', 'POST', 'PUT', 'OPTIONS'), $route->getMethods());
            $this->assertEquals(array('https'), $route->getSchemes());
            $this->assertEquals('context.getMethod() == "GET"', $route->getCondition());
        }
    }

    public function testLoadWithResource()
    {
        $loader = new YamlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('validresource.yml');
        $routes = $routeCollection->all();

        $this->assertCount(3, $routes, 'Three routes are loaded');
        $this->assertContainsOnly('Symfony\Component\Routing\Route', $routes);

        foreach ($routes as $route) {
            $this->assertSame('/{foo}/blog/{slug}', $route->getPath());
            $this->assertSame('123', $route->getDefault('foo'));
            $this->assertSame('\d+', $route->getRequirement('foo'));
            $this->assertSame('bar', $route->getOption('foo'));
            $this->assertSame('', $route->getHost());
            $this->assertSame('context.getMethod() == "POST"', $route->getCondition());
        }
    }

}
PK(1[6����PRouting/Symfony/Component/Routing/Tests/Loader/AnnotationDirectoryLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader;
use Symfony\Component\Config\FileLocator;

class AnnotationDirectoryLoaderTest extends AbstractAnnotationLoaderTest
{
    protected $loader;
    protected $reader;

    protected function setUp()
    {
        parent::setUp();

        $this->reader = $this->getReader();
        $this->loader = new AnnotationDirectoryLoader(new FileLocator(), $this->getClassLoader($this->reader));
    }

    public function testLoad()
    {
        $this->reader->expects($this->exactly(2))->method('getClassAnnotation');

        $this->reader
            ->expects($this->any())
            ->method('getMethodAnnotations')
            ->will($this->returnValue(array()))
        ;

        $this->loader->load(__DIR__.'/../Fixtures/AnnotatedClasses');
    }

    public function testSupports()
    {
        $fixturesDir = __DIR__.'/../Fixtures';

        $this->assertTrue($this->loader->supports($fixturesDir), '->supports() returns true if the resource is loadable');
        $this->assertFalse($this->loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($this->loader->supports($fixturesDir, 'annotation'), '->supports() checks the resource type if specified');
        $this->assertFalse($this->loader->supports($fixturesDir, 'foo'), '->supports() checks the resource type if specified');
    }
}
PK(1[M�~�##DRouting/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\XmlFileLoader;
use Symfony\Component\Routing\Tests\Fixtures\CustomXmlFileLoader;

class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $loader = new XmlFileLoader($this->getMock('Symfony\Component\Config\FileLocator'));

        $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($loader->supports('foo.xml', 'xml'), '->supports() checks the resource type if specified');
        $this->assertFalse($loader->supports('foo.xml', 'foo'), '->supports() checks the resource type if specified');
    }

    public function testLoadWithRoute()
    {
        $loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('validpattern.xml');
        $routes = $routeCollection->all();

        $this->assertCount(3, $routes, 'Three routes are loaded');
        $this->assertContainsOnly('Symfony\Component\Routing\Route', $routes);

        $identicalRoutes = array_slice($routes, 0, 2);

        foreach ($identicalRoutes as $route) {
            $this->assertSame('/blog/{slug}', $route->getPath());
            $this->assertSame('{locale}.example.com', $route->getHost());
            $this->assertSame('MyBundle:Blog:show', $route->getDefault('_controller'));
            $this->assertSame('\w+', $route->getRequirement('locale'));
            $this->assertSame('RouteCompiler', $route->getOption('compiler_class'));
            $this->assertEquals(array('GET', 'POST', 'PUT', 'OPTIONS'), $route->getMethods());
            $this->assertEquals(array('https'), $route->getSchemes());
            $this->assertEquals('context.getMethod() == "GET"', $route->getCondition());
        }
    }

    public function testLoadWithNamespacePrefix()
    {
        $loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('namespaceprefix.xml');

        $this->assertCount(1, $routeCollection->all(), 'One route is loaded');

        $route = $routeCollection->get('blog_show');
        $this->assertSame('/blog/{slug}', $route->getPath());
        $this->assertSame('{_locale}.example.com', $route->getHost());
        $this->assertSame('MyBundle:Blog:show', $route->getDefault('_controller'));
        $this->assertSame('\w+', $route->getRequirement('slug'));
        $this->assertSame('en|fr|de', $route->getRequirement('_locale'));
        $this->assertSame(null, $route->getDefault('slug'));
        $this->assertSame('RouteCompiler', $route->getOption('compiler_class'));
    }

    public function testLoadWithImport()
    {
        $loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $routeCollection = $loader->load('validresource.xml');
        $routes = $routeCollection->all();

        $this->assertCount(3, $routes, 'Three routes are loaded');
        $this->assertContainsOnly('Symfony\Component\Routing\Route', $routes);

        foreach ($routes as $route) {
            $this->assertSame('/{foo}/blog/{slug}', $route->getPath());
            $this->assertSame('123', $route->getDefault('foo'));
            $this->assertSame('\d+', $route->getRequirement('foo'));
            $this->assertSame('bar', $route->getOption('foo'));
            $this->assertSame('', $route->getHost());
            $this->assertSame('context.getMethod() == "POST"', $route->getCondition());
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getPathsToInvalidFiles
     */
    public function testLoadThrowsExceptionWithInvalidFile($filePath)
    {
        $loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $loader->load($filePath);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getPathsToInvalidFiles
     */
    public function testLoadThrowsExceptionWithInvalidFileEvenWithoutSchemaValidation($filePath)
    {
        $loader = new CustomXmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $loader->load($filePath);
    }

    public function getPathsToInvalidFiles()
    {
        return array(array('nonvalidnode.xml'), array('nonvalidroute.xml'), array('nonvalid.xml'), array('missing_id.xml'), array('missing_path.xml'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Document types are not allowed.
     */
    public function testDocTypeIsNotAllowed()
    {
        $loader = new XmlFileLoader(new FileLocator(array(__DIR__.'/../Fixtures')));
        $loader->load('withdoctype.xml');
    }
}
PK(1[|�C44ORouting/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

abstract class AbstractAnnotationLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function getReader()
    {
        return $this->getMockBuilder('Doctrine\Common\Annotations\Reader')
            ->disableOriginalConstructor()
            ->getMock()
        ;
    }

    public function getClassLoader($reader)
    {
        return $this->getMockBuilder('Symfony\Component\Routing\Loader\AnnotationClassLoader')
            ->setConstructorArgs(array($reader))
            ->getMockForAbstractClass()
        ;
    }
}
PK(1[u��;KRouting/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests\Loader;

use Symfony\Component\Routing\Loader\AnnotationFileLoader;
use Symfony\Component\Config\FileLocator;

class AnnotationFileLoaderTest extends AbstractAnnotationLoaderTest
{
    protected $loader;
    protected $reader;

    protected function setUp()
    {
        parent::setUp();

        $this->reader = $this->getReader();
        $this->loader = new AnnotationFileLoader(new FileLocator(), $this->getClassLoader($this->reader));
    }

    public function testLoad()
    {
        $this->reader->expects($this->once())->method('getClassAnnotation');

        $this->loader->load(__DIR__.'/../Fixtures/AnnotatedClasses/FooClass.php');
    }

    public function testSupports()
    {
        $fixture = __DIR__.'/../Fixtures/annotated.php';

        $this->assertTrue($this->loader->supports($fixture), '->supports() returns true if the resource is loadable');
        $this->assertFalse($this->loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');

        $this->assertTrue($this->loader->supports($fixture, 'annotation'), '->supports() checks the resource type if specified');
        $this->assertFalse($this->loader->supports($fixture, 'foo'), '->supports() checks the resource type if specified');
    }
}
PK(1[��6Routing/Symfony/Component/Routing/Tests/RouterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\Routing\Router;
use Symfony\Component\HttpFoundation\Request;

class RouterTest extends \PHPUnit_Framework_TestCase
{
    private $router = null;

    private $loader = null;

    protected function setUp()
    {
        $this->loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $this->router = new Router($this->loader, 'routing.yml');
    }

    public function testSetOptionsWithSupportedOptions()
    {
        $this->router->setOptions(array(
            'cache_dir' => './cache',
            'debug' => true,
            'resource_type' => 'ResourceType'
        ));

        $this->assertSame('./cache', $this->router->getOption('cache_dir'));
        $this->assertTrue($this->router->getOption('debug'));
        $this->assertSame('ResourceType', $this->router->getOption('resource_type'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The Router does not support the following options: "option_foo", "option_bar"
     */
    public function testSetOptionsWithUnsupportedOptions()
    {
        $this->router->setOptions(array(
            'cache_dir' => './cache',
            'option_foo' => true,
            'option_bar' => 'baz',
            'resource_type' => 'ResourceType'
        ));
    }

    public function testSetOptionWithSupportedOption()
    {
        $this->router->setOption('cache_dir', './cache');

        $this->assertSame('./cache', $this->router->getOption('cache_dir'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The Router does not support the "option_foo" option
     */
    public function testSetOptionWithUnsupportedOption()
    {
        $this->router->setOption('option_foo', true);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The Router does not support the "option_foo" option
     */
    public function testGetOptionWithUnsupportedOption()
    {
        $this->router->getOption('option_foo', true);
    }

    public function testThatRouteCollectionIsLoaded()
    {
        $this->router->setOption('resource_type', 'ResourceType');

        $routeCollection = $this->getMock('Symfony\Component\Routing\RouteCollection');

        $this->loader->expects($this->once())
            ->method('load')->with('routing.yml', 'ResourceType')
            ->will($this->returnValue($routeCollection));

        $this->assertSame($routeCollection, $this->router->getRouteCollection());
    }

    /**
     * @dataProvider provideMatcherOptionsPreventingCaching
     */
    public function testMatcherIsCreatedIfCacheIsNotConfigured($option)
    {
        $this->router->setOption($option, null);

        $this->loader->expects($this->once())
            ->method('load')->with('routing.yml', null)
            ->will($this->returnValue($this->getMock('Symfony\Component\Routing\RouteCollection')));

        $this->assertInstanceOf('Symfony\\Component\\Routing\\Matcher\\UrlMatcher', $this->router->getMatcher());

    }

    public function provideMatcherOptionsPreventingCaching()
    {
        return array(
            array('cache_dir'),
            array('matcher_cache_class')
        );
    }

    /**
     * @dataProvider provideGeneratorOptionsPreventingCaching
     */
    public function testGeneratorIsCreatedIfCacheIsNotConfigured($option)
    {
        $this->router->setOption($option, null);

        $this->loader->expects($this->once())
            ->method('load')->with('routing.yml', null)
            ->will($this->returnValue($this->getMock('Symfony\Component\Routing\RouteCollection')));

        $this->assertInstanceOf('Symfony\\Component\\Routing\\Generator\\UrlGenerator', $this->router->getGenerator());

    }

    public function provideGeneratorOptionsPreventingCaching()
    {
        return array(
            array('cache_dir'),
            array('generator_cache_class')
        );
    }

    public function testMatchRequestWithUrlMatcherInterface()
    {
        $matcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $matcher->expects($this->once())->method('match');

        $p = new \ReflectionProperty($this->router, 'matcher');
        $p->setAccessible(true);
        $p->setValue($this->router, $matcher);

        $this->router->matchRequest(Request::create('/'));
    }

    public function testMatchRequestWithRequestMatcherInterface()
    {
        $matcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
        $matcher->expects($this->once())->method('matchRequest');

        $p = new \ReflectionProperty($this->router, 'matcher');
        $p->setAccessible(true);
        $p->setValue($this->router, $matcher);

        $this->router->matchRequest(Request::create('/'));
    }
}
PK(1[u��A�,�,5Routing/Symfony/Component/Routing/Tests/RouteTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Routing\Tests;

use Symfony\Component\Routing\Route;

class RouteTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $route = new Route('/{foo}', array('foo' => 'bar'), array('foo' => '\d+'), array('foo' => 'bar'), '{locale}.example.com');
        $this->assertEquals('/{foo}', $route->getPath(), '__construct() takes a path as its first argument');
        $this->assertEquals(array('foo' => 'bar'), $route->getDefaults(), '__construct() takes defaults as its second argument');
        $this->assertEquals(array('foo' => '\d+'), $route->getRequirements(), '__construct() takes requirements as its third argument');
        $this->assertEquals('bar', $route->getOption('foo'), '__construct() takes options as its fourth argument');
        $this->assertEquals('{locale}.example.com', $route->getHost(), '__construct() takes a host pattern as its fifth argument');

        $route = new Route('/', array(), array(), array(), '', array('Https'), array('POST', 'put'), 'context.getMethod() == "GET"');
        $this->assertEquals(array('https'), $route->getSchemes(), '__construct() takes schemes as its sixth argument and lowercases it');
        $this->assertEquals(array('POST', 'PUT'), $route->getMethods(), '__construct() takes methods as its seventh argument and uppercases it');
        $this->assertEquals('context.getMethod() == "GET"', $route->getCondition(), '__construct() takes a condition as its eight argument');

        $route = new Route('/', array(), array(), array(), '', 'Https', 'Post');
        $this->assertEquals(array('https'), $route->getSchemes(), '__construct() takes a single scheme as its sixth argument');
        $this->assertEquals(array('POST'), $route->getMethods(), '__construct() takes a single method as its seventh argument');
    }

    public function testPath()
    {
        $route = new Route('/{foo}');
        $route->setPath('/{bar}');
        $this->assertEquals('/{bar}', $route->getPath(), '->setPath() sets the path');
        $route->setPath('');
        $this->assertEquals('/', $route->getPath(), '->setPath() adds a / at the beginning of the path if needed');
        $route->setPath('bar');
        $this->assertEquals('/bar', $route->getPath(), '->setPath() adds a / at the beginning of the path if needed');
        $this->assertEquals($route, $route->setPath(''), '->setPath() implements a fluent interface');
        $route->setPath('//path');
        $this->assertEquals('/path', $route->getPath(), '->setPath() does not allow two slashes "//" at the beginning of the path as it would be confused with a network path when generating the path from the route');
    }

    public function testOptions()
    {
        $route = new Route('/{foo}');
        $route->setOptions(array('foo' => 'bar'));
        $this->assertEquals(array_merge(array(
        'compiler_class'     => 'Symfony\\Component\\Routing\\RouteCompiler',
        ), array('foo' => 'bar')), $route->getOptions(), '->setOptions() sets the options');
        $this->assertEquals($route, $route->setOptions(array()), '->setOptions() implements a fluent interface');

        $route->setOptions(array('foo' => 'foo'));
        $route->addOptions(array('bar' => 'bar'));
        $this->assertEquals($route, $route->addOptions(array()), '->addOptions() implements a fluent interface');
        $this->assertEquals(array('foo' => 'foo', 'bar' => 'bar', 'compiler_class' => 'Symfony\\Component\\Routing\\RouteCompiler'), $route->getOptions(), '->addDefaults() keep previous defaults');
    }

    public function testOption()
    {
        $route = new Route('/{foo}');
        $this->assertFalse($route->hasOption('foo'), '->hasOption() return false if option is not set');
        $this->assertEquals($route, $route->setOption('foo', 'bar'), '->setOption() implements a fluent interface');
        $this->assertEquals('bar', $route->getOption('foo'), '->setOption() sets the option');
        $this->assertTrue($route->hasOption('foo'), '->hasOption() return true if option is set');
    }

    public function testDefaults()
    {
        $route = new Route('/{foo}');
        $route->setDefaults(array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $route->getDefaults(), '->setDefaults() sets the defaults');
        $this->assertEquals($route, $route->setDefaults(array()), '->setDefaults() implements a fluent interface');

        $route->setDefault('foo', 'bar');
        $this->assertEquals('bar', $route->getDefault('foo'), '->setDefault() sets a default value');

        $route->setDefault('foo2', 'bar2');
        $this->assertEquals('bar2', $route->getDefault('foo2'), '->getDefault() return the default value');
        $this->assertNull($route->getDefault('not_defined'), '->getDefault() return null if default value is not set');

        $route->setDefault('_controller', $closure = function () { return 'Hello'; });
        $this->assertEquals($closure, $route->getDefault('_controller'), '->setDefault() sets a default value');

        $route->setDefaults(array('foo' => 'foo'));
        $route->addDefaults(array('bar' => 'bar'));
        $this->assertEquals($route, $route->addDefaults(array()), '->addDefaults() implements a fluent interface');
        $this->assertEquals(array('foo' => 'foo', 'bar' => 'bar'), $route->getDefaults(), '->addDefaults() keep previous defaults');
    }

    public function testRequirements()
    {
        $route = new Route('/{foo}');
        $route->setRequirements(array('foo' => '\d+'));
        $this->assertEquals(array('foo' => '\d+'), $route->getRequirements(), '->setRequirements() sets the requirements');
        $this->assertEquals('\d+', $route->getRequirement('foo'), '->getRequirement() returns a requirement');
        $this->assertNull($route->getRequirement('bar'), '->getRequirement() returns null if a requirement is not defined');
        $route->setRequirements(array('foo' => '^\d+$'));
        $this->assertEquals('\d+', $route->getRequirement('foo'), '->getRequirement() removes ^ and $ from the path');
        $this->assertEquals($route, $route->setRequirements(array()), '->setRequirements() implements a fluent interface');

        $route->setRequirements(array('foo' => '\d+'));
        $route->addRequirements(array('bar' => '\d+'));
        $this->assertEquals($route, $route->addRequirements(array()), '->addRequirements() implements a fluent interface');
        $this->assertEquals(array('foo' => '\d+', 'bar' => '\d+'), $route->getRequirements(), '->addRequirement() keep previous requirements');
    }

    public function testRequirement()
    {
        $route = new Route('/{foo}');
        $this->assertFalse($route->hasRequirement('foo'), '->hasRequirement() return false if requirement is not set');
        $route->setRequirement('foo', '^\d+$');
        $this->assertEquals('\d+', $route->getRequirement('foo'), '->setRequirement() removes ^ and $ from the path');
        $this->assertTrue($route->hasRequirement('foo'), '->hasRequirement() return true if requirement is set');
    }

    /**
     * @dataProvider getInvalidRequirements
     * @expectedException \InvalidArgumentException
     */
    public function testSetInvalidRequirement($req)
    {
        $route = new Route('/{foo}');
        $route->setRequirement('foo', $req);
    }

    public function getInvalidRequirements()
    {
        return array(
           array(''),
           array(array()),
           array('^$'),
           array('^'),
           array('$')
        );
    }

    public function testHost()
    {
        $route = new Route('/');
        $route->setHost('{locale}.example.net');
        $this->assertEquals('{locale}.example.net', $route->getHost(), '->setHost() sets the host pattern');
    }

    public function testScheme()
    {
        $route = new Route('/');
        $this->assertEquals(array(), $route->getSchemes(), 'schemes is initialized with array()');
        $route->setSchemes('hTTp');
        $this->assertEquals(array('http'), $route->getSchemes(), '->setSchemes() accepts a single scheme string and lowercases it');
        $route->setSchemes(array('HttpS', 'hTTp'));
        $this->assertEquals(array('https', 'http'), $route->getSchemes(), '->setSchemes() accepts an array of schemes and lowercases them');
    }

    public function testSchemeIsBC()
    {
        $route = new Route('/');
        $route->setRequirement('_scheme', 'http|https');
        $this->assertEquals('http|https', $route->getRequirement('_scheme'));
        $this->assertEquals(array('http', 'https'), $route->getSchemes());
        $route->setSchemes(array('hTTp'));
        $this->assertEquals('http', $route->getRequirement('_scheme'));
        $route->setSchemes(array());
        $this->assertNull($route->getRequirement('_scheme'));
    }

    public function testMethod()
    {
        $route = new Route('/');
        $this->assertEquals(array(), $route->getMethods(), 'methods is initialized with array()');
        $route->setMethods('gEt');
        $this->assertEquals(array('GET'), $route->getMethods(), '->setMethods() accepts a single method string and uppercases it');
        $route->setMethods(array('gEt', 'PosT'));
        $this->assertEquals(array('GET', 'POST'), $route->getMethods(), '->setMethods() accepts an array of methods and uppercases them');
    }

    public function testMethodIsBC()
    {
        $route = new Route('/');
        $route->setRequirement('_method', 'GET|POST');
        $this->assertEquals('GET|POST', $route->getRequirement('_method'));
        $this->assertEquals(array('GET', 'POST'), $route->getMethods());
        $route->setMethods(array('gEt'));
        $this->assertEquals('GET', $route->getRequirement('_method'));
        $route->setMethods(array());
        $this->assertNull($route->getRequirement('_method'));
    }

    public function testCondition()
    {
        $route = new Route('/');
        $this->assertEquals(null, $route->getCondition());
        $route->setCondition('context.getMethod() == "GET"');
        $this->assertEquals('context.getMethod() == "GET"', $route->getCondition());
    }

    public function testCompile()
    {
        $route = new Route('/{foo}');
        $this->assertInstanceOf('Symfony\Component\Routing\CompiledRoute', $compiled = $route->compile(), '->compile() returns a compiled route');
        $this->assertSame($compiled, $route->compile(), '->compile() only compiled the route once if unchanged');
        $route->setRequirement('foo', '.*');
        $this->assertNotSame($compiled, $route->compile(), '->compile() recompiles if the route was modified');
    }

    public function testPattern()
    {
        $route = new Route('/{foo}');
        $this->assertEquals('/{foo}', $route->getPattern());

        $route->setPattern('/bar');
        $this->assertEquals('/bar', $route->getPattern());
    }

    public function testSerialize()
    {
        $route = new Route('/{foo}', array('foo' => 'default'), array('foo' => '\d+'));

        $serialized = serialize($route);
        $unserialized = unserialize($serialized);

        $this->assertEquals($route, $unserialized);
        $this->assertNotSame($route, $unserialized);
    }
}
PK(1[~�662Routing/Symfony/Component/Routing/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Routing Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK)1[��W8j#j#)Structures_Graph/tests/BasicGraphTest.phpnu�[���<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
// +-----------------------------------------------------------------------------+
// | Copyright (c) 2003 S�rgio Gon�alves Carvalho                                |
// +-----------------------------------------------------------------------------+
// | This file is part of Structures_Graph.                                      |
// |                                                                             |
// | Structures_Graph is free software; you can redistribute it and/or modify    |
// | it under the terms of the GNU Lesser General Public License as published by |
// | the Free Software Foundation; either version 2.1 of the License, or         |
// | (at your option) any later version.                                         |
// |                                                                             |
// | Structures_Graph is distributed in the hope that it will be useful,         |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of              |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               |
// | GNU Lesser General Public License for more details.                         |
// |                                                                             |
// | You should have received a copy of the GNU Lesser General Public License    |
// | along with Structures_Graph; if not, write to the Free Software             |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA                    |
// | 02111-1307 USA                                                              |
// +-----------------------------------------------------------------------------+
// | Author: S�rgio Carvalho <sergio.carvalho@portugalmail.com>                  |
// +-----------------------------------------------------------------------------+
//

require_once dirname(__FILE__) . '/helper.inc';

/**
 * @access private
 */
class BasicGraph extends PHPUnit_Framework_TestCase
{
    var $_graph = null;

    function test_create_graph() {
        $this->_graph = new Structures_Graph();
        $this->assertTrue(is_a($this->_graph, 'Structures_Graph')); 
    }

    function test_add_node() {
        $this->_graph = new Structures_Graph();
        $data = 1;
        $node = new Structures_Graph_Node($data);
        $this->_graph->addNode($node);
        $node = new Structures_Graph_Node($data);
        $this->_graph->addNode($node);
        $node = new Structures_Graph_Node($data);
        $this->_graph->addNode($node);
    }

    function test_connect_node() {
        $this->_graph = new Structures_Graph();
        $data = 1;
        $node1 = new Structures_Graph_Node($data);
        $node2 = new Structures_Graph_Node($data);
        $this->_graph->addNode($node1);
        $this->_graph->addNode($node2);
        $node1->connectTo($node2);

        $node =& $this->_graph->getNodes();
        $node =& $node[0];
        $node = $node->getNeighbours();
        $node =& $node[0];
        /* 
         ZE1 == and === operators fail on $node,$node2 because of the recursion introduced
         by the _graph field in the Node object. So, we'll use the stupid method for reference
         testing
        */
        $node = true;
        $this->assertTrue($node2);
        $node = false;
        $this->assertFalse($node2);
    }

    function test_data_references() {
        $this->_graph = new Structures_Graph();
        $data = 1;
        $node = new Structures_Graph_Node();
        $node->setData($data);
        $this->_graph->addNode($node);
        $data = 2;
        $dataInNode =& $this->_graph->getNodes();
        $dataInNode =& $dataInNode[0];
        $dataInNode =& $dataInNode->getData();
        $this->assertEquals($data, $dataInNode);
    }

    function test_metadata_references() {
        $this->_graph = new Structures_Graph();
        $data = 1;
        $node = new Structures_Graph_Node();
        $node->setMetadata('5', $data);
        $data = 2;
        $dataInNode =& $node->getMetadata('5');
        $this->assertEquals($data, $dataInNode);
    }
   
    function test_metadata_key_exists() {
        $this->_graph = new Structures_Graph();
        $data = 1;
        $node = new Structures_Graph_Node();
        $node->setMetadata('5', $data);
        $this->assertTrue($node->metadataKeyExists('5'));
        $this->assertFalse($node->metadataKeyExists('1'));
    }

    function test_directed_degree() {
        $this->_graph = new Structures_Graph(true);
        $node = array();
        $node[] = new Structures_Graph_Node();
        $node[] = new Structures_Graph_Node();
        $node[] = new Structures_Graph_Node();
        $this->_graph->addNode($node[0]);
        $this->_graph->addNode($node[1]);
        $this->_graph->addNode($node[2]);
        $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs');
        $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs');
        $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs');
        $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs');
        $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs');
        $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs');
        $node[0]->connectTo($node[1]);
        $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc');
        $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc');
        $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc');
        $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc');
        $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc');
        $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc');
        $node[0]->connectTo($node[2]);
        $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs');
        $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs');
        $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs');
        $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs');
        $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs');
        $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs');
    }

    function test_undirected_degree() {
        $this->_graph = new Structures_Graph(false);
        $node = array();
        $node[] = new Structures_Graph_Node();
        $node[] = new Structures_Graph_Node();
        $node[] = new Structures_Graph_Node();
        $this->_graph->addNode($node[0]);
        $this->_graph->addNode($node[1]);
        $this->_graph->addNode($node[2]);
        $this->assertEquals(0, $node[0]->inDegree(), 'inDegree test failed for node 0 with 0 arcs');
        $this->assertEquals(0, $node[1]->inDegree(), 'inDegree test failed for node 1 with 0 arcs');
        $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 0 arcs');
        $this->assertEquals(0, $node[0]->outDegree(), 'outDegree test failed for node 0 with 0 arcs');
        $this->assertEquals(0, $node[1]->outDegree(), 'outDegree test failed for node 1 with 0 arcs');
        $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 0 arcs');
        $node[0]->connectTo($node[1]);
        $this->assertEquals(1, $node[0]->inDegree(), 'inDegree test failed for node 0 with 1 arc');
        $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 1 arc');
        $this->assertEquals(0, $node[2]->inDegree(), 'inDegree test failed for node 2 with 1 arc');
        $this->assertEquals(1, $node[0]->outDegree(), 'outDegree test failed for node 0 with 1 arc');
        $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 1 arc');
        $this->assertEquals(0, $node[2]->outDegree(), 'outDegree test failed for node 2 with 1 arc');
        $node[0]->connectTo($node[2]);
        $this->assertEquals(2, $node[0]->inDegree(), 'inDegree test failed for node 0 with 2 arcs');
        $this->assertEquals(1, $node[1]->inDegree(), 'inDegree test failed for node 1 with 2 arcs');
        $this->assertEquals(1, $node[2]->inDegree(), 'inDegree test failed for node 2 with 2 arcs');
        $this->assertEquals(2, $node[0]->outDegree(), 'outDegree test failed for node 0 with 2 arcs');
        $this->assertEquals(1, $node[1]->outDegree(), 'outDegree test failed for node 1 with 2 arcs');
        $this->assertEquals(1, $node[2]->outDegree(), 'outDegree test failed for node 2 with 2 arcs');
    }
}
?>
PK)1[6��:UU0Structures_Graph/tests/TopologicalSorterTest.phpnu�[���<?php
require_once dirname(__FILE__) . '/helper.inc';
require_once 'Structures/Graph/Manipulator/TopologicalSorter.php';

class TopologicalSorterTest extends PHPUnit_Framework_TestCase
{
    public function testSort()
    {
        $graph = new Structures_Graph();

        $name1 = 'node1';
        $node1 = new Structures_Graph_Node();
        $node1->setData($name1);
        $graph->addNode($node1);

        $name11 = 'node11';
        $node11 = new Structures_Graph_Node();
        $node11->setData($name11);
        $graph->addNode($node11);
        $node1->connectTo($node11);

        $name12 = 'node12';
        $node12 = new Structures_Graph_Node();
        $node12->setData($name12);
        $graph->addNode($node12);
        $node1->connectTo($node12);

        $name121 = 'node121';
        $node121 = new Structures_Graph_Node();
        $node121->setData($name121);
        $graph->addNode($node121);
        $node12->connectTo($node121);

        $name2 = 'node2';
        $node2 = new Structures_Graph_Node();
        $node2->setData($name2);
        $graph->addNode($node2);

        $name21 = 'node21';
        $node21 = new Structures_Graph_Node();
        $node21->setData($name21);
        $graph->addNode($node21);
        $node2->connectTo($node21);

        $nodes = Structures_Graph_Manipulator_TopologicalSorter::sort($graph);
        $this->assertCount(2, $nodes[0]);
        $this->assertEquals('node1', $nodes[0][0]->getData());
        $this->assertEquals('node2', $nodes[0][1]->getData());

        $this->assertCount(3, $nodes[1]);
        $this->assertEquals('node11', $nodes[1][0]->getData());
        $this->assertEquals('node12', $nodes[1][1]->getData());
        $this->assertEquals('node21', $nodes[1][2]->getData());

        $this->assertCount(1, $nodes[2]);
        $this->assertEquals('node121', $nodes[2][0]->getData());
    }
}
?>
PK)1[�V���#Structures_Graph/tests/AllTests.phpnu�[���<?php
require_once dirname(__FILE__) . '/helper.inc';

class Structures_Graph_AllTests
{
    public static function main()
    {
        PHPUnit_TextUI_TestRunner::run(self::suite());
    }

    public static function suite()
    {
        $suite = new PHPUnit_Framework_TestSuite('Structures_Graph Tests');

        $dir = new GlobIterator(dirname(__FILE__) . '/*Test.php');
        $suite->addTestFiles($dir);

        return $suite;
    }
}
PK)1[���*Structures_Graph/tests/AcyclicTestTest.phpnu�[���<?php
require_once dirname(__FILE__) . '/helper.inc';
require_once 'Structures/Graph/Manipulator/AcyclicTest.php';

class AcyclicTestTest extends PHPUnit_Framework_TestCase
{
    public function testIsAcyclicFalse()
    {
        $graph = new Structures_Graph();
        $node1 = new Structures_Graph_Node();
        $graph->addNode($node1);

        $node2 = new Structures_Graph_Node();
        $graph->addNode($node2);
        $node1->connectTo($node2);

        $node3 = new Structures_Graph_Node();
        $graph->addNode($node3);
        $node2->connectTo($node3);

        $node3->connectTo($node1);

        $this->assertFalse(
            Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph),
            'Graph is cyclic'
        );
    }

    public function testIsAcyclicTrue()
    {
        $graph = new Structures_Graph();
        $node1 = new Structures_Graph_Node();
        $graph->addNode($node1);

        $node2 = new Structures_Graph_Node();
        $graph->addNode($node2);
        $node1->connectTo($node2);

        $node3 = new Structures_Graph_Node();
        $graph->addNode($node3);
        $node2->connectTo($node3);

        $this->assertTrue(
            Structures_Graph_Manipulator_AcyclicTest::isAcyclic($graph),
            'Graph is acyclic'
        );
    }
}
?>
PK)1[a�[ii!Structures_Graph/tests/helper.incnu�[���<?php
if ('/opt/alt/php71/usr/share/pear' == '@'.'php_dir'.'@') {
    // This package hasn't been installed.
    // Adjust path to ensure includes find files in working directory.
    set_include_path(dirname(dirname(__FILE__))
        . PATH_SEPARATOR . dirname(__FILE__)
        . PATH_SEPARATOR . get_include_path());
}

require_once 'Structures/Graph.php';
PK)1[��+\MMCProcess/Symfony/Component/Process/Tests/PhpExecutableFinderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\PhpExecutableFinder;

/**
 * @author Robert Schönthal <seroscho@googlemail.com>
 */
class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * tests find() with the env var PHP_PATH
     */
    public function testFindWithPhpPath()
    {
        if (defined('PHP_BINARY')) {
            $this->markTestSkipped('The PHP binary is easily available as of PHP 5.4');
        }

        $f = new PhpExecutableFinder();

        $current = $f->find();

        //not executable PHP_PATH
        putenv('PHP_PATH=/not/executable/php');
        $this->assertFalse($f->find(), '::find() returns false for not executable PHP');

        //executable PHP_PATH
        putenv('PHP_PATH='.$current);
        $this->assertEquals($f->find(), $current, '::find() returns the executable PHP');
    }

    /**
     * tests find() with default executable
     */
    public function testFindWithSuffix()
    {
        if (defined('PHP_BINARY')) {
            $this->markTestSkipped('The PHP binary is easily available as of PHP 5.4');
        }

        putenv('PHP_PATH=');
        putenv('PHP_PEAR_PHP_BIN=');
        $f = new PhpExecutableFinder();

        $current = $f->find();

        //TODO maybe php executable is custom or even Windows
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertTrue(is_executable($current));
            $this->assertTrue((bool) preg_match('/'.addSlashes(DIRECTORY_SEPARATOR).'php\.(exe|bat|cmd|com)$/i', $current), '::find() returns the executable PHP with suffixes');
        }
    }
}
PK)1[#�OProcess/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.phpnu�[���<?php

define('ERR_SELECT_FAILED', 1);
define('ERR_TIMEOUT', 2);
define('ERR_READ_FAILED', 3);
define('ERR_WRITE_FAILED', 4);

$read = array(STDIN);
$write = array(STDOUT, STDERR);

stream_set_blocking(STDIN, 0);
stream_set_blocking(STDOUT, 0);
stream_set_blocking(STDERR, 0);

$out = $err = '';
while ($read || $write) {
    $r = $read;
    $w = $write;
    $e = null;
    $n = stream_select($r, $w, $e, 5);

    if (false === $n) {
        die(ERR_SELECT_FAILED);
    } elseif ($n < 1) {
        die(ERR_TIMEOUT);
    }

    if (in_array(STDOUT, $w) && strlen($out) > 0) {
         $written = fwrite(STDOUT, (binary) $out, 32768);
         if (false === $written) {
             die(ERR_WRITE_FAILED);
         }
         $out = (binary) substr($out, $written);
    }
    if (null === $read && strlen($out) < 1) {
        $write = array_diff($write, array(STDOUT));
    }

    if (in_array(STDERR, $w) && strlen($err) > 0) {
         $written = fwrite(STDERR, (binary) $err, 32768);
         if (false === $written) {
             die(ERR_WRITE_FAILED);
         }
         $err = (binary) substr($err, $written);
    }
    if (null === $read && strlen($err) < 1) {
        $write = array_diff($write, array(STDERR));
    }

    if ($r) {
        $str = fread(STDIN, 32768);
        if (false !== $str) {
            $out .= $str;
            $err .= $str;
        }
        if (false === $str || feof(STDIN)) {
            $read = null;
            if (!feof(STDIN)) {
                die(ERR_READ_FAILED);
            }
        }
    }
}
PK)1[�WKo�
�
FProcess/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Exception\ProcessFailedException;

/**
 * @author Sebastian Marek <proofek@gmail.com>
 */
class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * tests ProcessFailedException throws exception if the process was successful
     */
    public function testProcessFailedExceptionThrowsException()
    {
        $process = $this->getMock(
            'Symfony\Component\Process\Process',
            array('isSuccessful'),
            array('php')
        );
        $process->expects($this->once())
            ->method('isSuccessful')
            ->will($this->returnValue(true));

        $this->setExpectedException(
            '\InvalidArgumentException',
            'Expected a failed process, but the given process was successful.'
        );

        new ProcessFailedException($process);
    }

    /**
     * tests ProcessFailedException uses information from process output
     * to generate exception message
     */
    public function testProcessFailedExceptionPopulatesInformationFromProcessOutput()
    {
        $cmd = 'php';
        $exitCode = 1;
        $exitText = 'General error';
        $output = "Command output";
        $errorOutput = "FATAL: Unexpected error";

        $process = $this->getMock(
            'Symfony\Component\Process\Process',
            array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText'),
            array($cmd)
        );
        $process->expects($this->once())
            ->method('isSuccessful')
            ->will($this->returnValue(false));
        $process->expects($this->once())
            ->method('getOutput')
            ->will($this->returnValue($output));
        $process->expects($this->once())
            ->method('getErrorOutput')
            ->will($this->returnValue($errorOutput));
        $process->expects($this->once())
            ->method('getExitCode')
            ->will($this->returnValue($exitCode));
        $process->expects($this->once())
            ->method('getExitCodeText')
            ->will($this->returnValue($exitText));

        $exception = new ProcessFailedException($process);

        $this->assertEquals(
            "The command \"$cmd\" failed.\nExit Code: $exitCode($exitText)\n\nOutput:\n================\n{$output}\n\nError Output:\n================\n{$errorOutput}",
            $exception->getMessage()
        );
    }
}
PK)1[C�u^UU<Process/Symfony/Component/Process/Tests/ProcessUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\ProcessUtils;

class ProcessUtilsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataArguments
     */
    public function testEscapeArgument($result, $argument)
    {
        $this->assertSame($result, ProcessUtils::escapeArgument($argument));
    }

    public function dataArguments()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            return array(
                array('"\"php\" \"-v\""', '"php" "-v"'),
                array('"foo bar"', 'foo bar'),
                array('^%"path"^%', '%path%'),
                array('"<|>\\" \\"\'f"', '<|>" "\'f'),
                array('""', ''),
                array('"with\trailingbs\\\\"', 'with\trailingbs\\'),
            );
        }

        return array(
            array("'\"php\" \"-v\"'", '"php" "-v"'),
            array("'foo bar'", 'foo bar'),
            array("'%path%'", '%path%'),
            array("'<|>\" \"'\\''f'", '<|>" "\'f'),
            array("''", ''),
            array("'with\\trailingbs\\'", 'with\trailingbs\\'),
        );
    }
}
PK)1[[�VAChCh?Process/Symfony/Component/Process/Tests/AbstractProcessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\ProcessPipes;

/**
 * @author Robert Schönthal <seroscho@googlemail.com>
 */
abstract class AbstractProcessTest extends \PHPUnit_Framework_TestCase
{
    public function testThatProcessDoesNotThrowWarningDuringRun()
    {
        @trigger_error('Test Error', E_USER_NOTICE);
        $process = $this->getProcess("php -r 'sleep(3)'");
        $process->run();
        $actualError = error_get_last();
        $this->assertEquals('Test Error', $actualError['message']);
        $this->assertEquals(E_USER_NOTICE, $actualError['type']);
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
     */
    public function testNegativeTimeoutFromConstructor()
    {
        $this->getProcess('', null, null, null, -1);
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
     */
    public function testNegativeTimeoutFromSetter()
    {
        $p = $this->getProcess('');
        $p->setTimeout(-1);
    }

    public function testFloatAndNullTimeout()
    {
        $p = $this->getProcess('');

        $p->setTimeout(10);
        $this->assertSame(10.0, $p->getTimeout());

        $p->setTimeout(null);
        $this->assertNull($p->getTimeout());

        $p->setTimeout(0.0);
        $this->assertNull($p->getTimeout());
    }

    public function testStopWithTimeoutIsActuallyWorking()
    {
        $this->verifyPosixIsEnabled();

        // exec is mandatory here since we send a signal to the process
        // see https://github.com/symfony/symfony/issues/5030 about prepending
        // command with exec
        $p = $this->getProcess('exec php '.__DIR__.'/NonStopableProcess.php 3');
        $p->start();
        usleep(100000);
        $start = microtime(true);
        $p->stop(1.1, SIGKILL);
        while ($p->isRunning()) {
            usleep(1000);
        }
        $duration = microtime(true) - $start;

        $this->assertLessThan(1.8, $duration);
    }

    public function testAllOutputIsActuallyReadOnTermination()
    {
        // this code will result in a maximum of 2 reads of 8192 bytes by calling
        // start() and isRunning().  by the time getOutput() is called the process
        // has terminated so the internal pipes array is already empty. normally
        // the call to start() will not read any data as the process will not have
        // generated output, but this is non-deterministic so we must count it as
        // a possibility.  therefore we need 2 * ProcessPipes::CHUNK_SIZE plus
        // another byte which will never be read.
        $expectedOutputSize = ProcessPipes::CHUNK_SIZE * 2 + 2;

        $code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));

        $p->start();
        // Let's wait enough time for process to finish...
        // Here we don't call Process::run or Process::wait to avoid any read of pipes
        usleep(500000);

        if ($p->isRunning()) {
            $this->markTestSkipped('Process execution did not complete in the required time frame');
        }

        $o = $p->getOutput();

        $this->assertEquals($expectedOutputSize, strlen($o));
    }

    public function testCallbacksAreExecutedWithStart()
    {
        $data = '';

        $process = $this->getProcess('echo foo && php -r "sleep(1);" && echo foo');
        $process->start(function ($type, $buffer) use (&$data) {
            $data .= $buffer;
        });

        while ($process->isRunning()) {
            usleep(10000);
        }

        $this->assertEquals(2, preg_match_all('/foo/', $data, $matches));
    }

    /**
     * tests results from sub processes
     *
     * @dataProvider responsesCodeProvider
     */
    public function testProcessResponses($expected, $getter, $code)
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
        $p->run();

        $this->assertSame($expected, $p->$getter());
    }

    /**
     * tests results from sub processes
     *
     * @dataProvider pipesCodeProvider
     */
    public function testProcessPipes($code, $size)
    {
        $expected = str_repeat(str_repeat('*', 1024), $size) . '!';
        $expectedLength = (1024 * $size) + 1;

        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg($code)));
        $p->setStdin($expected);
        $p->run();

        $this->assertEquals($expectedLength, strlen($p->getOutput()));
        $this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
    }

    public function chainedCommandsOutputProvider()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            return array(
                array("2 \r\n2\r\n", '&&', '2')
            );
        }

        return array(
            array("1\n1\n", ';', '1'),
            array("2\n2\n", '&&', '2'),
        );
    }

    /**
     *
     * @dataProvider chainedCommandsOutputProvider
     */
    public function testChainedCommandsOutput($expected, $operator, $input)
    {
        $process = $this->getProcess(sprintf('echo %s %s echo %s', $input, $operator, $input));
        $process->run();
        $this->assertEquals($expected, $process->getOutput());
    }

    public function testCallbackIsExecutedForOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('echo \'foo\';')));

        $called = false;
        $p->run(function ($type, $buffer) use (&$called) {
            $called = $buffer === 'foo';
        });

        $this->assertTrue($called, 'The callback should be executed with the output');
    }

    public function testGetErrorOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));

        $p->run();
        $this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
    }

    public function testGetIncrementalErrorOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { usleep(100000); file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));

        $p->start();
        while ($p->isRunning()) {
            $this->assertLessThanOrEqual(1, preg_match_all('/ERROR/', $p->getIncrementalErrorOutput(), $matches));
            usleep(20000);
        }
    }

    public function testFlushErrorOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));

        $p->run();
        $p->clearErrorOutput();
        $this->assertEmpty($p->getErrorOutput());
    }

    public function testGetOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++; usleep(500); }')));

        $p->run();
        $this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
    }

    public function testGetIncrementalOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) { echo \' foo \'; usleep(50000); $n++; }')));

        $p->start();
        while ($p->isRunning()) {
            $this->assertLessThanOrEqual(1, preg_match_all('/foo/', $p->getIncrementalOutput(), $matches));
            usleep(20000);
        }
    }

    public function testFlushOutput()
    {
        $p = $this->getProcess(sprintf('php -r %s', escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));

        $p->run();
        $p->clearOutput();
        $this->assertEmpty($p->getOutput());
    }

    public function testExitCodeCommandFailed()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX exit code');
        }

        // such command run in bash return an exitcode 127
        $process = $this->getProcess('nonexistingcommandIhopeneversomeonewouldnameacommandlikethis');
        $process->run();

        $this->assertGreaterThan(0, $process->getExitCode());
    }

    public function testTTYCommand()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does have /dev/tty support');
        }

        $process = $this->getProcess('echo "foo" >> /dev/null && php -r "usleep(100000);"');
        $process->setTTY(true);
        $process->start();
        $this->assertTrue($process->isRunning());
        $process->wait();

        $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
    }

    public function testTTYCommandExitCode()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does have /dev/tty support');
        }

        $process = $this->getProcess('echo "foo" >> /dev/null');
        $process->setTTY(true);
        $process->run();

        $this->assertTrue($process->isSuccessful());
    }

    public function testExitCodeTextIsNullWhenExitCodeIsNull()
    {
        $process = $this->getProcess('');
        $this->assertNull($process->getExitCodeText());
    }

    public function testExitCodeText()
    {
        $process = $this->getProcess('');
        $r = new \ReflectionObject($process);
        $p = $r->getProperty('exitcode');
        $p->setAccessible(true);

        $p->setValue($process, 2);
        $this->assertEquals('Misuse of shell builtins', $process->getExitCodeText());
    }

    public function testStartIsNonBlocking()
    {
        $process = $this->getProcess('php -r "usleep(500000);"');
        $start = microtime(true);
        $process->start();
        $end = microtime(true);
        $this->assertLessThan(0.2, $end-$start);
        $process->wait();
    }

    public function testUpdateStatus()
    {
        $process = $this->getProcess('php -h');
        $process->run();
        $this->assertTrue(strlen($process->getOutput()) > 0);
    }

    public function testGetExitCodeIsNullOnStart()
    {
        $process = $this->getProcess('php -r "usleep(200000);"');
        $this->assertNull($process->getExitCode());
        $process->start();
        $this->assertNull($process->getExitCode());
        $process->wait();
        $this->assertEquals(0, $process->getExitCode());
    }

    public function testGetExitCodeIsNullOnWhenStartingAgain()
    {
        $process = $this->getProcess('php -r "usleep(200000);"');
        $process->run();
        $this->assertEquals(0, $process->getExitCode());
        $process->start();
        $this->assertNull($process->getExitCode());
        $process->wait();
        $this->assertEquals(0, $process->getExitCode());
    }

    public function testGetExitCode()
    {
        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertSame(0, $process->getExitCode());
    }

    public function testStatus()
    {
        $process = $this->getProcess('php -r "usleep(500000);"');
        $this->assertFalse($process->isRunning());
        $this->assertFalse($process->isStarted());
        $this->assertFalse($process->isTerminated());
        $this->assertSame(Process::STATUS_READY, $process->getStatus());
        $process->start();
        $this->assertTrue($process->isRunning());
        $this->assertTrue($process->isStarted());
        $this->assertFalse($process->isTerminated());
        $this->assertSame(Process::STATUS_STARTED, $process->getStatus());
        $process->wait();
        $this->assertFalse($process->isRunning());
        $this->assertTrue($process->isStarted());
        $this->assertTrue($process->isTerminated());
        $this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
    }

    public function testStop()
    {
        $process = $this->getProcess('php -r "sleep(4);"');
        $process->start();
        $this->assertTrue($process->isRunning());
        $process->stop();
        $this->assertFalse($process->isRunning());
    }

    public function testIsSuccessful()
    {
        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertTrue($process->isSuccessful());
    }

    public function testIsSuccessfulOnlyAfterTerminated()
    {
        $process = $this->getProcess('php -r "sleep(1);"');
        $process->start();
        while ($process->isRunning()) {
            $this->assertFalse($process->isSuccessful());
            usleep(300000);
        }

        $this->assertTrue($process->isSuccessful());
    }

    public function testIsNotSuccessful()
    {
        $process = $this->getProcess('php -r "usleep(500000);throw new \Exception(\'BOUM\');"');
        $process->start();
        $this->assertTrue($process->isRunning());
        $process->wait();
        $this->assertFalse($process->isSuccessful());
    }

    public function testProcessIsNotSignaled()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertFalse($process->hasBeenSignaled());
    }

    public function testProcessWithoutTermSignalIsNotSignaled()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertFalse($process->hasBeenSignaled());
    }

    public function testProcessWithoutTermSignal()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertEquals(0, $process->getTermSignal());
    }

    public function testProcessIsSignaledIfStopped()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        $process = $this->getProcess('php -r "sleep(4);"');
        $process->start();
        $process->stop();
        $this->assertTrue($process->hasBeenSignaled());
    }

    public function testProcessWithTermSignal()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        // SIGTERM is only defined if pcntl extension is present
        $termSignal = defined('SIGTERM') ? SIGTERM : 15;

        $process = $this->getProcess('php -r "sleep(4);"');
        $process->start();
        $process->stop();

        $this->assertEquals($termSignal, $process->getTermSignal());
    }

    public function testProcessThrowsExceptionWhenExternallySignaled()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Windows does not support POSIX signals');
        }

        if (!function_exists('posix_kill')) {
            $this->markTestSkipped('posix_kill is required for this test');
        }

        $termSignal = defined('SIGKILL') ? SIGKILL : 9;

        $process = $this->getProcess('exec php -r "while (true) {}"');
        $process->start();
        posix_kill($process->getPid(), $termSignal);

        $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'The process has been signaled with signal "9".');
        $process->wait();
    }

    public function testRestart()
    {
        $process1 = $this->getProcess('php -r "echo getmypid();"');
        $process1->run();
        $process2 = $process1->restart();

        $process2->wait(); // wait for output

        // Ensure that both processed finished and the output is numeric
        $this->assertFalse($process1->isRunning());
        $this->assertFalse($process2->isRunning());
        $this->assertTrue(is_numeric($process1->getOutput()));
        $this->assertTrue(is_numeric($process2->getOutput()));

        // Ensure that restart returned a new process by check that the output is different
        $this->assertNotEquals($process1->getOutput(), $process2->getOutput());
    }

    public function testPhpDeadlock()
    {
        $this->markTestSkipped('Can course PHP to hang');

        // Sleep doesn't work as it will allow the process to handle signals and close
        // file handles from the other end.
        $process = $this->getProcess('php -r "while (true) {}"');
        $process->start();

        // PHP will deadlock when it tries to cleanup $process
    }

    public function testRunProcessWithTimeout()
    {
        $timeout = 0.5;
        $process = $this->getProcess('php -r "usleep(600000);"');
        $process->setTimeout($timeout);
        $start = microtime(true);
        try {
            $process->run();
            $this->fail('A RuntimeException should have been raised');
        } catch (RuntimeException $e) {

        }
        $duration = microtime(true) - $start;

        $this->assertLessThan($timeout + Process::TIMEOUT_PRECISION, $duration);
    }

    public function testCheckTimeoutOnNonStartedProcess()
    {
        $process = $this->getProcess('php -r "sleep(3);"');
        $process->checkTimeout();
    }

    public function testCheckTimeoutOnTerminatedProcess()
    {
        $process = $this->getProcess('php -v');
        $process->run();
        $process->checkTimeout();
    }

    public function testCheckTimeoutOnStartedProcess()
    {
        $timeout = 0.5;
        $precision = 100000;
        $process = $this->getProcess('php -r "sleep(3);"');
        $process->setTimeout($timeout);
        $start = microtime(true);

        $process->start();

        try {
            while ($process->isRunning()) {
                $process->checkTimeout();
                usleep($precision);
            }
            $this->fail('A RuntimeException should have been raised');
        } catch (RuntimeException $e) {

        }
        $duration = microtime(true) - $start;

        $this->assertLessThan($timeout + $precision, $duration);
        $this->assertFalse($process->isSuccessful());
    }

    /**
     * @group idle-timeout
     */
    public function testIdleTimeout()
    {
        $process = $this->getProcess('sleep 3');
        $process->setTimeout(10);
        $process->setIdleTimeout(1);

        try {
            $process->run();

            $this->fail('A timeout exception was expected.');
        } catch (ProcessTimedOutException $ex) {
            $this->assertTrue($ex->isIdleTimeout());
            $this->assertFalse($ex->isGeneralTimeout());
            $this->assertEquals(1.0, $ex->getExceededTimeout());
        }
    }

    /**
     * @group idle-timeout
     */
    public function testIdleTimeoutNotExceededWhenOutputIsSent()
    {
        $process = $this->getProcess('echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 1 && echo "foo" && sleep 5');
        $process->setTimeout(5);
        $process->setIdleTimeout(3);

        try {
            $process->run();
            $this->fail('A timeout exception was expected.');
        } catch (ProcessTimedOutException $ex) {
            $this->assertTrue($ex->isGeneralTimeout());
            $this->assertFalse($ex->isIdleTimeout());
            $this->assertEquals(5.0, $ex->getExceededTimeout());
        }
    }

    public function testStartAfterATimeout()
    {
        $process = $this->getProcess('php -r "$n = 1000; while ($n--) {echo \'\'; usleep(1000); }"');
        $process->setTimeout(0.1);
        try {
            $process->run();
            $this->fail('An exception should have been raised.');
        } catch (\Exception $e) {

        }
        $process->start();
        usleep(10000);
        $process->stop();
    }

    public function testGetPid()
    {
        $process = $this->getProcess('php -r "usleep(500000);"');
        $process->start();
        $this->assertGreaterThan(0, $process->getPid());
        $process->wait();
    }

    public function testGetPidIsNullBeforeStart()
    {
        $process = $this->getProcess('php -r "sleep(1);"');
        $this->assertNull($process->getPid());
    }

    public function testGetPidIsNullAfterRun()
    {
        $process = $this->getProcess('php -m');
        $process->run();
        $this->assertNull($process->getPid());
    }

    public function testSignal()
    {
        $this->verifyPosixIsEnabled();

        $process = $this->getProcess('exec php -f ' . __DIR__ . '/SignalListener.php');
        $process->start();
        usleep(500000);
        $process->signal(SIGUSR1);

        while ($process->isRunning() && false === strpos($process->getoutput(), 'Caught SIGUSR1')) {
            usleep(10000);
        }

        $this->assertEquals('Caught SIGUSR1', $process->getOutput());
    }

    public function testExitCodeIsAvailableAfterSignal()
    {
        $this->verifyPosixIsEnabled();

        $process = $this->getProcess('sleep 4');
        $process->start();
        $process->signal(SIGKILL);

        while ($process->isRunning()) {
            usleep(10000);
        }

        $this->assertFalse($process->isRunning());
        $this->assertTrue($process->hasBeenSignaled());
        $this->assertFalse($process->isSuccessful());
        $this->assertEquals(137, $process->getExitCode());
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\LogicException
     */
    public function testSignalProcessNotRunning()
    {
        $this->verifyPosixIsEnabled();
        $process = $this->getProcess('php -m');
        $process->signal(SIGHUP);
    }

    /**
     * @dataProvider provideMethodsThatNeedARunningProcess
     */
    public function testMethodsThatNeedARunningProcess($method)
    {
        $process = $this->getProcess('php -m');
        $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
        call_user_func(array($process, $method));
    }

    public function provideMethodsThatNeedARunningProcess()
    {
        return array(
            array('getOutput'),
            array('getIncrementalOutput'),
            array('getErrorOutput'),
            array('getIncrementalErrorOutput'),
            array('wait'),
        );
    }

    /**
     * @dataProvider provideMethodsThatNeedATerminatedProcess
     */
    public function testMethodsThatNeedATerminatedProcess($method)
    {
        $process = $this->getProcess('php -r "sleep(1);"');
        $process->start();
        try {
            call_user_func(array($process, $method));
            $process->stop(0);
            $this->fail('A LogicException must have been thrown');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\Process\Exception\LogicException', $e);
            $this->assertEquals(sprintf('Process must be terminated before calling %s.', $method), $e->getMessage());
        }
        $process->stop(0);
    }

    public function provideMethodsThatNeedATerminatedProcess()
    {
        return array(
            array('hasBeenSignaled'),
            array('getTermSignal'),
            array('hasBeenStopped'),
            array('getStopSignal'),
        );
    }

    private function verifyPosixIsEnabled()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('POSIX signals do not work on Windows');
        }
        if (!defined('SIGUSR1')) {
            $this->markTestSkipped('The pcntl extension is not enabled');
        }
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     */
    public function testSignalWithWrongIntSignal()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('POSIX signals do not work on Windows');
        }

        $process = $this->getProcess('php -r "sleep(3);"');
        $process->start();
        $process->signal(-4);
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     */
    public function testSignalWithWrongNonIntSignal()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('POSIX signals do not work on Windows');
        }

        $process = $this->getProcess('php -r "sleep(3);"');
        $process->start();
        $process->signal('Céphalopodes');
    }

    public function responsesCodeProvider()
    {
        return array(
            //expected output / getter / code to execute
            //array(1,'getExitCode','exit(1);'),
            //array(true,'isSuccessful','exit();'),
            array('output', 'getOutput', 'echo \'output\';'),
        );
    }

    public function pipesCodeProvider()
    {
        $variations = array(
            'fwrite(STDOUT, $in = file_get_contents(\'php://stdin\')); fwrite(STDERR, $in);',
            'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
        );

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            // Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
            $sizes = array(1, 2, 4, 8);
        } else {
            $sizes = array(1, 16, 64, 1024, 4096);
        }

        $codes = array();
        foreach ($sizes as $size) {
            foreach ($variations as $code) {
                $codes[] = array($code, $size);
            }
        }

        return $codes;
    }

    /**
     * provides default method names for simple getter/setter
     */
    public function methodProvider()
    {
        $defaults = array(
            array('CommandLine'),
            array('Timeout'),
            array('WorkingDirectory'),
            array('Env'),
            array('Stdin'),
            array('Options')
        );

        return $defaults;
    }

    /**
     * @param string  $commandline
     * @param null    $cwd
     * @param array   $env
     * @param null    $stdin
     * @param integer $timeout
     * @param array   $options
     *
     * @return Process
     */
    abstract protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array());
}
PK)1[=�,j��:Process/Symfony/Component/Process/Tests/SignalListener.phpnu�[���<?php

// required for signal handling
declare(ticks = 1);

pcntl_signal(SIGUSR1, function () {echo "Caught SIGUSR1"; exit;});

$n=0;

// ticks require activity to work - sleep(4); does not work
while ($n < 400) {
    usleep(10000);
    $n++;
}

return;
PK)1[���
��=Process/Symfony/Component/Process/Tests/SimpleProcessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Process;

class SimpleProcessTest extends AbstractProcessTest
{
    private $enabledSigchild = false;

    public function setUp()
    {
        ob_start();
        phpinfo(INFO_GENERAL);

        $this->enabledSigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
    }

    public function testGetExitCode()
    {
        $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case
        parent::testGetExitCode();
    }

    public function testExitCodeCommandFailed()
    {
        $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case
        parent::testExitCodeCommandFailed();
    }

    public function testProcessIsSignaledIfStopped()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
        parent::testProcessIsSignaledIfStopped();
    }

    public function testProcessWithTermSignal()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
        parent::testProcessWithTermSignal();
    }

    public function testProcessIsNotSignaled()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
        parent::testProcessIsNotSignaled();
    }

    public function testProcessWithoutTermSignal()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
        parent::testProcessWithoutTermSignal();
    }

    public function testExitCodeText()
    {
        $this->skipIfPHPSigchild(); // This test use exitcode that is not available in this case
        parent::testExitCodeText();
    }

    public function testIsSuccessful()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testIsSuccessful();
    }

    public function testIsNotSuccessful()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testIsNotSuccessful();
    }

    public function testGetPid()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testGetPid();
    }

    public function testGetPidIsNullBeforeStart()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testGetPidIsNullBeforeStart();
    }

    public function testGetPidIsNullAfterRun()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testGetPidIsNullAfterRun();
    }

    public function testSignal()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
        parent::testSignal();
    }

    public function testProcessWithoutTermSignalIsNotSignaled()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved');
        parent::testProcessWithoutTermSignalIsNotSignaled();
    }

    public function testProcessThrowsExceptionWhenExternallySignaled()
    {
        $this->skipIfPHPSigchild(); // This test use PID that is not available in this case
        parent::testProcessThrowsExceptionWhenExternallySignaled();
    }

    public function testExitCodeIsAvailableAfterSignal()
    {
        $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
        parent::testExitCodeIsAvailableAfterSignal();
    }

    public function testSignalProcessNotRunning()
    {
        $this->setExpectedException('Symfony\Component\Process\Exception\LogicException', 'Can not send signal on a non running process.');
        parent::testSignalProcessNotRunning();
    }

    public function testSignalWithWrongIntSignal()
    {
        if ($this->enabledSigchild) {
            $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
        } else {
            $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'Error while sending signal `-4`.');
        }
        parent::testSignalWithWrongIntSignal();
    }

    public function testSignalWithWrongNonIntSignal()
    {
        if ($this->enabledSigchild) {
            $this->expectExceptionIfPHPSigchild('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
        } else {
            $this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'Error while sending signal `Céphalopodes`.');
        }
        parent::testSignalWithWrongNonIntSignal();
    }

    /**
     * {@inheritdoc}
     */
    protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
    {
        return new Process($commandline, $cwd, $env, $stdin, $timeout, $options);
    }

    private function skipIfPHPSigchild()
    {
        if ($this->enabledSigchild) {
            $this->markTestSkipped('Your PHP has been compiled with --enable-sigchild, this test can not be executed');
        }
    }

    private function expectExceptionIfPHPSigchild($classname, $message)
    {
        if ($this->enabledSigchild) {
            $this->setExpectedException($classname, $message);
        }
    }
}
PK)1[�+�v,,>Process/Symfony/Component/Process/Tests/NonStopableProcess.phpnu�[���<?php

/**
 * Runs a PHP script that can be stopped only with a SIGKILL (9) signal for 3 seconds
 *
 * @args duration Run this script with a custom duration
 *
 * @example `php NonStopableProcess.php 42` will run the script for 42 seconds
 */

function handleSignal($signal)
{
    switch ($signal) {
        case SIGTERM:
            $name = 'SIGTERM';
            break;
        case SIGINT:
            $name = 'SIGINT';
            break;
        default:
            $name = $signal . ' (unknown)';
            break;
    }

    echo "received signal $name\n";
}

declare(ticks = 1);
pcntl_signal(SIGTERM, 'handleSignal');
pcntl_signal(SIGINT, 'handleSignal');

$duration = isset($argv[1]) ? (int) $argv[1] : 3;
$start = microtime(true);

while ($duration > (microtime(true) - $start)) {
    usleep(1000);
}
PK)1[m�����HProcess/Symfony/Component/Process/Tests/ProcessInSigchildEnvironment.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\Process;

class ProcessInSigchildEnvironment extends Process
{
    protected function isSigchildEnabled()
    {
        return true;
    }
}
PK)1[����GProcess/Symfony/Component/Process/Tests/SigchildDisabledProcessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

class SigchildDisabledProcessTest extends AbstractProcessTest
{
    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testGetExitCode()
    {
        parent::testGetExitCode();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testGetExitCodeIsNullOnStart()
    {
        parent::testGetExitCodeIsNullOnStart();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testGetExitCodeIsNullOnWhenStartingAgain()
    {
        parent::testGetExitCodeIsNullOnWhenStartingAgain();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testExitCodeCommandFailed()
    {
        parent::testExitCodeCommandFailed();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessIsSignaledIfStopped()
    {
        parent::testProcessIsSignaledIfStopped();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithTermSignal()
    {
        parent::testProcessWithTermSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessIsNotSignaled()
    {
        parent::testProcessIsNotSignaled();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage his PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithoutTermSignal()
    {
        parent::testProcessWithoutTermSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testCheckTimeoutOnStartedProcess()
    {
        parent::testCheckTimeoutOnStartedProcess();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPid()
    {
        parent::testGetPid();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPidIsNullBeforeStart()
    {
        parent::testGetPidIsNullBeforeStart();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPidIsNullAfterRun()
    {
        parent::testGetPidIsNullAfterRun();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testExitCodeText()
    {
        $process = $this->getProcess('qdfsmfkqsdfmqmsd');
        $process->run();

        $process->getExitCodeText();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testExitCodeTextIsNullWhenExitCodeIsNull()
    {
        parent::testExitCodeTextIsNullWhenExitCodeIsNull();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testIsSuccessful()
    {
        parent::testIsSuccessful();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testIsSuccessfulOnlyAfterTerminated()
    {
        parent::testIsSuccessfulOnlyAfterTerminated();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testIsNotSuccessful()
    {
        parent::testIsNotSuccessful();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.
     */
    public function testTTYCommandExitCode()
    {
        parent::testTTYCommandExitCode();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process can not be signaled.
     */
    public function testSignal()
    {
        parent::testSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithoutTermSignalIsNotSignaled()
    {
        parent::testProcessWithoutTermSignalIsNotSignaled();
    }

    public function testStopWithTimeoutIsActuallyWorking()
    {
        $this->markTestSkipped('Stopping with signal is not supported in sigchild environment');
    }

    public function testProcessThrowsExceptionWhenExternallySignaled()
    {
        $this->markTestSkipped('Retrieving Pid is not supported in sigchild environment');
    }

    public function testExitCodeIsAvailableAfterSignal()
    {
        $this->markTestSkipped('Signal is not supported in sigchild environment');
    }

    /**
     * {@inheritdoc}
     */
    protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
    {
        $process = new ProcessInSigchildEnvironment($commandline, $cwd, $env, $stdin, $timeout, $options);
        $process->setEnhanceSigchildCompatibility(false);

        return $process;
    }
}
PK)1[H��spp>Process/Symfony/Component/Process/Tests/ProcessBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\ProcessBuilder;

class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testInheritEnvironmentVars()
    {
        $_ENV['MY_VAR_1'] = 'foo';

        $proc = ProcessBuilder::create()
            ->add('foo')
            ->getProcess();

        unset($_ENV['MY_VAR_1']);

        $env = $proc->getEnv();
        $this->assertArrayHasKey('MY_VAR_1', $env);
        $this->assertEquals('foo', $env['MY_VAR_1']);
    }

    public function testAddEnvironmentVariables()
    {
        $pb = new ProcessBuilder();
        $env = array(
            'foo' => 'bar',
            'foo2' => 'bar2',
        );
        $proc = $pb
            ->add('command')
            ->setEnv('foo', 'bar2')
            ->addEnvironmentVariables($env)
            ->inheritEnvironmentVariables(false)
            ->getProcess()
        ;

        $this->assertSame($env, $proc->getEnv());
    }

    public function testProcessShouldInheritAndOverrideEnvironmentVars()
    {
        $_ENV['MY_VAR_1'] = 'foo';

        $proc = ProcessBuilder::create()
            ->setEnv('MY_VAR_1', 'bar')
            ->add('foo')
            ->getProcess();

        unset($_ENV['MY_VAR_1']);

        $env = $proc->getEnv();
        $this->assertArrayHasKey('MY_VAR_1', $env);
        $this->assertEquals('bar', $env['MY_VAR_1']);
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
     */
    public function testNegativeTimeoutFromSetter()
    {
        $pb = new ProcessBuilder();
        $pb->setTimeout(-1);
    }

    public function testNullTimeout()
    {
        $pb = new ProcessBuilder();
        $pb->setTimeout(10);
        $pb->setTimeout(null);

        $r = new \ReflectionObject($pb);
        $p = $r->getProperty('timeout');
        $p->setAccessible(true);

        $this->assertNull($p->getValue($pb));
    }

    public function testShouldSetArguments()
    {
        $pb = new ProcessBuilder(array('initial'));
        $pb->setArguments(array('second'));

        $proc = $pb->getProcess();

        $this->assertContains("second", $proc->getCommandLine());
    }

    public function testPrefixIsPrependedToAllGeneratedProcess()
    {
        $pb = new ProcessBuilder();
        $pb->setPrefix('/usr/bin/php');

        $proc = $pb->setArguments(array('-v'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "-v"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' '-v'", $proc->getCommandLine());
        }

        $proc = $pb->setArguments(array('-i'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "-i"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' '-i'", $proc->getCommandLine());
        }
    }

    public function testArrayPrefixesArePrependedToAllGeneratedProcess()
    {
        $pb = new ProcessBuilder();
        $pb->setPrefix(array('/usr/bin/php', 'composer.phar'));

        $proc = $pb->setArguments(array('-v'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "composer.phar" "-v"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' 'composer.phar' '-v'", $proc->getCommandLine());
        }

        $proc = $pb->setArguments(array('-i'))->getProcess();
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php" "composer.phar" "-i"', $proc->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php' 'composer.phar' '-i'", $proc->getCommandLine());
        }
    }

    public function testShouldEscapeArguments()
    {
        $pb = new ProcessBuilder(array('%path%', 'foo " bar', '%baz%baz'));
        $proc = $pb->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertSame('^%"path"^% "foo \\" bar" "%baz%baz"', $proc->getCommandLine());
        } else {
            $this->assertSame("'%path%' 'foo \" bar' '%baz%baz'", $proc->getCommandLine());
        }
    }

    public function testShouldEscapeArgumentsAndPrefix()
    {
        $pb = new ProcessBuilder(array('arg'));
        $pb->setPrefix('%prefix%');
        $proc = $pb->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertSame('^%"prefix"^% "arg"', $proc->getCommandLine());
        } else {
            $this->assertSame("'%prefix%' 'arg'", $proc->getCommandLine());
        }
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\LogicException
     */
    public function testShouldThrowALogicExceptionIfNoPrefixAndNoArgument()
    {
        ProcessBuilder::create()->getProcess();
    }

    public function testShouldNotThrowALogicExceptionIfNoArgument()
    {
        $process = ProcessBuilder::create()
            ->setPrefix('/usr/bin/php')
            ->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
        }
    }

    public function testShouldNotThrowALogicExceptionIfNoPrefix()
    {
        $process = ProcessBuilder::create(array('/usr/bin/php'))
            ->getProcess();

        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
        } else {
            $this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
        }
    }
}
PK)1[x[��:Process/Symfony/Component/Process/Tests/PhpProcessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\PhpProcess;

class PhpProcessTest extends \PHPUnit_Framework_TestCase
{
    public function testNonBlockingWorks()
    {
        $expected = 'hello world!';
        $process = new PhpProcess(<<<PHP
<?php echo '$expected';
PHP
        );
        $process->start();
        $process->wait();
        $this->assertEquals($expected, $process->getOutput());
    }
}
PK)1[钊�\\FProcess/Symfony/Component/Process/Tests/SigchildEnabledProcessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Process\Tests;

class SigchildEnabledProcessTest extends AbstractProcessTest
{
    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessIsSignaledIfStopped()
    {
        parent::testProcessIsSignaledIfStopped();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithTermSignal()
    {
        parent::testProcessWithTermSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessIsNotSignaled()
    {
        parent::testProcessIsNotSignaled();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithoutTermSignal()
    {
        parent::testProcessWithoutTermSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPid()
    {
        parent::testGetPid();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPidIsNullBeforeStart()
    {
        parent::testGetPidIsNullBeforeStart();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.
     */
    public function testGetPidIsNullAfterRun()
    {
        parent::testGetPidIsNullAfterRun();
    }

    public function testExitCodeText()
    {
        $process = $this->getProcess('qdfsmfkqsdfmqmsd');
        $process->run();

        $this->assertInternalType('string', $process->getExitCodeText());
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. The process can not be signaled.
     */
    public function testSignal()
    {
        parent::testSignal();
    }

    /**
     * @expectedException \Symfony\Component\Process\Exception\RuntimeException
     * @expectedExceptionMessage This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.
     */
    public function testProcessWithoutTermSignalIsNotSignaled()
    {
        parent::testProcessWithoutTermSignalIsNotSignaled();
    }

    public function testProcessThrowsExceptionWhenExternallySignaled()
    {
        $this->markTestSkipped('Retrieving Pid is not supported in sigchild environment');
    }

    public function testExitCodeIsAvailableAfterSignal()
    {
        $this->markTestSkipped('Signal is not supported in sigchild environment');
    }

    public function testStartAfterATimeout()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Restarting a timed-out process on Windows is not supported in sigchild environment');
        }
        parent::testStartAfterATimeout();
    }

    /**
     * {@inheritdoc}
     */
    protected function getProcess($commandline, $cwd = null, array $env = null, $stdin = null, $timeout = 60, array $options = array())
    {
        $process = new ProcessInSigchildEnvironment($commandline, $cwd, $env, $stdin, $timeout, $options);
        $process->setEnhanceSigchildCompatibility(true);

        return $process;
    }
}
PK)1[p\H2Process/Symfony/Component/Process/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Process Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK*1[2�c�$�$@Serializer/Symfony/Component/Serializer/Tests/SerializerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests;

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
use Symfony\Component\Serializer\Tests\Fixtures\TraversableDummy;
use Symfony\Component\Serializer\Tests\Fixtures\NormalizableTraversableDummy;
use Symfony\Component\Serializer\Tests\Normalizer\TestNormalizer;
use Symfony\Component\Serializer\Tests\Normalizer\TestDenormalizer;

class SerializerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testNormalizeNoMatch()
    {
        $this->serializer = new Serializer(array($this->getMock('Symfony\Component\Serializer\Normalizer\CustomNormalizer')));
        $this->serializer->normalize(new \stdClass(), 'xml');
    }

    public function testNormalizeTraversable()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $result = $this->serializer->serialize(new TraversableDummy(), 'json');
        $this->assertEquals('{"foo":"foo","bar":"bar"}', $result);
    }

    public function testNormalizeGivesPriorityToInterfaceOverTraversable()
    {
        $this->serializer = new Serializer(array(new CustomNormalizer()), array('json' => new JsonEncoder()));
        $result = $this->serializer->serialize(new NormalizableTraversableDummy(), 'json');
        $this->assertEquals('{"foo":"normalizedFoo","bar":"normalizedBar"}', $result);
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testNormalizeOnDenormalizer()
    {
        $this->serializer = new Serializer(array(new TestDenormalizer()), array());
        $this->assertTrue($this->serializer->normalize(new \stdClass(), 'json'));
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testDenormalizeNoMatch()
    {
        $this->serializer = new Serializer(array($this->getMock('Symfony\Component\Serializer\Normalizer\CustomNormalizer')));
        $this->serializer->denormalize('foo', 'stdClass');
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testDenormalizeOnNormalizer()
    {
        $this->serializer = new Serializer(array(new TestNormalizer()), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->assertTrue($this->serializer->denormalize(json_encode($data), 'stdClass', 'json'));
    }

    public function testSerialize()
    {
        $this->serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $result = $this->serializer->serialize(Model::fromArray($data), 'json');
        $this->assertEquals(json_encode($data), $result);
    }

    public function testSerializeScalar()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $result = $this->serializer->serialize('foo', 'json');
        $this->assertEquals('"foo"', $result);
    }

    public function testSerializeArrayOfScalars()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $data = array('foo', array(5, 3));
        $result = $this->serializer->serialize($data, 'json');
        $this->assertEquals(json_encode($data), $result);
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testSerializeNoEncoder()
    {
        $this->serializer = new Serializer(array(), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->serialize($data, 'json');
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\LogicException
     */
    public function testSerializeNoNormalizer()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->serialize(Model::fromArray($data), 'json');
    }

    public function testDeserialize()
    {
        $this->serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $result = $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
        $this->assertEquals($data, $result->toArray());
    }

    public function testDeserializeUseCache()
    {
        $this->serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
        $data = array('title' => 'bar', 'numbers' => array(2, 8));
        $result = $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
        $this->assertEquals($data, $result->toArray());
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\LogicException
     */
    public function testDeserializeNoNormalizer()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testDeserializeWrongNormalizer()
    {
        $this->serializer = new Serializer(array(new CustomNormalizer()), array('json' => new JsonEncoder()));
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testDeserializeNoEncoder()
    {
        $this->serializer = new Serializer(array(), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json');
    }

    public function testDeserializeSupported()
    {
        $this->serializer = new Serializer(array(new GetSetMethodNormalizer()), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->assertTrue($this->serializer->supportsDenormalization(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json'));
    }

    public function testDeserializeNotSupported()
    {
        $this->serializer = new Serializer(array(new GetSetMethodNormalizer()), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->assertFalse($this->serializer->supportsDenormalization(json_encode($data), 'stdClass', 'json'));
    }

    public function testDeserializeNotSupportedMissing()
    {
        $this->serializer = new Serializer(array(), array());
        $data = array('title' => 'foo', 'numbers' => array(5, 3));
        $this->assertFalse($this->serializer->supportsDenormalization(json_encode($data), '\Symfony\Component\Serializer\Tests\Model', 'json'));
    }

    public function testEncode()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $data = array('foo', array(5, 3));
        $result = $this->serializer->encode($data, 'json');
        $this->assertEquals(json_encode($data), $result);
    }

    public function testDecode()
    {
        $this->serializer = new Serializer(array(), array('json' => new JsonEncoder()));
        $data = array('foo', array(5, 3));
        $result = $this->serializer->decode(json_encode($data), 'json');
        $this->assertEquals($data, $result);
    }
}

class Model
{
    private $title;
    private $numbers;

    public static function fromArray($array)
    {
        $model = new self();
        if (isset($array['title'])) {
            $model->setTitle($array['title']);
        }
        if (isset($array['numbers'])) {
            $model->setNumbers($array['numbers']);
        }

        return $model;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getNumbers()
    {
        return $this->numbers;
    }

    public function setNumbers($numbers)
    {
        $this->numbers = $numbers;
    }

    public function toArray()
    {
        return array('title' => $this->title, 'numbers' => $this->numbers);
    }
}
PK*1[�m�))KSerializer/Symfony/Component/Serializer/Tests/Normalizer/TestNormalizer.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Normalizer;

use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

/**
 * Provides a test Normalizer which only implements the NormalizerInterface.
 *
 * @author Lin Clark <lin@lin-clark.com>
 */
class TestNormalizer implements NormalizerInterface
{
    /**
    * {@inheritdoc}
    */
    public function normalize($object, $format = null, array $context = array())
    {
    }

    /**
    * {@inheritdoc}
    */
    public function supportsNormalization($data, $format = null)
    {
        return true;
    }
}
PK*1[$ѕ�QSerializer/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Normalizer;

use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
use Symfony\Component\Serializer\Serializer;

class CustomNormalizerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->normalizer = new CustomNormalizer();
        $this->normalizer->setSerializer(new Serializer());
    }

    public function testSerialize()
    {
        $obj = new ScalarDummy();
        $obj->foo = 'foo';
        $obj->xmlFoo = 'xml';
        $this->assertEquals('foo', $this->normalizer->normalize($obj, 'json'));
        $this->assertEquals('xml', $this->normalizer->normalize($obj, 'xml'));
    }

    public function testDeserialize()
    {
        $obj = $this->normalizer->denormalize('foo', get_class(new ScalarDummy()), 'xml');
        $this->assertEquals('foo', $obj->xmlFoo);
        $this->assertNull($obj->foo);

        $obj = $this->normalizer->denormalize('foo', get_class(new ScalarDummy()), 'json');
        $this->assertEquals('foo', $obj->foo);
        $this->assertNull($obj->xmlFoo);
    }

    public function testSupportsNormalization()
    {
        $this->assertTrue($this->normalizer->supportsNormalization(new ScalarDummy()));
        $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
    }

    public function testSupportsDenormalization()
    {
        $this->assertTrue($this->normalizer->supportsDenormalization(array(), 'Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy'));
        $this->assertFalse($this->normalizer->supportsDenormalization(array(), 'stdClass'));
        $this->assertTrue($this->normalizer->supportsDenormalization(array(), 'Symfony\Component\Serializer\Tests\Fixtures\DenormalizableDummy'));
    }
}
PK*1[��P1!!WSerializer/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Normalizer;

use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class GetSetMethodNormalizerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->serializer = $this->getMock(__NAMESPACE__.'\SerializerNormalizer');
        $this->normalizer = new GetSetMethodNormalizer();
        $this->normalizer->setSerializer($this->serializer);
    }

    public function testNormalize()
    {
        $obj = new GetSetDummy();
        $object = new \stdClass();
        $obj->setFoo('foo');
        $obj->setBar('bar');
        $obj->setCamelCase('camelcase');
        $obj->setObject($object);

        $this->serializer
            ->expects($this->once())
            ->method('normalize')
            ->with($object, 'any')
            ->will($this->returnValue('string_object'))
        ;

        $this->assertEquals(
            array(
                'foo' => 'foo',
                'bar' => 'bar',
                'fooBar' => 'foobar',
                'camelCase' => 'camelcase',
                'object' => 'string_object',
            ),
            $this->normalizer->normalize($obj, 'any')
        );
    }

    public function testDenormalize()
    {
        $obj = $this->normalizer->denormalize(
            array('foo' => 'foo', 'bar' => 'bar', 'fooBar' => 'foobar'),
            __NAMESPACE__.'\GetSetDummy',
            'any'
        );
        $this->assertEquals('foo', $obj->getFoo());
        $this->assertEquals('bar', $obj->getBar());
    }

    public function testDenormalizeOnCamelCaseFormat()
    {
        $this->normalizer->setCamelizedAttributes(array('camel_case'));
        $obj = $this->normalizer->denormalize(
            array('camel_case' => 'camelCase'),
            __NAMESPACE__.'\GetSetDummy'
        );
        $this->assertEquals('camelCase', $obj->getCamelCase());
    }

    /**
     * @dataProvider attributeProvider
     */
    public function testFormatAttribute($attribute, $camelizedAttributes, $result)
    {
        $r = new \ReflectionObject($this->normalizer);
        $m = $r->getMethod('formatAttribute');
        $m->setAccessible(true);

        $this->normalizer->setCamelizedAttributes($camelizedAttributes);
        $this->assertEquals($m->invoke($this->normalizer, $attribute, $camelizedAttributes), $result);
    }

    public function attributeProvider()
    {
        return array(
            array('attribute_test', array('attribute_test'),'AttributeTest'),
            array('attribute_test', array('any'),'attribute_test'),
            array('attribute', array('attribute'),'Attribute'),
            array('attribute', array(), 'attribute'),
        );
    }

    public function testConstructorDenormalize()
    {
        $obj = $this->normalizer->denormalize(
            array('foo' => 'foo', 'bar' => 'bar', 'fooBar' => 'foobar'),
            __NAMESPACE__.'\GetConstructorDummy', 'any');
        $this->assertEquals('foo', $obj->getFoo());
        $this->assertEquals('bar', $obj->getBar());
    }

    /**
     * @dataProvider provideCallbacks
     */
    public function testCallbacks($callbacks, $value, $result, $message)
    {
        $this->normalizer->setCallbacks($callbacks);

        $obj = new GetConstructorDummy('', $value);

        $this->assertEquals(
            $result,
            $this->normalizer->normalize($obj, 'any'),
            $message
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testUncallableCallbacks()
    {
        $this->normalizer->setCallbacks(array('bar' => null));

        $obj = new GetConstructorDummy('baz', 'quux');

        $this->normalizer->normalize($obj, 'any');
    }

    public function testIgnoredAttributes()
    {
        $this->normalizer->setIgnoredAttributes(array('foo', 'bar', 'camelCase', 'object'));

        $obj = new GetSetDummy();
        $obj->setFoo('foo');
        $obj->setBar('bar');

        $this->assertEquals(
            array('fooBar' => 'foobar'),
            $this->normalizer->normalize($obj, 'any')
        );
    }

    public function provideCallbacks()
    {
        return array(
            array(
                array(
                    'bar' => function ($bar) {
                        return 'baz';
                    },
                ),
                'baz',
                array('foo' => '', 'bar' => 'baz'),
                'Change a string',
            ),
            array(
                array(
                    'bar' => function ($bar) {
                        return null;
                    },
                ),
                'baz',
                array('foo' => '', 'bar' => null),
                'Null an item'
            ),
            array(
                array(
                    'bar' => function ($bar) {
                        return $bar->format('d-m-Y H:i:s');
                    },
                ),
                new \DateTime('2011-09-10 06:30:00'),
                array('foo' => '', 'bar' => '10-09-2011 06:30:00'),
                'Format a date',
            ),
            array(
                array(
                    'bar' => function ($bars) {
                        $foos = '';
                        foreach ($bars as $bar) {
                            $foos .= $bar->getFoo();
                        }

                        return $foos;
                    },
                ),
                array(new GetConstructorDummy('baz', ''), new GetConstructorDummy('quux', '')),
                array('foo' => '', 'bar' => 'bazquux'),
                'Collect a property',
            ),
            array(
                array(
                    'bar' => function ($bars) {
                        return count($bars);
                    },
                ),
                array(new GetConstructorDummy('baz', ''), new GetConstructorDummy('quux', '')),
                array('foo' => '', 'bar' => 2),
                'Count a property',
            ),
        );
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Cannot normalize attribute "object" because injected serializer is not a normalizer
     */
    public function testUnableToNormalizeObjectAttribute()
    {
        $serializer = $this->getMock('Symfony\Component\Serializer\SerializerInterface');
        $this->normalizer->setSerializer($serializer);

        $obj    = new GetSetDummy();
        $object = new \stdClass();
        $obj->setObject($object);

        $this->normalizer->normalize($obj, 'any');
    }
}

class GetSetDummy
{
    protected $foo;
    private $bar;
    protected $camelCase;
    protected $object;

    public function getFoo()
    {
        return $this->foo;
    }

    public function setFoo($foo)
    {
        $this->foo = $foo;
    }

    public function getBar()
    {
        return $this->bar;
    }

    public function setBar($bar)
    {
        $this->bar = $bar;
    }

    public function getFooBar()
    {
        return $this->foo.$this->bar;
    }

    public function getCamelCase()
    {
        return $this->camelCase;
    }

    public function setCamelCase($camelCase)
    {
        $this->camelCase = $camelCase;
    }

    public function otherMethod()
    {
        throw new \RuntimeException("Dummy::otherMethod() should not be called");
    }

    public function setObject($object)
    {
        $this->object = $object;
    }

    public function getObject()
    {
        return $this->object;
    }
}

class GetConstructorDummy
{
    protected $foo;
    private $bar;

    public function __construct($foo, $bar)
    {
        $this->foo = $foo;
        $this->bar = $bar;
    }

    public function getFoo()
    {
        return $this->foo;
    }

    public function getBar()
    {
        return $this->bar;
    }

    public function otherMethod()
    {
        throw new \RuntimeException("Dummy::otherMethod() should not be called");
    }
}

abstract class SerializerNormalizer implements SerializerInterface, NormalizerInterface
{
}
PK*1[�qBBMSerializer/Symfony/Component/Serializer/Tests/Normalizer/TestDenormalizer.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Normalizer;

use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

/**
 * Provides a test Normalizer which only implements the DenormalizerInterface.
 *
 * @author Lin Clark <lin@lin-clark.com>
 */
class TestDenormalizer implements DenormalizerInterface
{
    /**
    * {@inheritdoc}
    */
    public function denormalize($data, $class, $format = null, array $context = array())
    {
    }

    /**
    * {@inheritdoc}
    */
    public function supportsDenormalization($data, $type, $format = null)
    {
        return true;
    }
}
PK*1[��K�__FSerializer/Symfony/Component/Serializer/Tests/Fixtures/ScalarDummy.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Fixtures;

use Symfony\Component\Serializer\Normalizer\NormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class ScalarDummy implements NormalizableInterface, DenormalizableInterface
{
    public $foo;
    public $xmlFoo;

    public function normalize(NormalizerInterface $normalizer, $format = null, array $context = array())
    {
        return $format === 'xml' ? $this->xmlFoo : $this->foo;
    }

    public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array())
    {
        if ($format === 'xml') {
            $this->xmlFoo = $data;
        } else {
            $this->foo = $data;
        }
    }
}
PK*1[��_��KSerializer/Symfony/Component/Serializer/Tests/Fixtures/TraversableDummy.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Fixtures;

class TraversableDummy implements \IteratorAggregate
{
    public $foo = 'foo';
    public $bar = 'bar';

    public function getIterator()
    {
        return new \ArrayIterator(get_object_vars($this));
    }
}
PK*1[G��5��WSerializer/Symfony/Component/Serializer/Tests/Fixtures/NormalizableTraversableDummy.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Fixtures;

use Symfony\Component\Serializer\Normalizer\NormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class NormalizableTraversableDummy extends TraversableDummy implements NormalizableInterface, DenormalizableInterface
{
    public function normalize(NormalizerInterface $normalizer, $format = null, array $context = array())
    {
        return array(
            'foo' => 'normalizedFoo',
            'bar' => 'normalizedBar',
        );
    }

    public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array())
    {
        return array(
            'foo' => 'denormalizedFoo',
            'bar' => 'denormalizedBar',
        );
    }
}
PK*1[�LY��@Serializer/Symfony/Component/Serializer/Tests/Fixtures/Dummy.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Fixtures;

use Symfony\Component\Serializer\Normalizer\NormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class Dummy implements NormalizableInterface, DenormalizableInterface
{
    public $foo;
    public $bar;
    public $baz;
    public $qux;

    public function normalize(NormalizerInterface $normalizer, $format = null, array $context = array())
    {
        return array(
            'foo' => $this->foo,
            'bar' => $this->bar,
            'baz' => $this->baz,
            'qux' => $this->qux,
        );
    }

    public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array())
    {
        $this->foo = $data['foo'];
        $this->bar = $data['bar'];
        $this->baz = $data['baz'];
        $this->qux = $data['qux'];
    }
}
PK*1[Y["�uuNSerializer/Symfony/Component/Serializer/Tests/Fixtures/DenormalizableDummy.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Fixtures;

use Symfony\Component\Serializer\Normalizer\DenormalizableInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;

class DenormalizableDummy implements DenormalizableInterface
{

    public function denormalize(DenormalizerInterface $denormalizer, $data, $format = null, array $context = array())
    {

    }

}
PK*1[f|�B.B.HSerializer/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Encoder;

use Symfony\Component\Serializer\Tests\Fixtures\Dummy;
use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;

class XmlEncoderTest extends \PHPUnit_Framework_TestCase
{
    private $encoder;

    protected function setUp()
    {
        $this->encoder = new XmlEncoder();
        $serializer = new Serializer(array(new CustomNormalizer()), array('xml' => new XmlEncoder()));
        $this->encoder->setSerializer($serializer);
    }

    public function testEncodeScalar()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = "foo";

        $expected = '<?xml version="1.0"?>'."\n".
            '<response>foo</response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
    }

    public function testSetRootNodeName()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = "foo";

        $this->encoder->setRootNodeName('test');
        $expected = '<?xml version="1.0"?>'."\n".
            '<test>foo</test>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
    }

    /**
     * @expectedException        \Symfony\Component\Serializer\Exception\UnexpectedValueException
     * @expectedExceptionMessage Document types are not allowed.
     */
    public function testDocTypeIsNotAllowed()
    {
        $this->encoder->decode('<?xml version="1.0"?><!DOCTYPE foo><foo></foo>', 'foo');
    }

    public function testAttributes()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = array(
            'foo-bar' => array(
                '@id' => 1,
                '@name' => 'Bar'
            ),
            'Foo' => array(
                'Bar' => "Test",
                '@Type' => 'test'
            ),
            'föo_bär' => 'a',
            "Bar" => array(1,2,3),
            'a' => 'b',
        );
        $expected = '<?xml version="1.0"?>'."\n".
            '<response>'.
            '<foo-bar id="1" name="Bar"/>'.
            '<Foo Type="test"><Bar>Test</Bar></Foo>'.
            '<föo_bär>a</föo_bär>'.
            '<Bar>1</Bar>'.
            '<Bar>2</Bar>'.
            '<Bar>3</Bar>'.
            '<a>b</a>'.
            '</response>'."\n";
        $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
    }

    public function testElementNameValid()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = array(
            'foo-bar' => 'a',
            'foo_bar' => 'a',
            'föo_bär' => 'a',
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<response>'.
            '<foo-bar>a</foo-bar>'.
            '<foo_bar>a</foo_bar>'.
            '<föo_bär>a</föo_bär>'.
            '</response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
    }

    public function testEncodeSimpleXML()
    {
        $xml = simplexml_load_string('<firstname>Peter</firstname>');
        $array = array('person' => $xml);

        $expected = '<?xml version="1.0"?>'."\n".
            '<response><person><firstname>Peter</firstname></person></response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
    }

    public function testEncodeXmlAttributes()
    {
        $xml = simplexml_load_string('<firstname>Peter</firstname>');
        $array = array('person' => $xml);

        $expected = '<?xml version="1.1" encoding="utf-8" standalone="yes"?>'."\n".
            '<response><person><firstname>Peter</firstname></person></response>'."\n";

        $context = array(
            'xml_version' => '1.1',
            'xml_encoding' => 'utf-8',
            'xml_standalone' => true,
        );

        $this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
    }

    public function testEncodeScalarRootAttributes()
    {
        $array = array(
          '#' => 'Paul',
          '@gender' => 'm'
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<response gender="m">Paul</response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
    }

    public function testEncodeRootAttributes()
    {
        $array = array(
          'firstname' => 'Paul',
          '@gender' => 'm'
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<response gender="m"><firstname>Paul</firstname></response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
    }

    public function testEncodeCdataWrapping()
    {
        $array = array(
          'firstname' => 'Paul <or Me>',
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<response><firstname><![CDATA[Paul <or Me>]]></firstname></response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
    }

    public function testEncodeScalarWithAttribute()
    {
        $array = array(
            'person' => array('@gender' => 'M', '#' => 'Peter'),
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<response><person gender="M">Peter</person></response>'."\n";

        $this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
    }

    public function testDecodeScalar()
    {
        $source = '<?xml version="1.0"?>'."\n".
            '<response>foo</response>'."\n";

        $this->assertEquals('foo', $this->encoder->decode($source, 'xml'));
    }

    public function testEncode()
    {
        $source = $this->getXmlSource();
        $obj = $this->getObject();

        $this->assertEquals($source, $this->encoder->encode($obj, 'xml'));
    }

    public function testEncodeSerializerXmlRootNodeNameOption()
    {
        $options = array('xml_root_node_name' => 'test');
        $this->encoder = new XmlEncoder();
        $serializer = new Serializer(array(), array('xml' => new XmlEncoder()));
        $this->encoder->setSerializer($serializer);

        $array = array(
            'person' => array('@gender' => 'M', '#' => 'Peter'),
        );

        $expected = '<?xml version="1.0"?>'."\n".
            '<test><person gender="M">Peter</person></test>'."\n";

        $this->assertEquals($expected, $serializer->serialize($array, 'xml', $options));
    }

    public function testDecode()
    {
        $source = $this->getXmlSource();
        $obj = $this->getObject();

        $this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml'));
    }

    public function testDecodeScalarWithAttribute()
    {
        $source = '<?xml version="1.0"?>'."\n".
            '<response><person gender="M">Peter</person></response>'."\n";

        $expected = array(
            'person' => array('@gender' => 'M', '#' => 'Peter'),
        );

        $this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
    }

    public function testDecodeScalarRootAttributes()
    {
        $source = '<?xml version="1.0"?>'."\n".
            '<person gender="M">Peter</person>'."\n";

        $expected = array(
            '#' => 'Peter',
            '@gender' => 'M'
        );

        $this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
    }

    public function testDecodeRootAttributes()
    {
        $source = '<?xml version="1.0"?>'."\n".
            '<person gender="M"><firstname>Peter</firstname><lastname>Mac Calloway</lastname></person>'."\n";

        $expected = array(
            'firstname' => 'Peter',
            'lastname' => 'Mac Calloway',
            '@gender' => 'M'
        );

        $this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
    }

    public function testDecodeArray()
    {
        $source = '<?xml version="1.0"?>'."\n".
            '<response>'.
            '<people>'.
            '<person><firstname>Benjamin</firstname><lastname>Alexandre</lastname></person>'.
            '<person><firstname>Damien</firstname><lastname>Clay</lastname></person>'.
            '</people>'.
            '</response>'."\n";

        $expected = array(
            'people' => array('person' => array(
                array('firstname' => 'Benjamin', 'lastname' => 'Alexandre'),
                array('firstname' => 'Damien', 'lastname' => 'Clay')
            ))
        );

        $this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
    }

    public function testDecodeWithoutItemHash()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = array(
            'foo-bar' => array(
                '@key' => "value",
                'item' => array("@key" => 'key', "key-val" => 'val')
            ),
            'Foo' => array(
                'Bar' => "Test",
                '@Type' => 'test'
            ),
            'föo_bär' => 'a',
            "Bar" => array(1,2,3),
            'a' => 'b',
        );
        $expected = array(
            'foo-bar' => array(
                '@key' => "value",
                'key' => array('@key' => 'key', "key-val" => 'val')
            ),
            'Foo' => array(
                'Bar' => "Test",
                '@Type' => 'test'
            ),
            'föo_bär' => 'a',
            "Bar" => array(1,2,3),
            'a' => 'b',
        );
        $xml = $this->encoder->encode($obj, 'xml');
        $this->assertEquals($expected, $this->encoder->decode($xml, 'xml'));
    }

    /**
     * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
     */
    public function testDecodeInvalidXml()
    {
        $this->encoder->decode('<?xml version="1.0"?><invalid><xml>', 'xml');
    }

    public function testPreventsComplexExternalEntities()
    {
        $oldCwd = getcwd();
        chdir(__DIR__);

        try {
            $this->encoder->decode('<?xml version="1.0"?><!DOCTYPE scan[<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=XmlEncoderTest.php">]><scan>&test;</scan>', 'xml');
            chdir($oldCwd);

            $this->fail('No exception was thrown.');
        } catch (\Exception $e) {
            chdir($oldCwd);

            if (!$e instanceof UnexpectedValueException) {
                $this->fail('Expected UnexpectedValueException');
            }
        }
    }

    public function testDecodeEmptyXml()
    {
        $this->setExpectedException('Symfony\Component\Serializer\Exception\UnexpectedValueException', 'Invalid XML data, it can not be empty.');
        $this->encoder->decode(' ', 'xml');
    }

    protected function getXmlSource()
    {
        return '<?xml version="1.0"?>'."\n".
            '<response>'.
            '<foo>foo</foo>'.
            '<bar>a</bar><bar>b</bar>'.
            '<baz><key>val</key><key2>val</key2><item key="A B">bar</item>'.
            '<item><title>title1</title></item><item><title>title2</title></item>'.
            '<Barry><FooBar id="1"><Baz>Ed</Baz></FooBar></Barry></baz>'.
            '<qux>1</qux>'.
            '</response>'."\n";
    }

    protected function getObject()
    {
        $obj = new Dummy();
        $obj->foo = 'foo';
        $obj->bar = array('a', 'b');
        $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => array(array('title' => 'title1'), array('title' => 'title2')), 'Barry' => array('FooBar' => array('Baz' => 'Ed', '@id' => 1)));
        $obj->qux = "1";

        return $obj;
    }
}
PK*1[F��		ISerializer/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Serializer\Tests\Encoder;

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;

class JsonEncoderTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->encoder = new JsonEncoder();
        $this->serializer = new Serializer(array(new CustomNormalizer()), array('json' => new JsonEncoder()));
    }

    public function testEncodeScalar()
    {
        $obj = new \stdClass();
        $obj->foo = "foo";

        $expected = '{"foo":"foo"}';

        $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
    }

    public function testComplexObject()
    {
        $obj = $this->getObject();

        $expected = $this->getJsonSource();

        $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
    }

    public function testOptions()
    {
        $context = array('json_encode_options' => JSON_NUMERIC_CHECK);

        $arr = array();
        $arr['foo'] = "3";

        $expected = '{"foo":3}';

        $this->assertEquals($expected, $this->serializer->serialize($arr, 'json', $context));

        $arr = array();
        $arr['foo'] = "3";

        $expected = '{"foo":"3"}';

        $this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent');
    }

    protected function getJsonSource()
    {
        return '{"foo":"foo","bar":["a","b"],"baz":{"key":"val","key2":"val","A B":"bar","item":[{"title":"title1"},{"title":"title2"}],"Barry":{"FooBar":{"Baz":"Ed","@id":1}}},"qux":"1"}';
    }

    protected function getObject()
    {
        $obj = new \stdClass();
        $obj->foo = 'foo';
        $obj->bar = array('a', 'b');
        $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => array(array('title' => 'title1'), array('title' => 'title2')), 'Barry' => array('FooBar' => array('Baz' => 'Ed', '@id' => 1)));
        $obj->qux = "1";

        return $obj;
    }
}
PK*1[���998Serializer/Symfony/Component/Serializer/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Serializer Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK+1[�Ǫ���4Locale/Symfony/Component/Locale/Tests/LocaleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Locale\Tests;

use Symfony\Component\Intl\Intl;
use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Locale\Locale;

/**
 * Test case for the {@link Locale} class.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class LocaleTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        // Locale extends \Locale, so intl must be present
        IntlTestHelper::requireIntl($this);
    }

    public function testGetDisplayCountries()
    {
        $countries = Locale::getDisplayCountries('en');
        $this->assertEquals('Brazil', $countries['BR']);
    }

    public function testGetCountries()
    {
        $countries = Locale::getCountries();
        $this->assertTrue(in_array('BR', $countries));
    }

    public function testGetDisplayLanguages()
    {
        $languages = Locale::getDisplayLanguages('en');
        $this->assertEquals('Brazilian Portuguese', $languages['pt_BR']);
    }

    public function testGetLanguages()
    {
        $languages = Locale::getLanguages();
        $this->assertTrue(in_array('pt_BR', $languages));
    }

    public function testGetDisplayLocales()
    {
        $locales = Locale::getDisplayLocales('en');
        $this->assertEquals('Portuguese', $locales['pt']);
    }

    public function testGetLocales()
    {
        $locales = Locale::getLocales();
        $this->assertTrue(in_array('pt', $locales));
    }
}
PK+1[<��=Locale/Symfony/Component/Locale/Tests/Stub/StubLocaleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Locale\Tests\Stub;

use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Locale\Stub\StubLocale;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class StubLocaleTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testGetCurrenciesData()
    {
        $currencies = StubLocale::getCurrenciesData('en');
        $this->assertEquals('R$', $currencies['BRL']['symbol']);
        $this->assertEquals('Brazilian Real', $currencies['BRL']['name']);
        $this->assertEquals(2, $currencies['BRL']['fractionDigits']);
        $this->assertEquals(0, $currencies['BRL']['roundingIncrement']);
    }

    public function testGetDisplayCurrencies()
    {
        $currencies = StubLocale::getDisplayCurrencies('en');
        $this->assertEquals('Brazilian Real', $currencies['BRL']);

        // Checking that the cache is being used
        $currencies = StubLocale::getDisplayCurrencies('en');
        $this->assertEquals('Argentine Peso', $currencies['ARS']);
    }

    public function testGetCurrencies()
    {
        $currencies = StubLocale::getCurrencies();
        $this->assertTrue(in_array('BRL', $currencies));
    }
}
PK+1[+��hh0Locale/Symfony/Component/Locale/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Locale Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK+1[�;�DFilesystem/Symfony/Component/Filesystem/Tests/FilesystemTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Filesystem\Tests;

class FilesystemTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string $workspace
     */
    protected $workspace = null;

    protected static $symlinkOnWindows = null;

    public static function setUpBeforeClass()
    {
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            static::$symlinkOnWindows = true;
            $originDir = tempnam(sys_get_temp_dir(), 'sl');
            $targetDir = tempnam(sys_get_temp_dir(), 'sl');
            if (true !== @symlink($originDir, $targetDir)) {
                $report = error_get_last();
                if (is_array($report) && false !== strpos($report['message'], 'error code(1314)')) {
                    static::$symlinkOnWindows = false;
                }
            }
        }
    }

    public function setUp()
    {
        $this->workspace = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.time().rand(0, 1000);
        mkdir($this->workspace, 0777, true);
        $this->workspace = realpath($this->workspace);
    }

    public function tearDown()
    {
        $this->clean($this->workspace);
    }

    /**
     * @param string $file
     */
    protected function clean($file)
    {
        if (is_dir($file) && !is_link($file)) {
            $dir = new \FilesystemIterator($file);
            foreach ($dir as $childFile) {
                $this->clean($childFile);
            }

            rmdir($file);
        } else {
            unlink($file);
        }
    }

    /**
     * @param int $expectedFilePerms expected file permissions as three digits (i.e. 755)
     * @param string $filePath
     */
    protected function assertFilePermissions($expectedFilePerms, $filePath)
    {
        $actualFilePerms = (int) substr(sprintf('%o', fileperms($filePath)), -3);
        $this->assertEquals(
            $expectedFilePerms,
            $actualFilePerms,
            sprintf('File permissions for %s must be %s. Actual %s', $filePath, $expectedFilePerms, $actualFilePerms)
        );
    }

    protected function getFileOwner($filepath)
    {
        $this->markAsSkippedIfPosixIsMissing();

        $infos = stat($filepath);
        if ($datas = posix_getpwuid($infos['uid'])) {
            return $datas['name'];
        }
    }

    protected function getFileGroup($filepath)
    {
        $this->markAsSkippedIfPosixIsMissing();

        $infos = stat($filepath);
        if ($datas = posix_getgrgid($infos['gid'])) {
            return $datas['name'];
        }
    }

    protected function markAsSkippedIfSymlinkIsMissing()
    {
        if (!function_exists('symlink')) {
            $this->markTestSkipped('symlink is not supported');
        }

        if (defined('PHP_WINDOWS_VERSION_MAJOR') && false === static::$symlinkOnWindows) {
            $this->markTestSkipped('symlink requires "Create symbolic links" privilege on windows');
        }
    }

    protected function markAsSkippedIfChmodIsMissing()
    {
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $this->markTestSkipped('chmod is not supported on windows');
        }
    }

    protected function markAsSkippedIfPosixIsMissing()
    {
        if (defined('PHP_WINDOWS_VERSION_MAJOR') || !function_exists('posix_isatty')) {
            $this->markTestSkipped('Posix is not supported');
        }
    }
}
PK+1['B 0�o�o@Filesystem/Symfony/Component/Filesystem/Tests/FilesystemTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Filesystem\Tests;

use Symfony\Component\Filesystem\Filesystem;

/**
 * Test class for Filesystem.
 */
class FilesystemTest extends FilesystemTestCase
{
    /**
     * @var \Symfony\Component\Filesystem\Filesystem $filesystem
     */
    private $filesystem = null;

    public function setUp()
    {
        parent::setUp();
        $this->filesystem = new Filesystem();
    }

    public function testCopyCreatesNewFile()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');

        $this->filesystem->copy($sourceFilePath, $targetFilePath);

        $this->assertFileExists($targetFilePath);
        $this->assertEquals('SOURCE FILE', file_get_contents($targetFilePath));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testCopyFails()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        $this->filesystem->copy($sourceFilePath, $targetFilePath);
    }

    public function testCopyOverridesExistingFileIfModified()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');
        file_put_contents($targetFilePath, 'TARGET FILE');
        touch($targetFilePath, time() - 1000);

        $this->filesystem->copy($sourceFilePath, $targetFilePath);

        $this->assertFileExists($targetFilePath);
        $this->assertEquals('SOURCE FILE', file_get_contents($targetFilePath));
    }

    public function testCopyDoesNotOverrideExistingFileByDefault()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');
        file_put_contents($targetFilePath, 'TARGET FILE');

        // make sure both files have the same modification time
        $modificationTime = time() - 1000;
        touch($sourceFilePath, $modificationTime);
        touch($targetFilePath, $modificationTime);

        $this->filesystem->copy($sourceFilePath, $targetFilePath);

        $this->assertFileExists($targetFilePath);
        $this->assertEquals('TARGET FILE', file_get_contents($targetFilePath));
    }

    public function testCopyOverridesExistingFileIfForced()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');
        file_put_contents($targetFilePath, 'TARGET FILE');

        // make sure both files have the same modification time
        $modificationTime = time() - 1000;
        touch($sourceFilePath, $modificationTime);
        touch($targetFilePath, $modificationTime);

        $this->filesystem->copy($sourceFilePath, $targetFilePath, true);

        $this->assertFileExists($targetFilePath);
        $this->assertEquals('SOURCE FILE', file_get_contents($targetFilePath));
    }

    public function testCopyCreatesTargetDirectoryIfItDoesNotExist()
    {
        $sourceFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_source_file';
        $targetFileDirectory = $this->workspace.DIRECTORY_SEPARATOR.'directory';
        $targetFilePath = $targetFileDirectory.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($sourceFilePath, 'SOURCE FILE');

        $this->filesystem->copy($sourceFilePath, $targetFilePath);

        $this->assertTrue(is_dir($targetFileDirectory));
        $this->assertFileExists($targetFilePath);
        $this->assertEquals('SOURCE FILE', file_get_contents($targetFilePath));
    }

    public function testCopyForOriginUrlsAndExistingLocalFileDefaultsToNotCopy()
    {
        $sourceFilePath = 'http://symfony.com/images/common/logo/logo_symfony_header.png';
        $targetFilePath = $this->workspace.DIRECTORY_SEPARATOR.'copy_target_file';

        file_put_contents($targetFilePath, 'TARGET FILE');

        $this->filesystem->copy($sourceFilePath, $targetFilePath, false);

        $this->assertFileExists($targetFilePath);
        $this->assertEquals(file_get_contents($sourceFilePath), file_get_contents($targetFilePath));
    }

    public function testMkdirCreatesDirectoriesRecursively()
    {
        $directory = $this->workspace
            .DIRECTORY_SEPARATOR.'directory'
            .DIRECTORY_SEPARATOR.'sub_directory';

        $this->filesystem->mkdir($directory);

        $this->assertTrue(is_dir($directory));
    }

    public function testMkdirCreatesDirectoriesFromArray()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;
        $directories = array(
            $basePath.'1', $basePath.'2', $basePath.'3'
        );

        $this->filesystem->mkdir($directories);

        $this->assertTrue(is_dir($basePath.'1'));
        $this->assertTrue(is_dir($basePath.'2'));
        $this->assertTrue(is_dir($basePath.'3'));
    }

    public function testMkdirCreatesDirectoriesFromTraversableObject()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;
        $directories = new \ArrayObject(array(
            $basePath.'1', $basePath.'2', $basePath.'3'
        ));

        $this->filesystem->mkdir($directories);

        $this->assertTrue(is_dir($basePath.'1'));
        $this->assertTrue(is_dir($basePath.'2'));
        $this->assertTrue(is_dir($basePath.'3'));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testMkdirCreatesDirectoriesFails()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;
        $dir = $basePath.'2';

        file_put_contents($dir, '');

        $this->filesystem->mkdir($dir);
    }

    public function testTouchCreatesEmptyFile()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.'1';

        $this->filesystem->touch($file);

        $this->assertFileExists($file);
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testTouchFails()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.'1'.DIRECTORY_SEPARATOR.'2';

        $this->filesystem->touch($file);
    }

    public function testTouchCreatesEmptyFilesFromArray()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;
        $files = array(
            $basePath.'1', $basePath.'2', $basePath.'3'
        );

        $this->filesystem->touch($files);

        $this->assertFileExists($basePath.'1');
        $this->assertFileExists($basePath.'2');
        $this->assertFileExists($basePath.'3');
    }

    public function testTouchCreatesEmptyFilesFromTraversableObject()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;
        $files = new \ArrayObject(array(
            $basePath.'1', $basePath.'2', $basePath.'3'
        ));

        $this->filesystem->touch($files);

        $this->assertFileExists($basePath.'1');
        $this->assertFileExists($basePath.'2');
        $this->assertFileExists($basePath.'3');
    }

    public function testRemoveCleansFilesAndDirectoriesIteratively()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR.'directory'.DIRECTORY_SEPARATOR;

        mkdir($basePath);
        mkdir($basePath.'dir');
        touch($basePath.'file');

        $this->filesystem->remove($basePath);

        $this->assertTrue(!is_dir($basePath));
    }

    public function testRemoveCleansArrayOfFilesAndDirectories()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;

        mkdir($basePath.'dir');
        touch($basePath.'file');

        $files = array(
            $basePath.'dir', $basePath.'file'
        );

        $this->filesystem->remove($files);

        $this->assertTrue(!is_dir($basePath.'dir'));
        $this->assertTrue(!is_file($basePath.'file'));
    }

    public function testRemoveCleansTraversableObjectOfFilesAndDirectories()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;

        mkdir($basePath.'dir');
        touch($basePath.'file');

        $files = new \ArrayObject(array(
            $basePath.'dir', $basePath.'file'
        ));

        $this->filesystem->remove($files);

        $this->assertTrue(!is_dir($basePath.'dir'));
        $this->assertTrue(!is_file($basePath.'file'));
    }

    public function testRemoveIgnoresNonExistingFiles()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;

        mkdir($basePath.'dir');

        $files = array(
            $basePath.'dir', $basePath.'file'
        );

        $this->filesystem->remove($files);

        $this->assertTrue(!is_dir($basePath.'dir'));
    }

    public function testRemoveCleansInvalidLinks()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $basePath = $this->workspace.DIRECTORY_SEPARATOR.'directory'.DIRECTORY_SEPARATOR;

        mkdir($basePath);
        mkdir($basePath.'dir');
        // create symlink to nonexistent file
        @symlink($basePath.'file', $basePath.'link');

        $this->filesystem->remove($basePath);

        $this->assertTrue(!is_dir($basePath));
    }

    public function testFilesExists()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR.'directory'.DIRECTORY_SEPARATOR;

        mkdir($basePath);
        touch($basePath.'file1');
        mkdir($basePath.'folder');

        $this->assertTrue($this->filesystem->exists($basePath.'file1'));
        $this->assertTrue($this->filesystem->exists($basePath.'folder'));
    }

    public function testFilesExistsTraversableObjectOfFilesAndDirectories()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;

        mkdir($basePath.'dir');
        touch($basePath.'file');

        $files = new \ArrayObject(array(
            $basePath.'dir', $basePath.'file'
        ));

        $this->assertTrue($this->filesystem->exists($files));
    }

    public function testFilesNotExistsTraversableObjectOfFilesAndDirectories()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR;

        mkdir($basePath.'dir');
        touch($basePath.'file');
        touch($basePath.'file2');

        $files = new \ArrayObject(array(
            $basePath.'dir', $basePath.'file', $basePath.'file2'
        ));

        unlink($basePath.'file');

        $this->assertFalse($this->filesystem->exists($files));
    }

    public function testInvalidFileNotExists()
    {
        $basePath = $this->workspace.DIRECTORY_SEPARATOR.'directory'.DIRECTORY_SEPARATOR;

        $this->assertFalse($this->filesystem->exists($basePath.time()));
    }

    public function testChmodChangesFileMode()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);
        $file = $dir.DIRECTORY_SEPARATOR.'file';
        touch($file);

        $this->filesystem->chmod($file, 0400);
        $this->filesystem->chmod($dir, 0753);

        $this->assertFilePermissions(753, $dir);
        $this->assertFilePermissions(400, $file);
    }

    public function testChmodWrongMod()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'file';
        touch($dir);

        $this->filesystem->chmod($dir, 'Wrongmode');
    }

    public function testChmodRecursive()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);
        $file = $dir.DIRECTORY_SEPARATOR.'file';
        touch($file);

        $this->filesystem->chmod($file, 0400, 0000, true);
        $this->filesystem->chmod($dir, 0753, 0000, true);

        $this->assertFilePermissions(753, $dir);
        $this->assertFilePermissions(753, $file);
    }

    public function testChmodAppliesUmask()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        touch($file);

        $this->filesystem->chmod($file, 0770, 0022);
        $this->assertFilePermissions(750, $file);
    }

    public function testChmodChangesModeOfArrayOfFiles()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $directory = $this->workspace.DIRECTORY_SEPARATOR.'directory';
        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $files = array($directory, $file);

        mkdir($directory);
        touch($file);

        $this->filesystem->chmod($files, 0753);

        $this->assertFilePermissions(753, $file);
        $this->assertFilePermissions(753, $directory);
    }

    public function testChmodChangesModeOfTraversableFileObject()
    {
        $this->markAsSkippedIfChmodIsMissing();

        $directory = $this->workspace.DIRECTORY_SEPARATOR.'directory';
        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $files = new \ArrayObject(array($directory, $file));

        mkdir($directory);
        touch($file);

        $this->filesystem->chmod($files, 0753);

        $this->assertFilePermissions(753, $file);
        $this->assertFilePermissions(753, $directory);
    }

    public function testChown()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);

        $this->filesystem->chown($dir, $this->getFileOwner($dir));
    }

    public function testChownRecursive()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);
        $file = $dir.DIRECTORY_SEPARATOR.'file';
        touch($file);

        $this->filesystem->chown($dir, $this->getFileOwner($dir), true);
    }

    public function testChownSymlink()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link);

        $this->filesystem->chown($link, $this->getFileOwner($link));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testChownSymlinkFails()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link);

        $this->filesystem->chown($link, 'user'.time().mt_rand(1000, 9999));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testChownFail()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);

        $this->filesystem->chown($dir, 'user'.time().mt_rand(1000, 9999));
    }

    public function testChgrp()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);

        $this->filesystem->chgrp($dir, $this->getFileGroup($dir));
    }

    public function testChgrpRecursive()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);
        $file = $dir.DIRECTORY_SEPARATOR.'file';
        touch($file);

        $this->filesystem->chgrp($dir, $this->getFileGroup($dir), true);
    }

    public function testChgrpSymlink()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link);

        $this->filesystem->chgrp($link, $this->getFileGroup($link));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testChgrpSymlinkFails()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link);

        $this->filesystem->chgrp($link, 'user'.time().mt_rand(1000, 9999));
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testChgrpFail()
    {
        $this->markAsSkippedIfPosixIsMissing();

        $dir = $this->workspace.DIRECTORY_SEPARATOR.'dir';
        mkdir($dir);

        $this->filesystem->chgrp($dir, 'user'.time().mt_rand(1000, 9999));
    }

    public function testRename()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';
        touch($file);

        $this->filesystem->rename($file, $newPath);

        $this->assertFileNotExists($file);
        $this->assertFileExists($newPath);
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testRenameThrowsExceptionIfTargetAlreadyExists()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';

        touch($file);
        touch($newPath);

        $this->filesystem->rename($file, $newPath);
    }

    public function testRenameOverwritesTheTargetIfItAlreadyExists()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';

        touch($file);
        touch($newPath);

        $this->filesystem->rename($file, $newPath, true);

        $this->assertFileNotExists($file);
        $this->assertFileExists($newPath);
    }

    /**
     * @expectedException \Symfony\Component\Filesystem\Exception\IOException
     */
    public function testRenameThrowsExceptionOnError()
    {
        $file = $this->workspace.DIRECTORY_SEPARATOR.uniqid();
        $newPath = $this->workspace.DIRECTORY_SEPARATOR.'new_file';

        $this->filesystem->rename($file, $newPath);
    }

    public function testSymlink()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link);

        $this->assertTrue(is_link($link));
        $this->assertEquals($file, readlink($link));
    }

    /**
     * @depends testSymlink
     */
    public function testRemoveSymlink()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        $this->filesystem->remove($link);

        $this->assertTrue(!is_link($link));
    }

    public function testSymlinkIsOverwrittenIfPointsToDifferentTarget()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);
        symlink($this->workspace, $link);

        $this->filesystem->symlink($file, $link);

        $this->assertTrue(is_link($link));
        $this->assertEquals($file, readlink($link));
    }

    public function testSymlinkIsNotOverwrittenIfAlreadyCreated()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link = $this->workspace.DIRECTORY_SEPARATOR.'link';

        touch($file);
        symlink($file, $link);

        $this->filesystem->symlink($file, $link);

        $this->assertTrue(is_link($link));
        $this->assertEquals($file, readlink($link));
    }

    public function testSymlinkCreatesTargetDirectoryIfItDoesNotExist()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $file = $this->workspace.DIRECTORY_SEPARATOR.'file';
        $link1 = $this->workspace.DIRECTORY_SEPARATOR.'dir'.DIRECTORY_SEPARATOR.'link';
        $link2 = $this->workspace.DIRECTORY_SEPARATOR.'dir'.DIRECTORY_SEPARATOR.'subdir'.DIRECTORY_SEPARATOR.'link';

        touch($file);

        $this->filesystem->symlink($file, $link1);
        $this->filesystem->symlink($file, $link2);

        $this->assertTrue(is_link($link1));
        $this->assertEquals($file, readlink($link1));
        $this->assertTrue(is_link($link2));
        $this->assertEquals($file, readlink($link2));
    }

    /**
     * @dataProvider providePathsForMakePathRelative
     */
    public function testMakePathRelative($endPath, $startPath, $expectedPath)
    {
        $path = $this->filesystem->makePathRelative($endPath, $startPath);

        $this->assertEquals($expectedPath, $path);
    }

    /**
     * @return array
     */
    public function providePathsForMakePathRelative()
    {
        $paths = array(
            array('/var/lib/symfony/src/Symfony/', '/var/lib/symfony/src/Symfony/Component', '../'),
            array('/var/lib/symfony/src/Symfony/', '/var/lib/symfony/src/Symfony/Component/', '../'),
            array('/var/lib/symfony/src/Symfony', '/var/lib/symfony/src/Symfony/Component', '../'),
            array('/var/lib/symfony/src/Symfony', '/var/lib/symfony/src/Symfony/Component/', '../'),
            array('var/lib/symfony/', 'var/lib/symfony/src/Symfony/Component', '../../../'),
            array('/usr/lib/symfony/', '/var/lib/symfony/src/Symfony/Component', '../../../../../../usr/lib/symfony/'),
            array('/var/lib/symfony/src/Symfony/', '/var/lib/symfony/', 'src/Symfony/'),
            array('/aa/bb', '/aa/bb', './'),
            array('/aa/bb', '/aa/bb/', './'),
            array('/aa/bb/', '/aa/bb', './'),
            array('/aa/bb/', '/aa/bb/', './'),
            array('/aa/bb/cc', '/aa/bb/cc/dd', '../'),
            array('/aa/bb/cc', '/aa/bb/cc/dd/', '../'),
            array('/aa/bb/cc/', '/aa/bb/cc/dd', '../'),
            array('/aa/bb/cc/', '/aa/bb/cc/dd/', '../'),
            array('/aa/bb/cc', '/aa', 'bb/cc/'),
            array('/aa/bb/cc', '/aa/', 'bb/cc/'),
            array('/aa/bb/cc/', '/aa', 'bb/cc/'),
            array('/aa/bb/cc/', '/aa/', 'bb/cc/'),
            array('/a/aab/bb', '/a/aa', '../aab/bb/'),
            array('/a/aab/bb', '/a/aa/', '../aab/bb/'),
            array('/a/aab/bb/', '/a/aa', '../aab/bb/'),
            array('/a/aab/bb/', '/a/aa/', '../aab/bb/'),
        );

        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $paths[] = array('c:\var\lib/symfony/src/Symfony/', 'c:/var/lib/symfony/', 'src/Symfony/');
        }

        return $paths;
    }

    public function testMirrorCopiesFilesAndDirectoriesRecursively()
    {
        $sourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR;
        $directory = $sourcePath.'directory'.DIRECTORY_SEPARATOR;
        $file1 = $directory.'file1';
        $file2 = $sourcePath.'file2';

        mkdir($sourcePath);
        mkdir($directory);
        file_put_contents($file1, 'FILE1');
        file_put_contents($file2, 'FILE2');

        $targetPath = $this->workspace.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR;

        $this->filesystem->mirror($sourcePath, $targetPath);

        $this->assertTrue(is_dir($targetPath));
        $this->assertTrue(is_dir($targetPath.'directory'));
        $this->assertFileEquals($file1, $targetPath.'directory'.DIRECTORY_SEPARATOR.'file1');
        $this->assertFileEquals($file2, $targetPath.'file2');

        $this->filesystem->remove($file1);

        $this->filesystem->mirror($sourcePath, $targetPath, null, array('delete' => false));
        $this->assertTrue($this->filesystem->exists($targetPath.'directory'.DIRECTORY_SEPARATOR.'file1'));

        $this->filesystem->mirror($sourcePath, $targetPath, null, array('delete' => true));
        $this->assertFalse($this->filesystem->exists($targetPath.'directory'.DIRECTORY_SEPARATOR.'file1'));

        file_put_contents($file1, 'FILE1');

        $this->filesystem->mirror($sourcePath, $targetPath, null, array('delete' => true));
        $this->assertTrue($this->filesystem->exists($targetPath.'directory'.DIRECTORY_SEPARATOR.'file1'));

        $this->filesystem->remove($directory);
        $this->filesystem->mirror($sourcePath, $targetPath, null, array('delete' => true));
        $this->assertFalse($this->filesystem->exists($targetPath.'directory'));
        $this->assertFalse($this->filesystem->exists($targetPath.'directory'.DIRECTORY_SEPARATOR.'file1'));
    }

    public function testMirrorCopiesLinks()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $sourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR;

        mkdir($sourcePath);
        file_put_contents($sourcePath.'file1', 'FILE1');
        symlink($sourcePath.'file1', $sourcePath.'link1');

        $targetPath = $this->workspace.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR;

        $this->filesystem->mirror($sourcePath, $targetPath);

        $this->assertTrue(is_dir($targetPath));
        $this->assertFileEquals($sourcePath.'file1', $targetPath.DIRECTORY_SEPARATOR.'link1');
        $this->assertTrue(is_link($targetPath.DIRECTORY_SEPARATOR.'link1'));
    }

    public function testMirrorCopiesLinkedDirectoryContents()
    {
        $this->markAsSkippedIfSymlinkIsMissing();

        $sourcePath = $this->workspace.DIRECTORY_SEPARATOR.'source'.DIRECTORY_SEPARATOR;

        mkdir($sourcePath.'nested/', 0777, true);
        file_put_contents($sourcePath.'/nested/file1.txt', 'FILE1');
        // Note: We symlink directory, not file
        symlink($sourcePath.'nested', $sourcePath.'link1');

        $targetPath = $this->workspace.DIRECTORY_SEPARATOR.'target'.DIRECTORY_SEPARATOR;

        $this->filesystem->mirror($sourcePath, $targetPath);

        $this->assertTrue(is_dir($targetPath));
        $this->assertFileEquals($sourcePath.'/nested/file1.txt', $targetPath.DIRECTORY_SEPARATOR.'link1/file1.txt');
        $this->assertTrue(is_link($targetPath.DIRECTORY_SEPARATOR.'link1'));
    }

    /**
     * @dataProvider providePathsForIsAbsolutePath
     */
    public function testIsAbsolutePath($path, $expectedResult)
    {
        $result = $this->filesystem->isAbsolutePath($path);

        $this->assertEquals($expectedResult, $result);
    }

    /**
     * @return array
     */
    public function providePathsForIsAbsolutePath()
    {
        return array(
            array('/var/lib', true),
            array('c:\\\\var\\lib', true),
            array('\\var\\lib', true),
            array('var/lib', false),
            array('../var/lib', false),
            array('', false),
            array(null, false)
        );
    }

    public function testDumpFile()
    {
        $filename = $this->workspace.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'baz.txt';

        $this->filesystem->dumpFile($filename, 'bar', 0753);

        $this->assertFileExists($filename);
        $this->assertSame('bar', file_get_contents($filename));

        // skip mode check on Windows
        if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $this->assertFilePermissions(753, $filename);
        }
    }

    public function testDumpFileWithNullMode()
    {
        $filename = $this->workspace.DIRECTORY_SEPARATOR.'foo'.DIRECTORY_SEPARATOR.'baz.txt';

        $this->filesystem->dumpFile($filename, 'bar', null);

        $this->assertFileExists($filename);
        $this->assertSame('bar', file_get_contents($filename));

        // skip mode check on Windows
        if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $this->assertFilePermissions(600, $filename);
        }
    }

    public function testDumpFileOverwritesAnExistingFile()
    {
        $filename = $this->workspace.DIRECTORY_SEPARATOR.'foo.txt';
        file_put_contents($filename, 'FOO BAR');

        $this->filesystem->dumpFile($filename, 'bar');

        $this->assertFileExists($filename);
        $this->assertSame('bar', file_get_contents($filename));
    }
}
PK+1[���Filesystem/Symfony/Component/Filesystem/Tests/ExceptionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Filesystem\Tests;

use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Exception\FileNotFoundException;

/**
 * Test class for Filesystem.
 */
class ExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testGetPath()
    {
        $e = new IOException('', 0, null, '/foo');
        $this->assertEquals('/foo', $e->getPath(), 'The pass should be returned.');
    }

    public function testGeneratedMessage()
    {
        $e = new FileNotFoundException(null, 0, null, '/foo');
        $this->assertEquals('/foo', $e->getPath());
        $this->assertEquals('File "/foo" could not be found.', $e->getMessage(), 'A message should be generated.');
    }

    public function testGeneratedMessageWithoutPath()
    {
        $e = new FileNotFoundException();
        $this->assertEquals('File could not be found.', $e->getMessage(), 'A message should be generated.');
    }

    public function testCustomMessage()
    {
        $e = new FileNotFoundException('bar', 0, null, '/foo');
        $this->assertEquals('bar', $e->getMessage(), 'A custom message should be possible still.');
    }
}
PK+1[�Ejc		8Filesystem/Symfony/Component/Filesystem/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Filesystem Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK+1[�ag�@<@<=Form/Symfony/Component/Form/Tests/AbstractTableLayoutTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormError;
use Symfony\Component\Security\Csrf\CsrfToken;

abstract class AbstractTableLayoutTest extends AbstractLayoutTest
{
    public function testRow()
    {
        $form = $this->factory->createNamed('name', 'text');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [./label[@for="name"]]
        /following-sibling::td
            [
                ./ul
                    [./li[.="[trans]Error![/trans]"]]
                    [count(./li)=1]
                /following-sibling::input[@id="name"]
            ]
    ]
'
        );
    }

    public function testLabelIsNotRenderedWhenSetToFalse()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'label' => false
        ));
        $html = $this->renderRow($form->createView());

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [count(//label)=0]
        /following-sibling::td
            [./input[@id="name"]]
    ]
'
        );
    }

    public function testRepeatedRow()
    {
        $form = $this->factory->createNamed('name', 'repeated');
        $html = $this->renderRow($form->createView());

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [./label[@for="name_first"]]
        /following-sibling::td
            [./input[@id="name_first"]]
    ]
/following-sibling::tr
    [
        ./td
            [./label[@for="name_second"]]
        /following-sibling::td
            [./input[@id="name_second"]]
    ]
/following-sibling::tr[@style="display: none"]
    [./td[@colspan="2"]/input
        [@type="hidden"]
        [@id="name__token"]
    ]
    [count(../tr)=3]
'
        );
    }

    public function testRepeatedRowWithErrors()
    {
        $form = $this->factory->createNamed('name', 'repeated');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        // The errors of the form are not rendered by intention!
        // In practice, repeated fields cannot have errors as all errors
        // on them are mapped to the first child.
        // (see RepeatedTypeValidatorExtension)

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [./label[@for="name_first"]]
        /following-sibling::td
            [./input[@id="name_first"]]
    ]
/following-sibling::tr
    [
        ./td
            [./label[@for="name_second"]]
        /following-sibling::td
            [./input[@id="name_second"]]
    ]
/following-sibling::tr[@style="display: none"]
    [./td[@colspan="2"]/input
        [@type="hidden"]
        [@id="name__token"]
    ]
    [count(../tr)=3]
'
        );
    }

    public function testButtonRow()
    {
        $form = $this->factory->createNamed('name', 'button');
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [.=""]
        /following-sibling::td
            [./button[@type="button"][@name="name"]]
    ]
    [count(//label)=0]
'
        );
    }

    public function testRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'repeated')
            ->add('field3', 'text')
            ->add('field4', 'text')
            ->getForm()
            ->createView();

        // Render field2 row -> does not implicitly call renderWidget because
        // it is a repeated field!
        $this->renderRow($view['field2']);

        // Render field3 widget
        $this->renderWidget($view['field3']);

        // Rest should only contain field1 and field4
        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/tr
    [
        ./td
            [./label[@for="name_field1"]]
        /following-sibling::td
            [./input[@id="name_field1"]]
    ]
/following-sibling::tr
    [
        ./td
            [./label[@for="name_field4"]]
        /following-sibling::td
            [./input[@id="name_field4"]]
    ]
    [count(../tr)=3]
    [count(..//label)=2]
    [count(..//input)=3]
/following-sibling::tr[@style="display: none"]
    [./td[@colspan="2"]/input
        [@type="hidden"]
        [@id="name__token"]
    ]
'
        );
    }

    public function testCollection()
    {
        $form = $this->factory->createNamed('name', 'collection', array('a', 'b'), array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr[./td/input[@type="text"][@value="a"]]
        /following-sibling::tr[./td/input[@type="text"][@value="b"]]
        /following-sibling::tr[@style="display: none"][./td[@colspan="2"]/input[@type="hidden"][@id="name__token"]]
    ]
    [count(./tr[./td/input])=3]
'
        );
    }

    public function testEmptyCollection()
    {
        $form = $this->factory->createNamed('name', 'collection', array(), array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [./tr[@style="display: none"][./td[@colspan="2"]/input[@type="hidden"][@id="name__token"]]]
    [count(./tr[./td/input])=1]
'
        );
    }

    public function testForm()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->setMethod('PUT')
            ->setAction('http://example.com')
            ->add('firstName', 'text')
            ->add('lastName', 'text')
            ->getForm()
            ->createView();

        $html = $this->renderForm($view, array(
            'id' => 'my&id',
            'attr' => array('class' => 'my&class'),
        ));

        $this->assertMatchesXpath($html,
'/form
    [
        ./input[@type="hidden"][@name="_method"][@value="PUT"]
        /following-sibling::table
            [
                ./tr
                    [
                        ./td
                            [./label[@for="name_firstName"]]
                        /following-sibling::td
                            [./input[@id="name_firstName"]]
                    ]
                /following-sibling::tr
                    [
                        ./td
                            [./label[@for="name_lastName"]]
                        /following-sibling::td
                            [./input[@id="name_lastName"]]
                    ]
                /following-sibling::tr[@style="display: none"]
                    [./td[@colspan="2"]/input
                        [@type="hidden"]
                        [@id="name__token"]
                    ]
            ]
            [count(.//input)=3]
            [@id="my&id"]
            [@class="my&class"]
    ]
    [@method="post"]
    [@action="http://example.com"]
    [@class="my&class"]
'
        );
    }

    public function testFormWidget()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('firstName', 'text')
            ->add('lastName', 'text')
            ->getForm()
            ->createView();

        $this->assertWidgetMatchesXpath($view, array(),
'/table
    [
        ./tr
            [
                ./td
                    [./label[@for="name_firstName"]]
                /following-sibling::td
                    [./input[@id="name_firstName"]]
            ]
        /following-sibling::tr
            [
                ./td
                    [./label[@for="name_lastName"]]
                /following-sibling::td
                    [./input[@id="name_lastName"]]
            ]
        /following-sibling::tr[@style="display: none"]
            [./td[@colspan="2"]/input
                [@type="hidden"]
                [@id="name__token"]
            ]
    ]
    [count(.//input)=3]
'
        );
    }

    // https://github.com/symfony/symfony/issues/2308
    public function testNestedFormError()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add($this->factory
                ->createNamedBuilder('child', 'form', null, array('error_bubbling' => false))
                ->add('grandChild', 'form')
            )
            ->getForm();

        $form->get('child')->addError(new FormError('[trans]Error![/trans]'));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr/td/ul[./li[.="[trans]Error![/trans]"]]
        /following-sibling::table[@id="name_child"]
    ]
    [count(.//li[.="[trans]Error![/trans]"])=1]
'
        );
    }

    public function testCsrf()
    {
        $this->csrfTokenManager->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(new CsrfToken('token_id', 'foo&bar')));

        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add($this->factory
                // No CSRF protection on nested forms
                ->createNamedBuilder('child', 'form')
                ->add($this->factory->createNamedBuilder('grandchild', 'text'))
            )
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr[@style="display: none"]
            [./td[@colspan="2"]/input
                [@type="hidden"]
                [@id="name__token"]
            ]
    ]
    [count(.//input[@type="hidden"])=1]
'
        );
    }

    public function testRepeated()
    {
        $form = $this->factory->createNamed('name', 'repeated', 'foobar', array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr
            [
                ./td
                    [./label[@for="name_first"]]
                /following-sibling::td
                    [./input[@type="text"][@id="name_first"]]
            ]
        /following-sibling::tr
            [
                ./td
                    [./label[@for="name_second"]]
                /following-sibling::td
                    [./input[@type="text"][@id="name_second"]]
            ]
        /following-sibling::tr[@style="display: none"]
            [./td[@colspan="2"]/input
                [@type="hidden"]
                [@id="name__token"]
            ]
    ]
    [count(.//input)=3]
'
        );
    }

    public function testRepeatedWithCustomOptions()
    {
        $form = $this->factory->createNamed('name', 'repeated', 'foobar', array(
            'type'           => 'password',
            'first_options'  => array('label' => 'Test', 'required' => false),
            'second_options' => array('label' => 'Test2')
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr
            [
                ./td
                    [./label[@for="name_first"][.="[trans]Test[/trans]"]]
                /following-sibling::td
                    [./input[@type="password"][@id="name_first"][@required="required"]]
            ]
        /following-sibling::tr
            [
                ./td
                    [./label[@for="name_second"][.="[trans]Test2[/trans]"]]
                /following-sibling::td
                    [./input[@type="password"][@id="name_second"][@required="required"]]
            ]
        /following-sibling::tr[@style="display: none"]
            [./td[@colspan="2"]/input
                [@type="hidden"]
                [@id="name__token"]
            ]
    ]
    [count(.//input)=3]
'
        );
    }

    /**
     * The block "_name_child_label" should be overridden in the theme of the
     * implemented driver.
     */
    public function testCollectionRowWithCustomBlock()
    {
        $collection = array('one', 'two', 'three');
        $form = $this->factory->createNamedBuilder('name', 'collection', $collection)
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/table
    [
        ./tr[./td/label[.="Custom label: [trans]0[/trans]"]]
        /following-sibling::tr[./td/label[.="Custom label: [trans]1[/trans]"]]
        /following-sibling::tr[./td/label[.="Custom label: [trans]2[/trans]"]]
    ]
'
        );
    }

    public function testFormEndWithRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text')
            ->getForm()
            ->createView();

        $this->renderWidget($view['field1']);

        // Rest should only contain field2
        $html = $this->renderEnd($view);

        // Insert the start tag, the end tag should be rendered by the helper
        // Unfortunately this is not valid HTML, because the surrounding table
        // tag is missing. If someone renders a form with table layout
        // manually, she should call form_rest() explicitly within the <table>
        // tag.
        $this->assertMatchesXpath('<form>' . $html,
'/form
    [
        ./tr
            [
                ./td
                    [./label[@for="name_field2"]]
                /following-sibling::td
                    [./input[@id="name_field2"]]
            ]
        /following-sibling::tr[@style="display: none"]
            [./td[@colspan="2"]/input
                [@type="hidden"]
                [@id="name__token"]
            ]
    ]
'
        );
    }

    public function testFormEndWithoutRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text')
            ->getForm()
            ->createView();

        $this->renderWidget($view['field1']);

        // Rest should only contain field2, but isn't rendered
        $html = $this->renderEnd($view, array('render_rest' => false));

        $this->assertEquals('</form>', $html);
    }

    public function testWidgetContainerAttributes()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('class' => 'foobar', 'data-foo' => 'bar'),
        ));

        $form->add('text', 'text');

        $html = $this->renderWidget($form->createView());

        // compare plain HTML to check the whitespace
        $this->assertContains('<table id="form" class="foobar" data-foo="bar">', $html);
    }

    public function testWidgetContainerAttributeNameRepeatedIfTrue()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('foo' => true),
        ));

        $html = $this->renderWidget($form->createView());

        // foo="foo"
        $this->assertContains('<table id="form" foo="foo">', $html);
    }

    public function testWidgetContainerAttributeHiddenIfFalse()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('foo' => false),
        ));

        $html = $this->renderWidget($form->createView());

        // no foo
        $this->assertContains('<table id="form">', $html);
    }
}
PK+1[���KK=Form/Symfony/Component/Form/Tests/FormPerformanceTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\Test\FormPerformanceTestCase as BaseFormPerformanceTestCase;

/**
 * @deprecated Deprecated since version 2.3, to be removed in 3.0. Use Symfony\Component\Form\Test\FormPerformanceTestCase instead.
 */
abstract class FormPerformanceTestCase extends BaseFormPerformanceTestCase
{
}
PK+1[@U���8Form/Symfony/Component/Form/Tests/AbstractLayoutTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;

abstract class AbstractLayoutTest extends \Symfony\Component\Form\Test\FormIntegrationTestCase
{
    protected $csrfTokenManager;

    protected function setUp()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('The "intl" extension is not available');
        }

        \Locale::setDefault('en');

        $this->csrfTokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');

        parent::setUp();
    }

    protected function getExtensions()
    {
        return array(
            new CsrfExtension($this->csrfTokenManager),
        );
    }

    protected function tearDown()
    {
        $this->csrfTokenManager = null;

        parent::tearDown();
    }

    protected function assertXpathNodeValue(\DomElement $element, $expression, $nodeValue)
    {
        $xpath = new \DOMXPath($element->ownerDocument);
        $nodeList = $xpath->evaluate($expression);
        $this->assertEquals(1, $nodeList->length);
        $this->assertEquals($nodeValue, $nodeList->item(0)->nodeValue);
    }

    protected function assertMatchesXpath($html, $expression, $count = 1)
    {
        $dom = new \DomDocument('UTF-8');
        try {
            // Wrap in <root> node so we can load HTML with multiple tags at
            // the top level
            $dom->loadXml('<root>'.$html.'</root>');
        } catch (\Exception $e) {
            $this->fail(sprintf(
                "Failed loading HTML:\n\n%s\n\nError: %s",
                $html,
                $e->getMessage()
            ));
        }
        $xpath = new \DOMXPath($dom);
        $nodeList = $xpath->evaluate('/root'.$expression);

        if ($nodeList->length != $count) {
            $dom->formatOutput = true;
            $this->fail(sprintf(
                "Failed asserting that \n\n%s\n\nmatches exactly %s. Matches %s in \n\n%s",
                $expression,
                $count == 1 ? 'once' : $count.' times',
                $nodeList->length == 1 ? 'once' : $nodeList->length.' times',
                // strip away <root> and </root>
                substr($dom->saveHTML(), 6, -8)
            ));
        }
    }

    protected function assertWidgetMatchesXpath(FormView $view, array $vars, $xpath)
    {
        // include ampersands everywhere to validate escaping
        $html = $this->renderWidget($view, array_merge(array(
            'id' => 'my&id',
            'attr' => array('class' => 'my&class'),
        ), $vars));

        $xpath = trim($xpath).'
    [@id="my&id"]
    [@class="my&class"]';

        $this->assertMatchesXpath($html, $xpath);
    }

    abstract protected function renderForm(FormView $view, array $vars = array());

    abstract protected function renderEnctype(FormView $view);

    abstract protected function renderLabel(FormView $view, $label = null, array $vars = array());

    abstract protected function renderErrors(FormView $view);

    abstract protected function renderWidget(FormView $view, array $vars = array());

    abstract protected function renderRow(FormView $view, array $vars = array());

    abstract protected function renderRest(FormView $view, array $vars = array());

    abstract protected function renderStart(FormView $view, array $vars = array());

    abstract protected function renderEnd(FormView $view, array $vars = array());

    abstract protected function setTheme(FormView $view, array $themes);

    public function testEnctype()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add('file', 'file')
            ->getForm();

        $this->assertEquals('enctype="multipart/form-data"', $this->renderEnctype($form->createView()));
    }

    public function testNoEnctype()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add('text', 'text')
            ->getForm();

        $this->assertEquals('', $this->renderEnctype($form->createView()));
    }

    public function testLabel()
    {
        $form = $this->factory->createNamed('name', 'text');
        $view = $form->createView();
        $this->renderWidget($view, array('label' => 'foo'));
        $html = $this->renderLabel($view);

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [.="[trans]Name[/trans]"]
'
        );
    }

    public function testLabelOnForm()
    {
        $form = $this->factory->createNamed('name', 'date');
        $view = $form->createView();
        $this->renderWidget($view, array('label' => 'foo'));
        $html = $this->renderLabel($view);

        $this->assertMatchesXpath($html,
'/label
    [@class="required"]
    [.="[trans]Name[/trans]"]
'
        );
    }

    public function testLabelWithCustomTextPassedAsOption()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'label' => 'Custom label',
        ));
        $html = $this->renderLabel($form->createView());

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [.="[trans]Custom label[/trans]"]
'
        );
    }

    public function testLabelWithCustomTextPassedDirectly()
    {
        $form = $this->factory->createNamed('name', 'text');
        $html = $this->renderLabel($form->createView(), 'Custom label');

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [.="[trans]Custom label[/trans]"]
'
        );
    }

    public function testLabelWithCustomTextPassedAsOptionAndDirectly()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'label' => 'Custom label',
        ));
        $html = $this->renderLabel($form->createView(), 'Overridden label');

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [.="[trans]Overridden label[/trans]"]
'
        );
    }

    public function testLabelDoesNotRenderFieldAttributes()
    {
        $form = $this->factory->createNamed('name', 'text');
        $html = $this->renderLabel($form->createView(), null, array(
            'attr' => array(
                'class' => 'my&class'
            ),
        ));

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [@class="required"]
'
        );
    }

    public function testLabelWithCustomAttributesPassedDirectly()
    {
        $form = $this->factory->createNamed('name', 'text');
        $html = $this->renderLabel($form->createView(), null, array(
            'label_attr' => array(
                'class' => 'my&class'
            ),
        ));

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [@class="my&class required"]
'
        );
    }

    public function testLabelWithCustomTextAndCustomAttributesPassedDirectly()
    {
        $form = $this->factory->createNamed('name', 'text');
        $html = $this->renderLabel($form->createView(), 'Custom label', array(
            'label_attr' => array(
                'class' => 'my&class'
            ),
        ));

        $this->assertMatchesXpath($html,
'/label
    [@for="name"]
    [@class="my&class required"]
    [.="[trans]Custom label[/trans]"]
'
        );
    }

    // https://github.com/symfony/symfony/issues/5029
    public function testLabelWithCustomTextAsOptionAndCustomAttributesPassedDirectly()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'label' => 'Custom label',
        ));
        $html = $this->renderLabel($form->createView(), null, array(
            'label_attr' => array(
                'class' => 'my&class'
            ),
        ));

        $this->assertMatchesXpath($html,
            '/label
    [@for="name"]
    [@class="my&class required"]
    [.="[trans]Custom label[/trans]"]
'
        );
    }

    public function testErrors()
    {
        $form = $this->factory->createNamed('name', 'text');
        $form->addError(new FormError('[trans]Error 1[/trans]'));
        $form->addError(new FormError('[trans]Error 2[/trans]'));
        $view = $form->createView();
        $html = $this->renderErrors($view);

        $this->assertMatchesXpath($html,
'/ul
    [
        ./li[.="[trans]Error 1[/trans]"]
        /following-sibling::li[.="[trans]Error 2[/trans]"]
    ]
    [count(./li)=2]
'
        );
    }

    public function testOverrideWidgetBlock()
    {
        // see custom_widgets.html.twig
        $form = $this->factory->createNamed('text_id', 'text');
        $html = $this->renderWidget($form->createView());

        $this->assertMatchesXpath($html,
'/div
    [
        ./input
        [@type="text"]
        [@id="text_id"]
    ]
    [@id="container"]
'
        );
    }

    public function testCheckedCheckbox()
    {
        $form = $this->factory->createNamed('name', 'checkbox', true);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="checkbox"]
    [@name="name"]
    [@checked="checked"]
    [@value="1"]
'
        );
    }

    public function testUncheckedCheckbox()
    {
        $form = $this->factory->createNamed('name', 'checkbox', false);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="checkbox"]
    [@name="name"]
    [not(@checked)]
'
        );
    }

    public function testCheckboxWithValue()
    {
        $form = $this->factory->createNamed('name', 'checkbox', false, array(
            'value' => 'foo&bar',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="checkbox"]
    [@name="name"]
    [@value="foo&bar"]
'
        );
    }

    public function testSingleChoice()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'multiple' => false,
            'expanded' => false,
        ));

        // If the field is collapsed, has no "multiple" attribute, is required but
        // has *no* empty value, the "required" must not be added, otherwise
        // the resulting HTML is invalid.
        // https://github.com/symfony/symfony/issues/8942

        // HTML 5 spec
        // http://www.w3.org/html/wg/drafts/html/master/forms.html#placeholder-label-option

        // "If a select element has a required attribute specified, does not
        //  have a multiple attribute specified, and has a display size of 1,
        //  then the select element must have a placeholder label option."

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=2]
'
        );
    }

    public function testSingleChoiceWithPreferred()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'preferred_choices' => array('&b'),
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array('separator' => '-- sep --'),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
        /following-sibling::option[@disabled="disabled"][not(@selected)][.="-- sep --"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceWithPreferredAndNoSeparator()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'preferred_choices' => array('&b'),
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array('separator' => null),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
    ]
    [count(./option)=2]
'
        );
    }

    public function testSingleChoiceWithPreferredAndBlankSeparator()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'preferred_choices' => array('&b'),
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array('separator' => ''),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
        /following-sibling::option[@disabled="disabled"][not(@selected)][.=""]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testChoiceWithOnlyPreferred()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'preferred_choices' => array('&a', '&b'),
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [count(./option)=2]
'
        );
    }

    public function testSingleChoiceNonRequired()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => false,
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value=""][.="[trans][/trans]"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceNonRequiredNoneSelected()
    {
        $form = $this->factory->createNamed('name', 'choice', null, array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => false,
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value=""][.="[trans][/trans]"]
        /following-sibling::option[@value="&a"][not(@selected)][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceWithNonRequiredEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'multiple' => false,
            'expanded' => false,
            'required' => false,
            'empty_value' => 'Select&Anything&Not&Me',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [not(@required)]
    [
        ./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Anything&Not&Me[/trans]"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceRequiredWithEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => true,
            'multiple' => false,
            'expanded' => false,
            'empty_value' => 'Test&Me'
        ));

        // The "disabled" attribute was removed again due to a bug in the
        // BlackBerry 10 browser.
        // See https://github.com/symfony/symfony/pull/7678
        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [@required="required"]
    [
        ./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Test&Me[/trans]"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceRequiredWithEmptyValueViaView()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => true,
            'multiple' => false,
            'expanded' => false,
        ));

        // The "disabled" attribute was removed again due to a bug in the
        // BlackBerry 10 browser.
        // See https://github.com/symfony/symfony/pull/7678
        $this->assertWidgetMatchesXpath($form->createView(), array('empty_value' => ''),
'/select
    [@name="name"]
    [@required="required"]
    [
        ./option[@value=""][not(@selected)][not(@disabled)][.="[trans][/trans]"]
        /following-sibling::option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=3]
'
        );
    }

    public function testSingleChoiceGrouped()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array(
                'Group&1' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
                'Group&2' => array('&c' => 'Choice&C'),
            ),
            'multiple' => false,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [./optgroup[@label="[trans]Group&1[/trans]"]
        [
            ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
            /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
        ]
        [count(./option)=2]
    ]
    [./optgroup[@label="[trans]Group&2[/trans]"]
        [./option[@value="&c"][not(@selected)][.="[trans]Choice&C[/trans]"]]
        [count(./option)=1]
    ]
    [count(./optgroup)=2]
'
        );
    }

    public function testMultipleChoice()
    {
        $form = $this->factory->createNamed('name', 'choice', array('&a'), array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => true,
            'multiple' => true,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name[]"]
    [@required="required"]
    [@multiple="multiple"]
    [
        ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=2]
'
        );
    }

    public function testMultipleChoiceSkipsEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'choice', array('&a'), array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'multiple' => true,
            'expanded' => false,
            'empty_value' => 'Test&Me'
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name[]"]
    [@multiple="multiple"]
    [
        ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=2]
'
        );
    }

    public function testMultipleChoiceNonRequired()
    {
        $form = $this->factory->createNamed('name', 'choice', array('&a'), array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'required' => false,
            'multiple' => true,
            'expanded' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name[]"]
    [@multiple="multiple"]
    [
        ./option[@value="&a"][@selected="selected"][.="[trans]Choice&A[/trans]"]
        /following-sibling::option[@value="&b"][not(@selected)][.="[trans]Choice&B[/trans]"]
    ]
    [count(./option)=2]
'
        );
    }

    public function testSingleChoiceExpanded()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input[@type="radio"][@name="name"][@id="name_0"][@value="&a"][@checked]
        /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"]
        /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][@value="&b"][not(@checked)]
        /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(./input)=3]
'
        );
    }

    public function testSingleChoiceExpandedWithEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'choice', '&a', array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B'),
            'multiple' => false,
            'expanded' => true,
            'empty_value' => 'Test&Me'
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input[@type="radio"][@name="name"][@id="name_placeholder"][not(@checked)]
        /following-sibling::label[@for="name_placeholder"][.="[trans]Test&Me[/trans]"]
        /following-sibling::input[@type="radio"][@name="name"][@id="name_0"][@checked]
        /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"]
        /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][not(@checked)]
        /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(./input)=4]
'
        );
    }

    public function testSingleChoiceExpandedWithBooleanValue()
    {
        $form = $this->factory->createNamed('name', 'choice', true, array(
            'choices' => array('1' => 'Choice&A', '0' => 'Choice&B'),
            'multiple' => false,
            'expanded' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input[@type="radio"][@name="name"][@id="name_0"][@checked]
        /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"]
        /following-sibling::input[@type="radio"][@name="name"][@id="name_1"][not(@checked)]
        /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(./input)=3]
'
        );
    }

    public function testMultipleChoiceExpanded()
    {
        $form = $this->factory->createNamed('name', 'choice', array('&a', '&c'), array(
            'choices' => array('&a' => 'Choice&A', '&b' => 'Choice&B', '&c' => 'Choice&C'),
            'multiple' => true,
            'expanded' => true,
            'required' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input[@type="checkbox"][@name="name[]"][@id="name_0"][@checked][not(@required)]
        /following-sibling::label[@for="name_0"][.="[trans]Choice&A[/trans]"]
        /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_1"][not(@checked)][not(@required)]
        /following-sibling::label[@for="name_1"][.="[trans]Choice&B[/trans]"]
        /following-sibling::input[@type="checkbox"][@name="name[]"][@id="name_2"][@checked][not(@required)]
        /following-sibling::label[@for="name_2"][.="[trans]Choice&C[/trans]"]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(./input)=4]
'
        );
    }

    public function testCountry()
    {
        $form = $this->factory->createNamed('name', 'country', 'AT');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [./option[@value="AT"][@selected="selected"][.="[trans]Austria[/trans]"]]
    [count(./option)>200]
'
        );
    }

    public function testCountryWithEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'country', 'AT', array(
            'empty_value' => 'Select&Country',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Country[/trans]"]]
    [./option[@value="AT"][@selected="selected"][.="[trans]Austria[/trans]"]]
    [count(./option)>201]
'
        );
    }

    public function testDateTime()
    {
        $form = $this->factory->createNamed('name', 'datetime', '2011-02-03 04:05:06', array(
            'input' => 'string',
            'with_seconds' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [@id="name_date"]
            [
                ./select
                    [@id="name_date_month"]
                    [./option[@value="2"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_day"]
                    [./option[@value="3"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_year"]
                    [./option[@value="2011"][@selected="selected"]]
            ]
        /following-sibling::div
            [@id="name_time"]
            [
                ./select
                    [@id="name_time_hour"]
                    [./option[@value="4"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_time_minute"]
                    [./option[@value="5"][@selected="selected"]]
            ]
    ]
    [count(.//select)=5]
'
        );
    }

    public function testDateTimeWithEmptyValueGlobal()
    {
        $form = $this->factory->createNamed('name', 'datetime', null, array(
            'input' => 'string',
            'empty_value' => 'Change&Me',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [@id="name_date"]
            [
                ./select
                    [@id="name_date_month"]
                    [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
                /following-sibling::select
                    [@id="name_date_day"]
                    [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
                /following-sibling::select
                    [@id="name_date_year"]
                    [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
            ]
        /following-sibling::div
            [@id="name_time"]
            [
                ./select
                    [@id="name_time_hour"]
                    [./option[@value=""][.="[trans]Change&Me[/trans]"]]
                /following-sibling::select
                    [@id="name_time_minute"]
                    [./option[@value=""][.="[trans]Change&Me[/trans]"]]
            ]
    ]
    [count(.//select)=5]
'
        );
    }

    public function testDateTimeWithHourAndMinute()
    {
        $data = array('year' => '2011', 'month' => '2', 'day' => '3', 'hour' => '4', 'minute' => '5');

        $form = $this->factory->createNamed('name', 'datetime', $data, array(
            'input' => 'array',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [@id="name_date"]
            [
                ./select
                    [@id="name_date_month"]
                    [./option[@value="2"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_day"]
                    [./option[@value="3"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_year"]
                    [./option[@value="2011"][@selected="selected"]]
            ]
        /following-sibling::div
            [@id="name_time"]
            [
                ./select
                    [@id="name_time_hour"]
                    [./option[@value="4"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_time_minute"]
                    [./option[@value="5"][@selected="selected"]]
            ]
    ]
    [count(.//select)=5]
'
        );
    }

    public function testDateTimeWithSeconds()
    {
        $form = $this->factory->createNamed('name', 'datetime', '2011-02-03 04:05:06', array(
            'input' => 'string',
            'with_seconds' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [@id="name_date"]
            [
                ./select
                    [@id="name_date_month"]
                    [./option[@value="2"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_day"]
                    [./option[@value="3"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_date_year"]
                    [./option[@value="2011"][@selected="selected"]]
            ]
        /following-sibling::div
            [@id="name_time"]
            [
                ./select
                    [@id="name_time_hour"]
                    [./option[@value="4"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_time_minute"]
                    [./option[@value="5"][@selected="selected"]]
                /following-sibling::select
                    [@id="name_time_second"]
                    [./option[@value="6"][@selected="selected"]]
            ]
    ]
    [count(.//select)=6]
'
        );
    }

    public function testDateTimeSingleText()
    {
        $form = $this->factory->createNamed('name', 'datetime', '2011-02-03 04:05:06', array(
            'input' => 'string',
            'date_widget' => 'single_text',
            'time_widget' => 'single_text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input
            [@type="date"]
            [@id="name_date"]
            [@name="name[date]"]
            [@value="2011-02-03"]
        /following-sibling::input
            [@type="time"]
            [@id="name_time"]
            [@name="name[time]"]
            [@value="04:05"]
    ]
'
        );
    }

    public function testDateTimeWithWidgetSingleText()
    {
        $form = $this->factory->createNamed('name', 'datetime', '2011-02-03 04:05:06', array(
            'input' => 'string',
            'widget' => 'single_text',
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="datetime"]
    [@name="name"]
    [@value="2011-02-03T04:05:06Z"]
'
        );
    }

    public function testDateTimeWithWidgetSingleTextIgnoreDateAndTimeWidgets()
    {
        $form = $this->factory->createNamed('name', 'datetime', '2011-02-03 04:05:06', array(
            'input' => 'string',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
            'widget' => 'single_text',
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="datetime"]
    [@name="name"]
    [@value="2011-02-03T04:05:06Z"]
'
        );
    }

    public function testDateChoice()
    {
        $form = $this->factory->createNamed('name', 'date', '2011-02-03', array(
            'input' => 'string',
            'widget' => 'choice',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_month"]
            [./option[@value="2"][@selected="selected"]]
        /following-sibling::select
            [@id="name_day"]
            [./option[@value="3"][@selected="selected"]]
        /following-sibling::select
            [@id="name_year"]
            [./option[@value="2011"][@selected="selected"]]
    ]
    [count(./select)=3]
'
        );
    }

    public function testDateChoiceWithEmptyValueGlobal()
    {
        $form = $this->factory->createNamed('name', 'date', null, array(
            'input' => 'string',
            'widget' => 'choice',
            'empty_value' => 'Change&Me',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_month"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
        /following-sibling::select
            [@id="name_day"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
        /following-sibling::select
            [@id="name_year"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
    ]
    [count(./select)=3]
'
        );
    }

    public function testDateChoiceWithEmptyValueOnYear()
    {
        $form = $this->factory->createNamed('name', 'date', null, array(
            'input' => 'string',
            'widget' => 'choice',
            'required' => false,
            'empty_value' => array('year' => 'Change&Me'),
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_month"]
            [./option[@value="1"]]
        /following-sibling::select
            [@id="name_day"]
            [./option[@value="1"]]
        /following-sibling::select
            [@id="name_year"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
    ]
    [count(./select)=3]
'
        );
    }

    public function testDateText()
    {
        $form = $this->factory->createNamed('name', 'date', '2011-02-03', array(
            'input' => 'string',
            'widget' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input
            [@id="name_month"]
            [@type="text"]
            [@value="2"]
        /following-sibling::input
            [@id="name_day"]
            [@type="text"]
            [@value="3"]
        /following-sibling::input
            [@id="name_year"]
            [@type="text"]
            [@value="2011"]
    ]
    [count(./input)=3]
'
        );
    }

    public function testDateSingleText()
    {
        $form = $this->factory->createNamed('name', 'date', '2011-02-03', array(
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="date"]
    [@name="name"]
    [@value="2011-02-03"]
'
        );
    }

    public function testDateErrorBubbling()
    {
        $form = $this->factory->createNamedBuilder('form', 'form')
            ->add('date', 'date')
            ->getForm();
        $form->get('date')->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();

        $this->assertEmpty($this->renderErrors($view));
        $this->assertNotEmpty($this->renderErrors($view['date']));
    }

    public function testBirthDay()
    {
        $form = $this->factory->createNamed('name', 'birthday', '2000-02-03', array(
            'input' => 'string',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_month"]
            [./option[@value="2"][@selected="selected"]]
        /following-sibling::select
            [@id="name_day"]
            [./option[@value="3"][@selected="selected"]]
        /following-sibling::select
            [@id="name_year"]
            [./option[@value="2000"][@selected="selected"]]
    ]
    [count(./select)=3]
'
        );
    }

    public function testBirthDayWithEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'birthday', '1950-01-01', array(
            'input' => 'string',
            'empty_value' => '',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_month"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans][/trans]"]]
            [./option[@value="1"][@selected="selected"]]
        /following-sibling::select
            [@id="name_day"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans][/trans]"]]
            [./option[@value="1"][@selected="selected"]]
        /following-sibling::select
            [@id="name_year"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans][/trans]"]]
            [./option[@value="1950"][@selected="selected"]]
    ]
    [count(./select)=3]
'
        );
    }

    public function testEmail()
    {
        $form = $this->factory->createNamed('name', 'email', 'foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="email"]
    [@name="name"]
    [@value="foo&bar"]
    [not(@maxlength)]
'
        );
    }

    public function testEmailWithMaxLength()
    {
        $form = $this->factory->createNamed('name', 'email', 'foo&bar', array(
            'max_length' => 123,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="email"]
    [@name="name"]
    [@value="foo&bar"]
    [@maxlength="123"]
'
        );
    }

    public function testFile()
    {
        $form = $this->factory->createNamed('name', 'file');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="file"]
'
        );
    }

    public function testHidden()
    {
        $form = $this->factory->createNamed('name', 'hidden', 'foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="hidden"]
    [@name="name"]
    [@value="foo&bar"]
'
        );
    }

    public function testReadOnly()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'read_only' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@readonly="readonly"]
'
        );
    }

    public function testDisabled()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'disabled' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@disabled="disabled"]
'
        );
    }

    public function testInteger()
    {
        $form = $this->factory->createNamed('name', 'integer', 123);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="number"]
    [@name="name"]
    [@value="123"]
'
        );
    }

    public function testLanguage()
    {
        $form = $this->factory->createNamed('name', 'language', 'de');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [./option[@value="de"][@selected="selected"][.="[trans]German[/trans]"]]
    [count(./option)>200]
'
        );
    }

    public function testLocale()
    {
        $form = $this->factory->createNamed('name', 'locale', 'de_AT');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [./option[@value="de_AT"][@selected="selected"][.="[trans]German (Austria)[/trans]"]]
    [count(./option)>200]
'
        );
    }

    public function testMoney()
    {
        $form = $this->factory->createNamed('name', 'money', 1234.56, array(
            'currency' => 'EUR',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@value="1234.56"]
    [contains(.., "€")]
'
        );
    }

    public function testNumber()
    {
        $form = $this->factory->createNamed('name', 'number', 1234.56);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@value="1234.56"]
'
        );
    }

    public function testPassword()
    {
        $form = $this->factory->createNamed('name', 'password', 'foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="password"]
    [@name="name"]
'
        );
    }

    public function testPasswordSubmittedWithNotAlwaysEmpty()
    {
        $form = $this->factory->createNamed('name', 'password', null, array(
            'always_empty' => false,
        ));
        $form->submit('foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="password"]
    [@name="name"]
    [@value="foo&bar"]
'
        );
    }

    public function testPasswordWithMaxLength()
    {
        $form = $this->factory->createNamed('name', 'password', 'foo&bar', array(
            'max_length' => 123,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="password"]
    [@name="name"]
    [@maxlength="123"]
'
        );
    }

    public function testPercent()
    {
        $form = $this->factory->createNamed('name', 'percent', 0.1);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@value="10"]
    [contains(.., "%")]
'
        );
    }

    public function testCheckedRadio()
    {
        $form = $this->factory->createNamed('name', 'radio', true);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="radio"]
    [@name="name"]
    [@checked="checked"]
    [@value="1"]
'
        );
    }

    public function testUncheckedRadio()
    {
        $form = $this->factory->createNamed('name', 'radio', false);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="radio"]
    [@name="name"]
    [not(@checked)]
'
        );
    }

    public function testRadioWithValue()
    {
        $form = $this->factory->createNamed('name', 'radio', false, array(
            'value' => 'foo&bar',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="radio"]
    [@name="name"]
    [@value="foo&bar"]
'
        );
    }

    public function testTextarea()
    {
        $form = $this->factory->createNamed('name', 'textarea', 'foo&bar', array(
            'pattern' => 'foo',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/textarea
    [@name="name"]
    [not(@pattern)]
    [.="foo&bar"]
'
        );
    }

    public function testText()
    {
        $form = $this->factory->createNamed('name', 'text', 'foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@value="foo&bar"]
    [not(@maxlength)]
'
        );
    }

    public function testTextWithMaxLength()
    {
        $form = $this->factory->createNamed('name', 'text', 'foo&bar', array(
            'max_length' => 123,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="text"]
    [@name="name"]
    [@value="foo&bar"]
    [@maxlength="123"]
'
        );
    }

    public function testSearch()
    {
        $form = $this->factory->createNamed('name', 'search', 'foo&bar');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="search"]
    [@name="name"]
    [@value="foo&bar"]
    [not(@maxlength)]
'
        );
    }

    public function testTime()
    {
        $form = $this->factory->createNamed('name', 'time', '04:05:06', array(
            'input' => 'string',
            'with_seconds' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_hour"]
            [not(@size)]
            [./option[@value="4"][@selected="selected"]]
        /following-sibling::select
            [@id="name_minute"]
            [not(@size)]
            [./option[@value="5"][@selected="selected"]]
    ]
    [count(./select)=2]
'
        );
    }

    public function testTimeWithSeconds()
    {
        $form = $this->factory->createNamed('name', 'time', '04:05:06', array(
            'input' => 'string',
            'with_seconds' => true,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_hour"]
            [not(@size)]
            [./option[@value="4"][@selected="selected"]]
            [count(./option)>23]
        /following-sibling::select
            [@id="name_minute"]
            [not(@size)]
            [./option[@value="5"][@selected="selected"]]
            [count(./option)>59]
        /following-sibling::select
            [@id="name_second"]
            [not(@size)]
            [./option[@value="6"][@selected="selected"]]
            [count(./option)>59]
    ]
    [count(./select)=3]
'
        );
    }

    public function testTimeText()
    {
        $form = $this->factory->createNamed('name', 'time', '04:05:06', array(
            'input' => 'string',
            'widget' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./input
            [@type="text"]
            [@id="name_hour"]
            [@name="name[hour]"]
            [@value="04"]
            [@size="1"]
            [@required="required"]
        /following-sibling::input
            [@type="text"]
            [@id="name_minute"]
            [@name="name[minute]"]
            [@value="05"]
            [@size="1"]
            [@required="required"]
    ]
    [count(./input)=2]
'
        );
    }

    public function testTimeSingleText()
    {
        $form = $this->factory->createNamed('name', 'time', '04:05:06', array(
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="time"]
    [@name="name"]
    [@value="04:05"]
    [not(@size)]
'
        );
    }

    public function testTimeWithEmptyValueGlobal()
    {
        $form = $this->factory->createNamed('name', 'time', null, array(
            'input' => 'string',
            'empty_value' => 'Change&Me',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_hour"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
            [count(./option)>24]
        /following-sibling::select
            [@id="name_minute"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
            [count(./option)>60]
    ]
    [count(./select)=2]
'
        );
    }

    public function testTimeWithEmptyValueOnYear()
    {
        $form = $this->factory->createNamed('name', 'time', null, array(
            'input' => 'string',
            'required' => false,
            'empty_value' => array('hour' => 'Change&Me'),
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./select
            [@id="name_hour"]
            [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Change&Me[/trans]"]]
            [count(./option)>24]
        /following-sibling::select
            [@id="name_minute"]
            [./option[@value="1"]]
            [count(./option)>59]
    ]
    [count(./select)=2]
'
        );
    }

    public function testTimeErrorBubbling()
    {
        $form = $this->factory->createNamedBuilder('form', 'form')
            ->add('time', 'time')
            ->getForm();
        $form->get('time')->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();

        $this->assertEmpty($this->renderErrors($view));
        $this->assertNotEmpty($this->renderErrors($view['time']));
    }

    public function testTimezone()
    {
        $form = $this->factory->createNamed('name', 'timezone', 'Europe/Vienna');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [@name="name"]
    [not(@required)]
    [./optgroup
        [@label="[trans]Europe[/trans]"]
        [./option[@value="Europe/Vienna"][@selected="selected"][.="[trans]Vienna[/trans]"]]
    ]
    [count(./optgroup)>10]
    [count(.//option)>200]
'
        );
    }

    public function testTimezoneWithEmptyValue()
    {
        $form = $this->factory->createNamed('name', 'timezone', null, array(
            'empty_value' => 'Select&Timezone',
            'required' => false,
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/select
    [./option[@value=""][not(@selected)][not(@disabled)][.="[trans]Select&Timezone[/trans]"]]
    [count(./optgroup)>10]
    [count(.//option)>201]
'
        );
    }

    public function testUrl()
    {
        $url = 'http://www.google.com?foo1=bar1&foo2=bar2';
        $form = $this->factory->createNamed('name', 'url', $url);

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/input
    [@type="url"]
    [@name="name"]
    [@value="http://www.google.com?foo1=bar1&foo2=bar2"]
'
        );
    }

    public function testCollectionPrototype()
    {
        $form = $this->factory->createNamedBuilder('name', 'form', array('items' => array('one', 'two', 'three')))
            ->add('items', 'collection', array('allow_add' => true))
            ->getForm()
            ->createView();

        $html = $this->renderWidget($form);

        $this->assertMatchesXpath($html,
            '//div[@id="name_items"][@data-prototype]
            |
            //table[@id="name_items"][@data-prototype]'
        );
    }

    public function testEmptyRootFormName()
    {
        $form = $this->factory->createNamedBuilder('', 'form')
            ->add('child', 'text')
            ->getForm();

        $this->assertMatchesXpath($this->renderWidget($form->createView()),
            '//input[@type="hidden"][@id="_token"][@name="_token"]
            |
             //input[@type="text"][@id="child"][@name="child"]'
        , 2);
    }

    public function testButton()
    {
        $form = $this->factory->createNamed('name', 'button');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
            '/button[@type="button"][@name="name"][.="[trans]Name[/trans]"]'
        );
    }

    public function testButtonLabelIsEmpty()
    {
        $form = $this->factory->createNamed('name', 'button');

        $this->assertSame('', $this->renderLabel($form->createView()));
    }

    public function testSubmit()
    {
        $form = $this->factory->createNamed('name', 'submit');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
            '/button[@type="submit"][@name="name"]'
        );
    }

    public function testReset()
    {
        $form = $this->factory->createNamed('name', 'reset');

        $this->assertWidgetMatchesXpath($form->createView(), array(),
            '/button[@type="reset"][@name="name"]'
        );
    }

    public function testStartTag()
    {
        $form = $this->factory->create('form', null, array(
            'method' => 'get',
            'action' => 'http://example.com/directory'
        ));

        $html = $this->renderStart($form->createView());

        $this->assertSame('<form name="form" method="get" action="http://example.com/directory">', $html);
    }

    public function testStartTagForPutRequest()
    {
        $form = $this->factory->create('form', null, array(
            'method' => 'put',
            'action' => 'http://example.com/directory'
        ));

        $html = $this->renderStart($form->createView());

        $this->assertMatchesXpath($html . '</form>',
'/form
    [./input[@type="hidden"][@name="_method"][@value="PUT"]]
    [@method="post"]
    [@action="http://example.com/directory"]'
        );
    }

    public function testStartTagWithOverriddenVars()
    {
        $form = $this->factory->create('form', null, array(
            'method' => 'put',
            'action' => 'http://example.com/directory',
        ));

        $html = $this->renderStart($form->createView(), array(
            'method' => 'post',
            'action' => 'http://foo.com/directory'
        ));

        $this->assertSame('<form name="form" method="post" action="http://foo.com/directory">', $html);
    }

    public function testStartTagForMultipartForm()
    {
        $form = $this->factory->createBuilder('form', null, array(
                'method' => 'get',
                'action' => 'http://example.com/directory'
            ))
            ->add('file', 'file')
            ->getForm();

        $html = $this->renderStart($form->createView());

        $this->assertSame('<form name="form" method="get" action="http://example.com/directory" enctype="multipart/form-data">', $html);
    }

    public function testStartTagWithExtraAttributes()
    {
        $form = $this->factory->create('form', null, array(
            'method' => 'get',
            'action' => 'http://example.com/directory'
        ));

        $html = $this->renderStart($form->createView(), array(
            'attr' => array('class' => 'foobar'),
        ));

        $this->assertSame('<form name="form" method="get" action="http://example.com/directory" class="foobar">', $html);
    }

    public function testWidgetAttributes()
    {
        $form = $this->factory->createNamed('text', 'text', 'value', array(
            'required' => true,
            'disabled' => true,
            'read_only' => true,
            'max_length' => 10,
            'pattern' => '\d+',
            'attr' => array('class' => 'foobar', 'data-foo' => 'bar'),
        ));

        $html = $this->renderWidget($form->createView());

        // compare plain HTML to check the whitespace
        $this->assertSame('<input type="text" id="text" name="text" readonly="readonly" disabled="disabled" required="required" maxlength="10" pattern="\d+" class="foobar" data-foo="bar" value="value" />', $html);
    }

    public function testWidgetAttributeNameRepeatedIfTrue()
    {
        $form = $this->factory->createNamed('text', 'text', 'value', array(
            'attr' => array('foo' => true),
        ));

        $html = $this->renderWidget($form->createView());

        // foo="foo"
        $this->assertSame('<input type="text" id="text" name="text" required="required" foo="foo" value="value" />', $html);
    }

    public function testWidgetAttributeHiddenIfFalse()
    {
        $form = $this->factory->createNamed('text', 'text', 'value', array(
            'attr' => array('foo' => false),
        ));

        $html = $this->renderWidget($form->createView());

        // no foo
        $this->assertSame('<input type="text" id="text" name="text" required="required" value="value" />', $html);
    }

    public function testButtonAttributes()
    {
        $form = $this->factory->createNamed('button', 'button', null, array(
            'disabled' => true,
            'attr' => array('class' => 'foobar', 'data-foo' => 'bar'),
        ));

        $html = $this->renderWidget($form->createView());

        // compare plain HTML to check the whitespace
        $this->assertSame('<button type="button" id="button" name="button" disabled="disabled" class="foobar" data-foo="bar">[trans]Button[/trans]</button>', $html);
    }

    public function testButtonAttributeNameRepeatedIfTrue()
    {
        $form = $this->factory->createNamed('button', 'button', null, array(
            'attr' => array('foo' => true),
        ));

        $html = $this->renderWidget($form->createView());

        // foo="foo"
        $this->assertSame('<button type="button" id="button" name="button" foo="foo">[trans]Button[/trans]</button>', $html);
    }

    public function testButtonAttributeHiddenIfFalse()
    {
        $form = $this->factory->createNamed('button', 'button', null, array(
            'attr' => array('foo' => false),
        ));

        $html = $this->renderWidget($form->createView());

        // no foo
        $this->assertSame('<button type="button" id="button" name="button">[trans]Button[/trans]</button>', $html);
    }
}
PK+1[����5Form/Symfony/Component/Form/Tests/Guess/GuessTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Guess;

use Symfony\Component\Form\Guess\Guess;

class TestGuess extends Guess {}

class GuessTest extends \PHPUnit_Framework_TestCase
{
    public function testGetBestGuessReturnsGuessWithHighestConfidence()
    {
        $guess1 = new TestGuess(Guess::MEDIUM_CONFIDENCE);
        $guess2 = new TestGuess(Guess::LOW_CONFIDENCE);
        $guess3 = new TestGuess(Guess::HIGH_CONFIDENCE);

        $this->assertSame($guess3, Guess::getBestGuess(array($guess1, $guess2, $guess3)));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGuessExpectsValidConfidence()
    {
        new TestGuess(5);
    }
}
PK+1[�u@Form/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

/**
 * This class is a hand written simplified version of PHP native `ArrayObject`
 * class, to show that it behaves differently than the PHP native implementation.
 */
class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable
{
    private $array;

    public function __construct(array $array = null)
    {
        $this->array = $array ?: array();
    }

    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->array);
    }

    public function offsetGet($offset)
    {
        return $this->array[$offset];
    }

    public function offsetSet($offset, $value)
    {
        if (null === $offset) {
            $this->array[] = $value;
        } else {
            $this->array[$offset] = $value;
        }
    }

    public function offsetUnset($offset)
    {
        unset($this->array[$offset]);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->array);
    }

    public function count()
    {
        return count($this->array);
    }

    public function serialize()
    {
        return serialize($this->array);
    }

    public function unserialize($serialized)
    {
        $this->array = (array) unserialize((string) $serialized);
    }
}
PK+1[�x���5Form/Symfony/Component/Form/Tests/Fixtures/Author.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

class Author
{
    public $firstName;
    private $lastName;
    private $australian;
    public $child;
    private $readPermissions;

    private $privateProperty;

    public function setLastName($lastName)
    {
        $this->lastName = $lastName;
    }

    public function getLastName()
    {
        return $this->lastName;
    }

    private function getPrivateGetter()
    {
        return 'foobar';
    }

    public function setAustralian($australian)
    {
        $this->australian = $australian;
    }

    public function isAustralian()
    {
        return $this->australian;
    }

    public function setReadPermissions($bool)
    {
        $this->readPermissions = $bool;
    }

    public function hasReadPermissions()
    {
        return $this->readPermissions;
    }

    private function isPrivateIsser()
    {
        return true;
    }

    public function getPrivateSetter()
    {
    }

    private function setPrivateSetter($data)
    {
    }
}
PK+1[.Form/Symfony/Component/Form/Tests/Fixtures/foonu�[���PK+1[[��َ�BForm/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

class FooTypeBazExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('baz', 'x');
    }

    public function getExtendedType()
    {
        return 'foo';
    }
}
PK+1[���*��6Form/Symfony/Component/Form/Tests/Fixtures/FooType.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FooType extends AbstractType
{
    public function getName()
    {
        return 'foo';
    }

    public function getParent()
    {
        return null;
    }
}
PK+1[:�.z��AForm/Symfony/Component/Form/Tests/Fixtures/AlternatingRowType.phpnu�[���<?php

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormBuilderInterface;

class AlternatingRowType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $formFactory = $builder->getFormFactory();

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formFactory) {
            $form = $event->getForm();
            $type = $form->getName() % 2 === 0 ? 'text' : 'textarea';
            $form->add('title', $type);
        });
    }

    public function getName()
    {
        return 'alternating_row';
    }
}
PK+1[֫�v��9Form/Symfony/Component/Form/Tests/Fixtures/AuthorType.phpnu�[���<?php

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AuthorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName')
            ->add('lastName')
        ;
    }

    public function getName()
    {
        return 'author';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
        ));
    }
}
PK+1[#�o9Form/Symfony/Component/Form/Tests/Fixtures/FooSubType.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FooSubType extends AbstractType
{
    public function getName()
    {
        return 'foo_sub_type';
    }

    public function getParent()
    {
        return 'foo';
    }
}
PK+1[��8���<Form/Symfony/Component/Form/Tests/Fixtures/TestExtension.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\FormTypeInterface;
use Symfony\Component\Form\FormTypeExtensionInterface;
use Symfony\Component\Form\FormTypeGuesserInterface;
use Symfony\Component\Form\FormExtensionInterface;

class TestExtension implements FormExtensionInterface
{
    private $types = array();

    private $extensions = array();

    private $guesser;

    public function __construct(FormTypeGuesserInterface $guesser)
    {
        $this->guesser = $guesser;
    }

    public function addType(FormTypeInterface $type)
    {
        $this->types[$type->getName()] = $type;
    }

    public function getType($name)
    {
        return isset($this->types[$name]) ? $this->types[$name] : null;
    }

    public function hasType($name)
    {
        return isset($this->types[$name]);
    }

    public function addTypeExtension(FormTypeExtensionInterface $extension)
    {
        $type = $extension->getExtendedType();

        if (!isset($this->extensions[$type])) {
            $this->extensions[$type] = array();
        }

        $this->extensions[$type][] = $extension;
    }

    public function getTypeExtensions($name)
    {
        return isset($this->extensions[$name]) ? $this->extensions[$name] : array();
    }

    public function hasTypeExtensions($name)
    {
        return isset($this->extensions[$name]);
    }

    public function getTypeGuesser()
    {
        return $this->guesser;
    }
}
PK+1[��x�

BForm/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;

class FooTypeBarExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('bar', 'x');
    }

    public function getAllowedOptionValues()
    {
        return array(
            'a_or_b' => array('c'),
        );
    }

    public function getExtendedType()
    {
        return 'foo';
    }
}
PK+1[m^�2++KForm/Symfony/Component/Form/Tests/Fixtures/FooSubTypeWithParentInstance.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FooSubTypeWithParentInstance extends AbstractType
{
    public function getName()
    {
        return 'foo_sub_type_parent_instance';
    }

    public function getParent()
    {
        return new FooType();
    }
}
PK+1[��!u��BForm/Symfony/Component/Form/Tests/Fixtures/FixedFilterListener.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class FixedFilterListener implements EventSubscriberInterface
{
    private $mapping;

    public function __construct(array $mapping)
    {
        $this->mapping = array_merge(array(
            'preSubmit' => array(),
            'onSubmit' => array(),
            'preSetData' => array(),
        ), $mapping);
    }

    public function preSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (isset($this->mapping['preSubmit'][$data])) {
            $event->setData($this->mapping['preSubmit'][$data]);
        }
    }

    public function onSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (isset($this->mapping['onSubmit'][$data])) {
            $event->setData($this->mapping['onSubmit'][$data]);
        }
    }

    public function preSetData(FormEvent $event)
    {
        $data = $event->getData();

        if (isset($this->mapping['preSetData'][$data])) {
            $event->setData($this->mapping['preSetData'][$data]);
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SUBMIT => 'preSubmit',
            FormEvents::SUBMIT => 'onSubmit',
            FormEvents::PRE_SET_DATA => 'preSetData',
        );
    }
}
PK+1[��UUCForm/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Fixtures;

use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\RuntimeException;

class FixedDataTransformer implements DataTransformerInterface
{
    private $mapping;

    public function __construct(array $mapping)
    {
        $this->mapping = $mapping;
    }

    public function transform($value)
    {
        if (!array_key_exists($value, $this->mapping)) {
            throw new RuntimeException(sprintf('No mapping for value "%s"', $value));
        }

        return $this->mapping[$value];
    }

    public function reverseTransform($value)
    {
        $result = array_search($value, $this->mapping, true);

        if ($result === false) {
            throw new RuntimeException(sprintf('No reverse mapping for value "%s"', $value));
        }

        return $result;
    }
}
PK+1[J����R�R5Form/Symfony/Component/Form/Tests/FormFactoryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Form\Guess\ValueGuess;
use Symfony\Component\Form\Guess\TypeGuess;
use Symfony\Component\Form\Tests\Fixtures\Author;
use Symfony\Component\Form\Tests\Fixtures\FooType;
use Symfony\Component\Form\Tests\Fixtures\FooSubType;
use Symfony\Component\Form\Tests\Fixtures\FooSubTypeWithParentInstance;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $guesser1;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $guesser2;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $registry;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $resolvedTypeFactory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $builder;

    /**
     * @var FormFactory
     */
    private $factory;

    protected function setUp()
    {
        $this->resolvedTypeFactory = $this->getMock('Symfony\Component\Form\ResolvedFormTypeFactoryInterface');
        $this->guesser1 = $this->getMock('Symfony\Component\Form\FormTypeGuesserInterface');
        $this->guesser2 = $this->getMock('Symfony\Component\Form\FormTypeGuesserInterface');
        $this->registry = $this->getMock('Symfony\Component\Form\FormRegistryInterface');
        $this->builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface');
        $this->factory = new FormFactory($this->registry, $this->resolvedTypeFactory);

        $this->registry->expects($this->any())
            ->method('getTypeGuesser')
            ->will($this->returnValue(new FormTypeGuesserChain(array(
                $this->guesser1,
                $this->guesser2,
            ))));
    }

    public function testCreateNamedBuilderWithTypeName()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $resolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('type')
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', 'type', null, $options));
    }

    public function testCreateNamedBuilderWithTypeInstance()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $type = new FooType();
        $resolvedType = $this->getMockResolvedType();

        $this->resolvedTypeFactory->expects($this->once())
            ->method('createResolvedType')
            ->with($type)
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', $type, null, $options));
    }

    public function testCreateNamedBuilderWithTypeInstanceWithParentType()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $type = new FooSubType();
        $resolvedType = $this->getMockResolvedType();
        $parentResolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('foo')
            ->will($this->returnValue($parentResolvedType));

        $this->resolvedTypeFactory->expects($this->once())
            ->method('createResolvedType')
            ->with($type, array(), $parentResolvedType)
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', $type, null, $options));
    }

    public function testCreateNamedBuilderWithTypeInstanceWithParentTypeInstance()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $type = new FooSubTypeWithParentInstance();
        $resolvedType = $this->getMockResolvedType();
        $parentResolvedType = $this->getMockResolvedType();

        $this->resolvedTypeFactory->expects($this->at(0))
            ->method('createResolvedType')
            ->with($type->getParent())
            ->will($this->returnValue($parentResolvedType));

        $this->resolvedTypeFactory->expects($this->at(1))
            ->method('createResolvedType')
            ->with($type, array(), $parentResolvedType)
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', $type, null, $options));
    }

    public function testCreateNamedBuilderWithResolvedTypeInstance()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $resolvedType = $this->getMockResolvedType();

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', $resolvedType, null, $options));
    }

    public function testCreateNamedBuilderFillsDataOption()
    {
        $givenOptions = array('a' => '1', 'b' => '2');
        $expectedOptions = array_merge($givenOptions, array('data' => 'DATA'));
        $resolvedOptions = array('a' => '2', 'b' => '3', 'data' => 'DATA');
        $resolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('type')
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $expectedOptions)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', 'type', 'DATA', $givenOptions));
    }

    public function testCreateNamedBuilderDoesNotOverrideExistingDataOption()
    {
        $options = array('a' => '1', 'b' => '2', 'data' => 'CUSTOM');
        $resolvedOptions = array('a' => '2', 'b' => '3', 'data' => 'CUSTOM');
        $resolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('type')
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->assertSame($this->builder, $this->factory->createNamedBuilder('name', 'type', 'DATA', $options));
    }

    /**
     * @expectedException        \Symfony\Component\Form\Exception\UnexpectedTypeException
     * @expectedExceptionMessage Expected argument of type "string, Symfony\Component\Form\ResolvedFormTypeInterface or Symfony\Component\Form\FormTypeInterface", "stdClass" given
     */
    public function testCreateNamedBuilderThrowsUnderstandableException()
    {
        $this->factory->createNamedBuilder('name', new \stdClass());
    }

    public function testCreateUsesTypeNameIfTypeGivenAsString()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $resolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('TYPE')
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'TYPE', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->builder->expects($this->once())
            ->method('getForm')
            ->will($this->returnValue('FORM'));

        $this->assertSame('FORM', $this->factory->create('TYPE', null, $options));
    }

    public function testCreateUsesTypeNameIfTypeGivenAsObject()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $resolvedType = $this->getMockResolvedType();

        $resolvedType->expects($this->once())
            ->method('getName')
            ->will($this->returnValue('TYPE'));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'TYPE', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->builder->expects($this->once())
            ->method('getForm')
            ->will($this->returnValue('FORM'));

        $this->assertSame('FORM', $this->factory->create($resolvedType, null, $options));
    }

    public function testCreateNamed()
    {
        $options = array('a' => '1', 'b' => '2');
        $resolvedOptions = array('a' => '2', 'b' => '3');
        $resolvedType = $this->getMockResolvedType();

        $this->registry->expects($this->once())
            ->method('getType')
            ->with('type')
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->once())
            ->method('createBuilder')
            ->with($this->factory, 'name', $options)
            ->will($this->returnValue($this->builder));

        $this->builder->expects($this->any())
            ->method('getOptions')
            ->will($this->returnValue($resolvedOptions));

        $resolvedType->expects($this->once())
            ->method('buildForm')
            ->with($this->builder, $resolvedOptions);

        $this->builder->expects($this->once())
            ->method('getForm')
            ->will($this->returnValue('FORM'));

        $this->assertSame('FORM', $this->factory->createNamed('name', 'type', null, $options));
    }

    public function testCreateBuilderForPropertyWithoutTypeGuesser()
    {
        $registry = $this->getMock('Symfony\Component\Form\FormRegistryInterface');
        $factory = $this->getMockBuilder('Symfony\Component\Form\FormFactory')
            ->setMethods(array('createNamedBuilder'))
            ->setConstructorArgs(array($registry, $this->resolvedTypeFactory))
            ->getMock();

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text', null, array())
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty('Application\Author', 'firstName');

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testCreateBuilderForPropertyCreatesFormWithHighestConfidence()
    {
        $this->guesser1->expects($this->once())
            ->method('guessType')
            ->with('Application\Author', 'firstName')
            ->will($this->returnValue(new TypeGuess(
                'text',
                array('max_length' => 10),
                Guess::MEDIUM_CONFIDENCE
            )));

        $this->guesser2->expects($this->once())
            ->method('guessType')
            ->with('Application\Author', 'firstName')
            ->will($this->returnValue(new TypeGuess(
                'password',
                array('max_length' => 7),
                Guess::HIGH_CONFIDENCE
            )));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'password', null, array('max_length' => 7))
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty('Application\Author', 'firstName');

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testCreateBuilderCreatesTextFormIfNoGuess()
    {
        $this->guesser1->expects($this->once())
                ->method('guessType')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(null));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text')
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty('Application\Author', 'firstName');

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testOptionsCanBeOverridden()
    {
        $this->guesser1->expects($this->once())
                ->method('guessType')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new TypeGuess(
                    'text',
                    array('max_length' => 10),
                    Guess::MEDIUM_CONFIDENCE
                )));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text', null, array('max_length' => 11))
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty(
            'Application\Author',
            'firstName',
            null,
            array('max_length' => 11)
        );

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testCreateBuilderUsesMaxLengthIfFound()
    {
        $this->guesser1->expects($this->once())
                ->method('guessMaxLength')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    15,
                    Guess::MEDIUM_CONFIDENCE
                )));

        $this->guesser2->expects($this->once())
                ->method('guessMaxLength')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    20,
                    Guess::HIGH_CONFIDENCE
                )));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text', null, array('max_length' => 20))
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty(
            'Application\Author',
            'firstName'
        );

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testCreateBuilderUsesRequiredSettingWithHighestConfidence()
    {
        $this->guesser1->expects($this->once())
                ->method('guessRequired')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    true,
                    Guess::MEDIUM_CONFIDENCE
                )));

        $this->guesser2->expects($this->once())
                ->method('guessRequired')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    false,
                    Guess::HIGH_CONFIDENCE
                )));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text', null, array('required' => false))
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty(
            'Application\Author',
            'firstName'
        );

        $this->assertEquals('builderInstance', $this->builder);
    }

    public function testCreateBuilderUsesPatternIfFound()
    {
        $this->guesser1->expects($this->once())
                ->method('guessPattern')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    '[a-z]',
                    Guess::MEDIUM_CONFIDENCE
                )));

        $this->guesser2->expects($this->once())
                ->method('guessPattern')
                ->with('Application\Author', 'firstName')
                ->will($this->returnValue(new ValueGuess(
                    '[a-zA-Z]',
                    Guess::HIGH_CONFIDENCE
                )));

        $factory = $this->getMockFactory(array('createNamedBuilder'));

        $factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('firstName', 'text', null, array('pattern' => '[a-zA-Z]'))
            ->will($this->returnValue('builderInstance'));

        $this->builder = $factory->createBuilderForProperty(
            'Application\Author',
            'firstName'
        );

        $this->assertEquals('builderInstance', $this->builder);
    }

    private function getMockFactory(array $methods = array())
    {
        return $this->getMockBuilder('Symfony\Component\Form\FormFactory')
            ->setMethods($methods)
            ->setConstructorArgs(array($this->registry, $this->resolvedTypeFactory))
            ->getMock();
    }

    private function getMockResolvedType()
    {
        return $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
    }

    private function getMockType()
    {
        return $this->getMock('Symfony\Component\Form\FormTypeInterface');
    }
}
PK+1[ȔfVA6A6=Form/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Util;

use Symfony\Component\Form\Util\OrderedHashMap;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class OrderedHashMapTest extends \PHPUnit_Framework_TestCase
{
    public function testGet()
    {
        $map = new OrderedHashMap();
        $map['first'] = 1;

        $this->assertSame(1, $map['first']);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetNonExistingFails()
    {
        $map = new OrderedHashMap();

        $map['first'];
    }

    public function testInsertStringKeys()
    {
        $map = new OrderedHashMap();
        $map['first'] = 1;
        $map['second'] = 2;

        $this->assertSame(array('first' => 1, 'second' => 2), iterator_to_array($map));
    }

    public function testInsertNullKeys()
    {
        $map = new OrderedHashMap();
        $map[] = 1;
        $map['foo'] = 2;
        $map[] = 3;

        $this->assertSame(array(0 => 1, 'foo' => 2, 1 => 3), iterator_to_array($map));
    }

    /**
     * Updates should not change the position of an element, otherwise we could
     * turn foreach loops into endless loops if they change the current
     * element:
     *
     *     foreach ($map as $index => $value) {
     *         $map[$index] = $value + 1;
     *     }
     *
     * And we don't want this, right? :)
     */
    public function testUpdateDoesNotChangeElementPosition()
    {
        $map = new OrderedHashMap();
        $map['first'] = 1;
        $map['second'] = 2;
        $map['first'] = 1;

        $this->assertSame(array('first' => 1, 'second' => 2), iterator_to_array($map));
    }

    public function testIsset()
    {
        $map = new OrderedHashMap();
        $map['first'] = 1;

        $this->assertTrue(isset($map['first']));
    }

    public function testIssetReturnsFalseForNonExisting()
    {
        $map = new OrderedHashMap();

        $this->assertFalse(isset($map['first']));
    }

    public function testIssetReturnsFalseForNull()
    {
        $map = new OrderedHashMap();
        $map['first'] = null;

        $this->assertFalse(isset($map['first']));
    }

    public function testUnset()
    {
        $map = new OrderedHashMap();
        $map['first'] = 1;
        $map['second'] = 2;

        unset($map['first']);

        $this->assertSame(array('second' => 2), iterator_to_array($map));
    }

    public function testUnsetNonExistingSucceeds()
    {
        $map = new OrderedHashMap();

        unset($map['first']);
    }

    public function testEmptyIteration()
    {
        $map = new OrderedHashMap();
        $it = $map->getIterator();

        $it->rewind();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsInsertion()
    {
        $map = new OrderedHashMap(array('first' => 1));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('first', $it->key());
        $this->assertSame(1, $it->current());

        // dynamic modification
        $map['added'] = 2;

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('first', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('added', $it->key());
        $this->assertSame(2, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsDeletionAndInsertion()
    {
        $map = new OrderedHashMap(array('first' => 1, 'removed' => 2));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('first', $it->key());
        $this->assertSame(1, $it->current());

        // dynamic modification
        unset($map['removed']);
        $map['added'] = 3;

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('first', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('added', $it->key());
        $this->assertSame(3, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsDeletionOfCurrentElement()
    {
        $map = new OrderedHashMap(array('removed' => 1, 'next' => 2));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        unset($map['removed']);

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationIgnoresReplacementOfCurrentElement()
    {
        $map = new OrderedHashMap(array('replaced' => 1, 'next' => 2));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('replaced', $it->key());
        $this->assertSame(1, $it->current());

        $map['replaced'] = 3;

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('replaced', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsDeletionOfCurrentAndLastElement()
    {
        $map = new OrderedHashMap(array('removed' => 1));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        unset($map['removed']);

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationIgnoresReplacementOfCurrentAndLastElement()
    {
        $map = new OrderedHashMap(array('replaced' => 1));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('replaced', $it->key());
        $this->assertSame(1, $it->current());

        $map['replaced'] = 2;

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('replaced', $it->key());
        $this->assertSame(1, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsDeletionOfPreviousElement()
    {
        $map = new OrderedHashMap(array('removed' => 1, 'next' => 2, 'onemore' => 3));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        unset($map['removed']);

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('onemore', $it->key());
        $this->assertSame(3, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationIgnoresReplacementOfPreviousElement()
    {
        $map = new OrderedHashMap(array('replaced' => 1, 'next' => 2, 'onemore' => 3));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('replaced', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        $map['replaced'] = 4;

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(2, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('onemore', $it->key());
        $this->assertSame(3, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testIterationSupportsDeletionOfMultiplePreviousElements()
    {
        $map = new OrderedHashMap(array('removed' => 1, 'alsoremoved' => 2, 'next' => 3, 'onemore' => 4));
        $it = $map->getIterator();

        $it->rewind();
        $this->assertTrue($it->valid());
        $this->assertSame('removed', $it->key());
        $this->assertSame(1, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('alsoremoved', $it->key());
        $this->assertSame(2, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(3, $it->current());

        unset($map['removed'], $map['alsoremoved']);

        // iterator is unchanged
        $this->assertTrue($it->valid());
        $this->assertSame('next', $it->key());
        $this->assertSame(3, $it->current());

        // continue iteration
        $it->next();
        $this->assertTrue($it->valid());
        $this->assertSame('onemore', $it->key());
        $this->assertSame(4, $it->current());

        // end of map
        $it->next();
        $this->assertFalse($it->valid());
        $this->assertNull($it->key());
        $this->assertNull($it->current());
    }

    public function testParallelIteration()
    {
        $map = new OrderedHashMap(array('first' => 1, 'second' => 2));
        $it1 = $map->getIterator();
        $it2 = $map->getIterator();

        $it1->rewind();
        $this->assertTrue($it1->valid());
        $this->assertSame('first', $it1->key());
        $this->assertSame(1, $it1->current());

        $it2->rewind();
        $this->assertTrue($it2->valid());
        $this->assertSame('first', $it2->key());
        $this->assertSame(1, $it2->current());

        // 1: continue iteration
        $it1->next();
        $this->assertTrue($it1->valid());
        $this->assertSame('second', $it1->key());
        $this->assertSame(2, $it1->current());

        // 2: remains unchanged
        $this->assertTrue($it2->valid());
        $this->assertSame('first', $it2->key());
        $this->assertSame(1, $it2->current());

        // 1: advance to end of map
        $it1->next();
        $this->assertFalse($it1->valid());
        $this->assertNull($it1->key());
        $this->assertNull($it1->current());

        // 2: remains unchanged
        $this->assertTrue($it2->valid());
        $this->assertSame('first', $it2->key());
        $this->assertSame(1, $it2->current());

        // 2: continue iteration
        $it2->next();
        $this->assertTrue($it2->valid());
        $this->assertSame('second', $it2->key());
        $this->assertSame(2, $it2->current());

        // 1: remains unchanged
        $this->assertFalse($it1->valid());
        $this->assertNull($it1->key());
        $this->assertNull($it1->current());

        // 2: advance to end of map
        $it2->next();
        $this->assertFalse($it2->valid());
        $this->assertNull($it2->key());
        $this->assertNull($it2->current());

        // 1: remains unchanged
        $this->assertFalse($it1->valid());
        $this->assertNull($it1->key());
        $this->assertNull($it1->current());
    }

    public function testCount()
    {
        $map = new OrderedHashMap();
        $map[] = 1;
        $map['foo'] = 2;
        unset($map[0]);
        $map[] = 3;

        $this->assertSame(2, count($map));
    }
}
PK+1[�z�nznz6Form/Symfony/Component/Form/Tests/CompoundFormTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Forms;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\SubmitButtonBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer;

class CompoundFormTest extends AbstractFormTest
{
    public function testValidIfAllChildrenAreValid()
    {
        $this->form->add($this->getBuilder('firstName')->getForm());
        $this->form->add($this->getBuilder('lastName')->getForm());

        $this->form->submit(array(
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
        ));

        $this->assertTrue($this->form->isValid());
    }

    public function testInvalidIfChildIsInvalid()
    {
        $this->form->add($this->getBuilder('firstName')->getForm());
        $this->form->add($this->getBuilder('lastName')->getForm());

        $this->form->submit(array(
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
        ));

        $this->form->get('lastName')->addError(new FormError('Invalid'));

        $this->assertFalse($this->form->isValid());
    }

    public function testValidIfChildIsNotSubmitted()
    {
        $this->form->add($this->getBuilder('firstName')->getForm());
        $this->form->add($this->getBuilder('lastName')->getForm());

        $this->form->submit(array(
            'firstName' => 'Bernhard',
        ));

        // "lastName" is not "valid" because it was not submitted. This happens
        // for example in PATCH requests. The parent form should still be
        // considered valid.

        $this->assertTrue($this->form->isValid());
    }

    public function testDisabledFormsValidEvenIfChildrenInvalid()
    {
        $form = $this->getBuilder('person')
            ->setDisabled(true)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->add($this->getBuilder('name'))
            ->getForm();

        $form->submit(array('name' => 'Jacques Doe'));

        $form->get('name')->addError(new FormError('Invalid'));

        $this->assertTrue($form->isValid());
    }

    public function testSubmitForwardsNullIfNotClearMissingButValueIsExplicitlyNull()
    {
        $child = $this->getMockForm('firstName');

        $this->form->add($child);

        $child->expects($this->once())
            ->method('submit')
            ->with($this->equalTo(null));

        $this->form->submit(array('firstName' => null), false);
    }

    public function testSubmitForwardsNullIfValueIsMissing()
    {
        $child = $this->getMockForm('firstName');

        $this->form->add($child);

        $child->expects($this->once())
            ->method('submit')
            ->with($this->equalTo(null));

        $this->form->submit(array());
    }

    public function testSubmitDoesNotForwardNullIfNotClearMissing()
    {
        $child = $this->getMockForm('firstName');

        $this->form->add($child);

        $child->expects($this->never())
            ->method('submit');

        $this->form->submit(array(), false);
    }

    public function testSubmitDoesNotAddExtraFieldForNullValues()
    {
        $factory = Forms::createFormFactoryBuilder()
            ->getFormFactory();

        $child = $factory->create('file', null, array('auto_initialize' => false));

        $this->form->add($child);
        $this->form->submit(array('file' => null), false);

        $this->assertCount(0, $this->form->getExtraData());
    }

    public function testClearMissingFlagIsForwarded()
    {
        $child = $this->getMockForm('firstName');

        $this->form->add($child);

        $child->expects($this->once())
            ->method('submit')
            ->with($this->equalTo('foo'), false);

        $this->form->submit(array('firstName' => 'foo'), false);
    }

    public function testCloneChildren()
    {
        $child = $this->getBuilder('child')->getForm();
        $this->form->add($child);

        $clone = clone $this->form;

        $this->assertNotSame($this->form, $clone);
        $this->assertNotSame($child, $clone['child']);
        $this->assertNotSame($this->form['child'], $clone['child']);
    }

    public function testNotEmptyIfChildNotEmpty()
    {
        $child = $this->getMockForm();
        $child->expects($this->once())
            ->method('isEmpty')
            ->will($this->returnValue(false));

        $this->form->setData(null);
        $this->form->add($child);

        $this->assertFalse($this->form->isEmpty());
    }

    public function testAdd()
    {
        $child = $this->getBuilder('foo')->getForm();
        $this->form->add($child);

        $this->assertTrue($this->form->has('foo'));
        $this->assertSame($this->form, $child->getParent());
        $this->assertSame(array('foo' => $child), $this->form->all());
    }

    public function testAddUsingNameAndType()
    {
        $child = $this->getBuilder('foo')->getForm();

        $this->factory->expects($this->once())
            ->method('createNamed')
            ->with('foo', 'text', null, array(
                'bar' => 'baz',
                'auto_initialize' => false,
            ))
            ->will($this->returnValue($child));

        $this->form->add('foo', 'text', array('bar' => 'baz'));

        $this->assertTrue($this->form->has('foo'));
        $this->assertSame($this->form, $child->getParent());
        $this->assertSame(array('foo' => $child), $this->form->all());
    }

    public function testAddUsingIntegerNameAndType()
    {
        $child = $this->getBuilder(0)->getForm();

        $this->factory->expects($this->once())
            ->method('createNamed')
            ->with('0', 'text', null, array(
                'bar' => 'baz',
                'auto_initialize' => false,
            ))
            ->will($this->returnValue($child));

        // in order to make casting unnecessary
        $this->form->add(0, 'text', array('bar' => 'baz'));

        $this->assertTrue($this->form->has(0));
        $this->assertSame($this->form, $child->getParent());
        $this->assertSame(array(0 => $child), $this->form->all());
    }

    public function testAddUsingNameButNoType()
    {
        $this->form = $this->getBuilder('name', null, '\stdClass')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();

        $child = $this->getBuilder('foo')->getForm();

        $this->factory->expects($this->once())
            ->method('createForProperty')
            ->with('\stdClass', 'foo')
            ->will($this->returnValue($child));

        $this->form->add('foo');

        $this->assertTrue($this->form->has('foo'));
        $this->assertSame($this->form, $child->getParent());
        $this->assertSame(array('foo' => $child), $this->form->all());
    }

    public function testAddUsingNameButNoTypeAndOptions()
    {
        $this->form = $this->getBuilder('name', null, '\stdClass')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();

        $child = $this->getBuilder('foo')->getForm();

        $this->factory->expects($this->once())
            ->method('createForProperty')
            ->with('\stdClass', 'foo', null, array(
                'bar' => 'baz',
                'auto_initialize' => false,
            ))
            ->will($this->returnValue($child));

        $this->form->add('foo', null, array('bar' => 'baz'));

        $this->assertTrue($this->form->has('foo'));
        $this->assertSame($this->form, $child->getParent());
        $this->assertSame(array('foo' => $child), $this->form->all());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException
     */
    public function testAddThrowsExceptionIfAlreadySubmitted()
    {
        $this->form->submit(array());
        $this->form->add($this->getBuilder('foo')->getForm());
    }

    public function testRemove()
    {
        $child = $this->getBuilder('foo')->getForm();
        $this->form->add($child);
        $this->form->remove('foo');

        $this->assertNull($child->getParent());
        $this->assertCount(0, $this->form);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException
     */
    public function testRemoveThrowsExceptionIfAlreadySubmitted()
    {
        $this->form->add($this->getBuilder('foo')->setCompound(false)->getForm());
        $this->form->submit(array('foo' => 'bar'));
        $this->form->remove('foo');
    }

    public function testRemoveIgnoresUnknownName()
    {
        $this->form->remove('notexisting');
    }

    public function testArrayAccess()
    {
        $child = $this->getBuilder('foo')->getForm();

        $this->form[] = $child;

        $this->assertTrue(isset($this->form['foo']));
        $this->assertSame($child, $this->form['foo']);

        unset($this->form['foo']);

        $this->assertFalse(isset($this->form['foo']));
    }

    public function testCountable()
    {
        $this->form->add($this->getBuilder('foo')->getForm());
        $this->form->add($this->getBuilder('bar')->getForm());

        $this->assertCount(2, $this->form);
    }

    public function testIterator()
    {
        $this->form->add($this->getBuilder('foo')->getForm());
        $this->form->add($this->getBuilder('bar')->getForm());

        $this->assertSame($this->form->all(), iterator_to_array($this->form));
    }

    public function testAddMapsViewDataToFormIfInitialized()
    {
        $test = $this;
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'foo' => 'bar',
            )))
            ->setData('foo')
            ->getForm();

        $child = $this->getBuilder()->getForm();
        $mapper->expects($this->once())
            ->method('mapDataToForms')
            ->with('bar', $this->isInstanceOf('\RecursiveIteratorIterator'))
            ->will($this->returnCallback(function ($data, \RecursiveIteratorIterator $iterator) use ($child, $test) {
                $test->assertInstanceOf('Symfony\Component\Form\Util\InheritDataAwareIterator', $iterator->getInnerIterator());
                $test->assertSame(array($child), iterator_to_array($iterator));
            }));

        $form->initialize();
        $form->add($child);
    }

    public function testAddDoesNotMapViewDataToFormIfNotInitialized()
    {
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->getForm();

        $child = $this->getBuilder()->getForm();
        $mapper->expects($this->never())
            ->method('mapDataToForms');

        $form->add($child);
    }

    public function testAddDoesNotMapViewDataToFormIfInheritData()
    {
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->setInheritData(true)
            ->getForm();

        $child = $this->getBuilder()->getForm();
        $mapper->expects($this->never())
            ->method('mapDataToForms');

        $form->initialize();
        $form->add($child);
    }

    public function testSetDataSupportsDynamicAdditionAndRemovalOfChildren()
    {
        $form = $this->getBuilder()
            ->setCompound(true)
            // We test using PropertyPathMapper on purpose. The traversal logic
            // is currently contained in InheritDataAwareIterator, but even
            // if that changes, this test should still function.
            ->setDataMapper(new PropertyPathMapper())
            ->getForm();

        $child = $this->getMockForm('child');
        $childToBeRemoved = $this->getMockForm('removed');
        $childToBeAdded = $this->getMockForm('added');

        $form->add($child);
        $form->add($childToBeRemoved);

        $child->expects($this->once())
            ->method('setData')
            ->will($this->returnCallback(function () use ($form, $childToBeAdded) {
                $form->remove('removed');
                $form->add($childToBeAdded);
            }));

        $childToBeRemoved->expects($this->never())
            ->method('setData');

        // once when it it is created, once when it is added
        $childToBeAdded->expects($this->exactly(2))
            ->method('setData');

        // pass NULL to all children
        $form->setData(array());
    }

    public function testSetDataMapsViewDataToChildren()
    {
        $test = $this;
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'foo' => 'bar',
            )))
            ->getForm();

        $form->add($child1 = $this->getBuilder('firstName')->getForm());
        $form->add($child2 = $this->getBuilder('lastName')->getForm());

        $mapper->expects($this->once())
            ->method('mapDataToForms')
            ->with('bar', $this->isInstanceOf('\RecursiveIteratorIterator'))
            ->will($this->returnCallback(function ($data, \RecursiveIteratorIterator $iterator) use ($child1, $child2, $test) {
                $test->assertInstanceOf('Symfony\Component\Form\Util\InheritDataAwareIterator', $iterator->getInnerIterator());
                $test->assertSame(array('firstName' => $child1, 'lastName' => $child2), iterator_to_array($iterator));
            }));

        $form->setData('foo');
    }

    public function testSubmitSupportsDynamicAdditionAndRemovalOfChildren()
    {
        $child = $this->getMockForm('child');
        $childToBeRemoved = $this->getMockForm('removed');
        $childToBeAdded = $this->getMockForm('added');

        $this->form->add($child);
        $this->form->add($childToBeRemoved);

        $form = $this->form;

        $child->expects($this->once())
            ->method('submit')
            ->will($this->returnCallback(function () use ($form, $childToBeAdded) {
                $form->remove('removed');
                $form->add($childToBeAdded);
            }));

        $childToBeRemoved->expects($this->never())
            ->method('submit');

        $childToBeAdded->expects($this->once())
            ->method('submit');

        // pass NULL to all children
        $this->form->submit(array());
    }

    public function testSubmitMapsSubmittedChildrenOntoExistingViewData()
    {
        $test = $this;
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'foo' => 'bar',
            )))
            ->setData('foo')
            ->getForm();

        $form->add($child1 = $this->getBuilder('firstName')->setCompound(false)->getForm());
        $form->add($child2 = $this->getBuilder('lastName')->setCompound(false)->getForm());

        $mapper->expects($this->once())
            ->method('mapFormsToData')
            ->with($this->isInstanceOf('\RecursiveIteratorIterator'), 'bar')
            ->will($this->returnCallback(function (\RecursiveIteratorIterator $iterator) use ($child1, $child2, $test) {
                $test->assertInstanceOf('Symfony\Component\Form\Util\InheritDataAwareIterator', $iterator->getInnerIterator());
                $test->assertSame(array('firstName' => $child1, 'lastName' => $child2), iterator_to_array($iterator));
                $test->assertEquals('Bernhard', $child1->getData());
                $test->assertEquals('Schussek', $child2->getData());
            }));

        $form->submit(array(
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
        ));
    }

    public function testMapFormsToDataIsNotInvokedIfInheritData()
    {
        $mapper = $this->getDataMapper();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->setInheritData(true)
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'foo' => 'bar',
            )))
            ->getForm();

        $form->add($child1 = $this->getBuilder('firstName')->setCompound(false)->getForm());
        $form->add($child2 = $this->getBuilder('lastName')->setCompound(false)->getForm());

        $mapper->expects($this->never())
            ->method('mapFormsToData');

        $form->submit(array(
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
        ));
    }

    /*
     * https://github.com/symfony/symfony/issues/4480
     */
    public function testSubmitRestoresViewDataIfCompoundAndEmpty()
    {
        $mapper = $this->getDataMapper();
        $object = new \stdClass();
        $form = $this->getBuilder('name', null, 'stdClass')
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->setData($object)
            ->getForm();

        $form->submit(array());

        $this->assertSame($object, $form->getData());
    }

    public function testSubmitMapsSubmittedChildrenOntoEmptyData()
    {
        $test = $this;
        $mapper = $this->getDataMapper();
        $object = new \stdClass();
        $form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($mapper)
            ->setEmptyData($object)
            ->setData(null)
            ->getForm();

        $form->add($child = $this->getBuilder('name')->setCompound(false)->getForm());

        $mapper->expects($this->once())
            ->method('mapFormsToData')
            ->with($this->isInstanceOf('\RecursiveIteratorIterator'), $object)
            ->will($this->returnCallback(function (\RecursiveIteratorIterator $iterator) use ($child, $test) {
                $test->assertInstanceOf('Symfony\Component\Form\Util\InheritDataAwareIterator', $iterator->getInnerIterator());
                $test->assertSame(array('name' => $child), iterator_to_array($iterator));
            }));

        $form->submit(array(
            'name' => 'Bernhard',
        ));
    }

    public function requestMethodProvider()
    {
        return array(
            array('POST'),
            array('PUT'),
            array('DELETE'),
            array('PATCH'),
        );
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitPostOrPutRequest($method)
    {
        $path = tempnam(sys_get_temp_dir(), 'sf2');
        touch($path);

        $values = array(
            'author' => array(
                'name' => 'Bernhard',
                'image' => array('filename' => 'foobar.png'),
            ),
        );

        $files = array(
            'author' => array(
                'error' => array('image' => UPLOAD_ERR_OK),
                'name' => array('image' => 'upload.png'),
                'size' => array('image' => 123),
                'tmp_name' => array('image' => $path),
                'type' => array('image' => 'image/png'),
            ),
        );

        $request = new Request(array(), $values, array(), array(), $files, array(
            'REQUEST_METHOD' => $method,
        ));

        $form = $this->getBuilder('author')
            ->setMethod($method)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('name')->getForm());
        $form->add($this->getBuilder('image')->getForm());

        $form->handleRequest($request);

        $file = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);

        $this->assertEquals('Bernhard', $form['name']->getData());
        $this->assertEquals($file, $form['image']->getData());

        unlink($path);
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitPostOrPutRequestWithEmptyRootFormName($method)
    {
        $path = tempnam(sys_get_temp_dir(), 'sf2');
        touch($path);

        $values = array(
            'name' => 'Bernhard',
            'extra' => 'data',
        );

        $files = array(
            'image' => array(
                'error' => UPLOAD_ERR_OK,
                'name' => 'upload.png',
                'size' => 123,
                'tmp_name' => $path,
                'type' => 'image/png',
            ),
        );

        $request = new Request(array(), $values, array(), array(), $files, array(
            'REQUEST_METHOD' => $method,
        ));

        $form = $this->getBuilder('')
            ->setMethod($method)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('name')->getForm());
        $form->add($this->getBuilder('image')->getForm());

        $form->handleRequest($request);

        $file = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);

        $this->assertEquals('Bernhard', $form['name']->getData());
        $this->assertEquals($file, $form['image']->getData());
        $this->assertEquals(array('extra' => 'data'), $form->getExtraData());

        unlink($path);
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitPostOrPutRequestWithSingleChildForm($method)
    {
        $path = tempnam(sys_get_temp_dir(), 'sf2');
        touch($path);

        $files = array(
            'image' => array(
                'error' => UPLOAD_ERR_OK,
                'name' => 'upload.png',
                'size' => 123,
                'tmp_name' => $path,
                'type' => 'image/png',
            ),
        );

        $request = new Request(array(), array(), array(), array(), $files, array(
            'REQUEST_METHOD' => $method,
        ));

        $form = $this->getBuilder('image')
            ->setMethod($method)
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();

        $form->handleRequest($request);

        $file = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);

        $this->assertEquals($file, $form->getData());

        unlink($path);
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitPostOrPutRequestWithSingleChildFormUploadedFile($method)
    {
        $path = tempnam(sys_get_temp_dir(), 'sf2');
        touch($path);

        $values = array(
            'name' => 'Bernhard',
        );

        $request = new Request(array(), $values, array(), array(), array(), array(
            'REQUEST_METHOD' => $method,
        ));

        $form = $this->getBuilder('name')
            ->setMethod($method)
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();

        $form->handleRequest($request);

        $this->assertEquals('Bernhard', $form->getData());

        unlink($path);
    }

    public function testSubmitGetRequest()
    {
        $values = array(
            'author' => array(
                'firstName' => 'Bernhard',
                'lastName' => 'Schussek',
            ),
        );

        $request = new Request($values, array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $form = $this->getBuilder('author')
            ->setMethod('GET')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('firstName')->getForm());
        $form->add($this->getBuilder('lastName')->getForm());

        $form->handleRequest($request);

        $this->assertEquals('Bernhard', $form['firstName']->getData());
        $this->assertEquals('Schussek', $form['lastName']->getData());
    }

    public function testSubmitGetRequestWithEmptyRootFormName()
    {
        $values = array(
            'firstName' => 'Bernhard',
            'lastName' => 'Schussek',
            'extra' => 'data'
        );

        $request = new Request($values, array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $form = $this->getBuilder('')
            ->setMethod('GET')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setRequestHandler(new HttpFoundationRequestHandler())
            ->getForm();
        $form->add($this->getBuilder('firstName')->getForm());
        $form->add($this->getBuilder('lastName')->getForm());

        $form->handleRequest($request);

        $this->assertEquals('Bernhard', $form['firstName']->getData());
        $this->assertEquals('Schussek', $form['lastName']->getData());
        $this->assertEquals(array('extra' => 'data'), $form->getExtraData());
    }

    public function testGetErrorsAsStringDeep()
    {
        $parent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();

        $this->form->addError(new FormError('Error!'));

        $parent->add($this->form);
        $parent->add($this->getBuilder('foo')->getForm());

        $this->assertEquals("name:\n    ERROR: Error!\nfoo:\n    No errors\n", $parent->getErrorsAsString());
    }

    // Basic cases are covered in SimpleFormTest
    public function testCreateViewWithChildren()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $options = array('a' => 'Foo', 'b' => 'Bar');
        $field1 = $this->getMockForm('foo');
        $field2 = $this->getMockForm('bar');
        $view = new FormView();
        $field1View = new FormView();
        $field2View = new FormView();

        $this->form = $this->getBuilder('form', null, null, $options)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setType($type)
            ->getForm();
        $this->form->add($field1);
        $this->form->add($field2);

        $test = $this;

        $assertChildViewsEqual = function (array $childViews) use ($test) {
            return function (FormView $view) use ($test, $childViews) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertSame($childViews, $view->children);
            };
        };

        // First create the view
        $type->expects($this->once())
            ->method('createView')
            ->will($this->returnValue($view));

        // Then build it for the form itself
        $type->expects($this->once())
            ->method('buildView')
            ->with($view, $this->form, $options)
            ->will($this->returnCallback($assertChildViewsEqual(array())));

        // Then add the first child form
        $field1->expects($this->once())
            ->method('createView')
            ->will($this->returnValue($field1View));

        // Then the second child form
        $field2->expects($this->once())
            ->method('createView')
            ->will($this->returnValue($field2View));

        // Again build the view for the form itself. This time the child views
        // exist.
        $type->expects($this->once())
            ->method('finishView')
            ->with($view, $this->form, $options)
            ->will($this->returnCallback($assertChildViewsEqual(array('foo' => $field1View, 'bar' => $field2View))));

        $this->assertSame($view, $this->form->createView());
    }

    public function testNoClickedButtonBeforeSubmission()
    {
        $this->assertNull($this->form->getClickedButton());
    }

    public function testNoClickedButton()
    {
        $button = $this->getMockBuilder('Symfony\Component\Form\SubmitButton')
            ->setConstructorArgs(array(new SubmitButtonBuilder('submit')))
            ->setMethods(array('isClicked'))
            ->getMock();

        $button->expects($this->any())
            ->method('isClicked')
            ->will($this->returnValue(false));

        $parentForm = $this->getBuilder('parent')->getForm();
        $nestedForm = $this->getBuilder('nested')->getForm();

        $this->form->setParent($parentForm);
        $this->form->add($button);
        $this->form->add($nestedForm);
        $this->form->submit(array());

        $this->assertNull($this->form->getClickedButton());
    }

    public function testClickedButton()
    {
        $button = $this->getMockBuilder('Symfony\Component\Form\SubmitButton')
            ->setConstructorArgs(array(new SubmitButtonBuilder('submit')))
            ->setMethods(array('isClicked'))
            ->getMock();

        $button->expects($this->any())
            ->method('isClicked')
            ->will($this->returnValue(true));

        $this->form->add($button);
        $this->form->submit(array());

        $this->assertSame($button, $this->form->getClickedButton());
    }

    public function testClickedButtonFromNestedForm()
    {
        $button = $this->getBuilder('submit')->getForm();

        $nestedForm = $this->getMockBuilder('Symfony\Component\Form\Form')
            ->setConstructorArgs(array($this->getBuilder('nested')))
            ->setMethods(array('getClickedButton'))
            ->getMock();

        $nestedForm->expects($this->any())
            ->method('getClickedButton')
            ->will($this->returnValue($button));

        $this->form->add($nestedForm);
        $this->form->submit(array());

        $this->assertSame($button, $this->form->getClickedButton());
    }

    public function testClickedButtonFromParentForm()
    {
        $button = $this->getBuilder('submit')->getForm();

        $parentForm = $this->getMockBuilder('Symfony\Component\Form\Form')
            ->setConstructorArgs(array($this->getBuilder('parent')))
            ->setMethods(array('getClickedButton'))
            ->getMock();

        $parentForm->expects($this->any())
            ->method('getClickedButton')
            ->will($this->returnValue($button));

        $this->form->setParent($parentForm);
        $this->form->submit(array());

        $this->assertSame($button, $this->form->getClickedButton());
    }

    protected function createForm()
    {
        return $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
    }
}
PK+1[���d<Form/Symfony/Component/Form/Tests/FormFactoryBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormFactoryBuilder;
use Symfony\Component\Form\Tests\Fixtures\FooType;

class FormFactoryBuilderTest extends \PHPUnit_Framework_TestCase
{
    private $registry;
    private $guesser;
    private $type;

    protected function setUp()
    {
        $factory = new \ReflectionClass('Symfony\Component\Form\FormFactory');
        $this->registry = $factory->getProperty('registry');
        $this->registry->setAccessible(true);

        $this->guesser = $this->getMock('Symfony\Component\Form\FormTypeGuesserInterface');
        $this->type = new FooType();
    }

    public function testAddType()
    {
        $factoryBuilder = new FormFactoryBuilder();
        $factoryBuilder->addType($this->type);

        $factory = $factoryBuilder->getFormFactory();
        $registry = $this->registry->getValue($factory);
        $extensions = $registry->getExtensions();

        $this->assertCount(1, $extensions);
        $this->assertTrue($extensions[0]->hasType($this->type->getName()));
        $this->assertNull($extensions[0]->getTypeGuesser());
    }

    public function testAddTypeGuesser()
    {
        $factoryBuilder = new FormFactoryBuilder();
        $factoryBuilder->addTypeGuesser($this->guesser);

        $factory = $factoryBuilder->getFormFactory();
        $registry = $this->registry->getValue($factory);
        $extensions = $registry->getExtensions();

        $this->assertCount(1, $extensions);
        $this->assertNotNull($extensions[0]->getTypeGuesser());
    }
}
PK+1[̈́����6Form/Symfony/Component/Form/Tests/FormRegistryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormRegistry;
use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\Form\Tests\Fixtures\TestExtension;
use Symfony\Component\Form\Tests\Fixtures\FooSubTypeWithParentInstance;
use Symfony\Component\Form\Tests\Fixtures\FooSubType;
use Symfony\Component\Form\Tests\Fixtures\FooTypeBazExtension;
use Symfony\Component\Form\Tests\Fixtures\FooTypeBarExtension;
use Symfony\Component\Form\Tests\Fixtures\FooType;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormRegistryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FormRegistry
     */
    private $registry;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $resolvedTypeFactory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $guesser1;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $guesser2;

    /**
     * @var TestExtension
     */
    private $extension1;

    /**
     * @var TestExtension
     */
    private $extension2;

    protected function setUp()
    {
        $this->resolvedTypeFactory = $this->getMock('Symfony\Component\Form\ResolvedFormTypeFactory');
        $this->guesser1 = $this->getMock('Symfony\Component\Form\FormTypeGuesserInterface');
        $this->guesser2 = $this->getMock('Symfony\Component\Form\FormTypeGuesserInterface');
        $this->extension1 = new TestExtension($this->guesser1);
        $this->extension2 = new TestExtension($this->guesser2);
        $this->registry = new FormRegistry(array(
            $this->extension1,
            $this->extension2,
        ), $this->resolvedTypeFactory);
    }

    public function testGetTypeFromExtension()
    {
        $type = new FooType();
        $resolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');

        $this->extension2->addType($type);

        $this->resolvedTypeFactory->expects($this->once())
            ->method('createResolvedType')
            ->with($type)
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $resolvedType = $this->registry->getType('foo');

        $this->assertSame($resolvedType, $this->registry->getType('foo'));
    }

    public function testGetTypeWithTypeExtensions()
    {
        $type = new FooType();
        $ext1 = new FooTypeBarExtension();
        $ext2 = new FooTypeBazExtension();
        $resolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');

        $this->extension2->addType($type);
        $this->extension1->addTypeExtension($ext1);
        $this->extension2->addTypeExtension($ext2);

        $this->resolvedTypeFactory->expects($this->once())
            ->method('createResolvedType')
            ->with($type, array($ext1, $ext2))
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $this->assertSame($resolvedType, $this->registry->getType('foo'));
    }

    public function testGetTypeConnectsParent()
    {
        $parentType = new FooType();
        $type = new FooSubType();
        $parentResolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $resolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');

        $this->extension1->addType($parentType);
        $this->extension2->addType($type);

        $this->resolvedTypeFactory->expects($this->at(0))
            ->method('createResolvedType')
            ->with($parentType)
            ->will($this->returnValue($parentResolvedType));

        $this->resolvedTypeFactory->expects($this->at(1))
            ->method('createResolvedType')
            ->with($type, array(), $parentResolvedType)
            ->will($this->returnValue($resolvedType));

        $parentResolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $resolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo_sub_type'));

        $this->assertSame($resolvedType, $this->registry->getType('foo_sub_type'));
    }

    public function testGetTypeConnectsParentIfGetParentReturnsInstance()
    {
        $type = new FooSubTypeWithParentInstance();
        $parentResolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $resolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');

        $this->extension1->addType($type);

        $this->resolvedTypeFactory->expects($this->at(0))
            ->method('createResolvedType')
            ->with($this->isInstanceOf('Symfony\Component\Form\Tests\Fixtures\FooType'))
            ->will($this->returnValue($parentResolvedType));

        $this->resolvedTypeFactory->expects($this->at(1))
            ->method('createResolvedType')
            ->with($type, array(), $parentResolvedType)
            ->will($this->returnValue($resolvedType));

        $parentResolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $resolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo_sub_type_parent_instance'));

        $this->assertSame($resolvedType, $this->registry->getType('foo_sub_type_parent_instance'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testGetTypeThrowsExceptionIfParentNotFound()
    {
        $type = new FooSubType();

        $this->extension1->addType($type);

        $this->registry->getType($type);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     */
    public function testGetTypeThrowsExceptionIfTypeNotFound()
    {
        $this->registry->getType('bar');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testGetTypeThrowsExceptionIfNoString()
    {
        $this->registry->getType(array());
    }

    public function testHasTypeAfterLoadingFromExtension()
    {
        $type = new FooType();
        $resolvedType = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');

        $this->resolvedTypeFactory->expects($this->once())
            ->method('createResolvedType')
            ->with($type)
            ->will($this->returnValue($resolvedType));

        $resolvedType->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'));

        $this->assertFalse($this->registry->hasType('foo'));

        $this->extension2->addType($type);

        $this->assertTrue($this->registry->hasType('foo'));
    }

    public function testGetTypeGuesser()
    {
        $expectedGuesser = new FormTypeGuesserChain(array($this->guesser1, $this->guesser2));

        $this->assertEquals($expectedGuesser, $this->registry->getTypeGuesser());

        $registry = new FormRegistry(
            array($this->getMock('Symfony\Component\Form\FormExtensionInterface')),
            $this->resolvedTypeFactory);

        $this->assertNull($registry->getTypeGuesser());
    }

    public function testGetExtensions()
    {
        $expectedExtensions = array($this->extension1, $this->extension2);

        $this->assertEquals($expectedExtensions, $this->registry->getExtensions());
    }
}
PK+1[]�9�}}4Form/Symfony/Component/Form/Tests/FormConfigTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\Exception\InvalidArgumentException;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormConfigTest extends \PHPUnit_Framework_TestCase
{
    public function getHtml4Ids()
    {
        return array(
            array('z0', true),
            array('A0', true),
            array('A9', true),
            array('Z0', true),
            array('#', false),
            array('a#', false),
            array('a$', false),
            array('a%', false),
            array('a ', false),
            array("a\t", false),
            array("a\n", false),
            array('a-', true),
            array('a_', true),
            array('a:', true),
            // Periods are allowed by the HTML4 spec, but disallowed by us
            // because they break the generated property paths
            array('a.', false),
            // Contrary to the HTML4 spec, we allow names starting with a
            // number, otherwise naming fields by collection indices is not
            // possible.
            // For root forms, leading digits will be stripped from the
            // "id" attribute to produce valid HTML4.
            array('0', true),
            array('9', true),
            // Contrary to the HTML4 spec, we allow names starting with an
            // underscore, since this is already a widely used practice in
            // Symfony2.
            // For root forms, leading underscores will be stripped from the
            // "id" attribute to produce valid HTML4.
            array('_', true),
            // Integers are allowed
            array(0, true),
            array(123, true),
            // NULL is allowed
            array(null, true),
            // Other types are not
            array(1.23, false),
            array(5., false),
            array(true, false),
            array(new \stdClass(), false),
        );
    }

    /**
     * @dataProvider getHtml4Ids
     */
    public function testNameAcceptsOnlyNamesValidAsIdsInHtml4($name, $accepted)
    {
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');

        try {
            new FormConfigBuilder($name, null, $dispatcher);
            if (!$accepted) {
                $this->fail(sprintf('The value "%s" should not be accepted', $name));
            }
        } catch (UnexpectedTypeException $e) {
            // if the value was not accepted, but should be, rethrow exception
            if ($accepted) {
                throw $e;
            }
        } catch (InvalidArgumentException $e) {
            // if the value was not accepted, but should be, rethrow exception
            if ($accepted) {
                throw $e;
            }
        }
    }

    public function testGetRequestHandlerCreatesNativeRequestHandlerIfNotSet()
    {
        $config = $this->getConfigBuilder()->getFormConfig();

        $this->assertInstanceOf('Symfony\Component\Form\NativeRequestHandler', $config->getRequestHandler());
    }

    public function testGetRequestHandlerReusesNativeRequestHandlerInstance()
    {
        $config1 = $this->getConfigBuilder()->getFormConfig();
        $config2 = $this->getConfigBuilder()->getFormConfig();

        $this->assertSame($config1->getRequestHandler(), $config2->getRequestHandler());
    }

    public function testSetMethodAllowsGet()
    {
        $this->getConfigBuilder()->setMethod('GET');
    }

    public function testSetMethodAllowsPost()
    {
        $this->getConfigBuilder()->setMethod('POST');
    }

    public function testSetMethodAllowsPut()
    {
        $this->getConfigBuilder()->setMethod('PUT');
    }

    public function testSetMethodAllowsDelete()
    {
        $this->getConfigBuilder()->setMethod('DELETE');
    }

    public function testSetMethodAllowsPatch()
    {
        $this->getConfigBuilder()->setMethod('PATCH');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     */
    public function testSetMethodDoesNotAllowOtherValues()
    {
        $this->getConfigBuilder()->setMethod('foo');
    }

    private function getConfigBuilder($name = 'name')
    {
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');

        return new FormConfigBuilder($name, null, $dispatcher);
    }
}
PK+1[�>)�bb@Form/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractRequestHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\Form\RequestHandlerInterface
     */
    protected $requestHandler;

    protected $request;

    protected function setUp()
    {
        $this->requestHandler = $this->getRequestHandler();
        $this->request = null;
    }

    public function methodExceptGetProvider()
    {
        return array(
            array('POST'),
            array('PUT'),
            array('DELETE'),
            array('PATCH'),
        );
    }

    public function methodProvider()
    {
        return array_merge(array(
            array('GET'),
        ), $this->methodExceptGetProvider());
    }

    /**
     * @dataProvider methodProvider
     */
    public function testSubmitIfNameInRequest($method)
    {
        $form = $this->getMockForm('param1', $method);

        $this->setRequestData($method, array(
            'param1' => 'DATA',
        ));

        $form->expects($this->once())
            ->method('submit')
            ->with('DATA', 'PATCH' !== $method);

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodProvider
     */
    public function testDoNotSubmitIfWrongRequestMethod($method)
    {
        $form = $this->getMockForm('param1', $method);

        $otherMethod = 'POST' === $method ? 'PUT' : 'POST';

        $this->setRequestData($otherMethod, array(
            'param1' => 'DATA',
        ));

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodExceptGetProvider
     */
    public function testDoNoSubmitSimpleFormIfNameNotInRequestAndNotGetRequest($method)
    {
        $form = $this->getMockForm('param1', $method, false);

        $this->setRequestData($method, array(
            'paramx' => array(),
        ));

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodExceptGetProvider
     */
    public function testDoNotSubmitCompoundFormIfNameNotInRequestAndNotGetRequest($method)
    {
        $form = $this->getMockForm('param1', $method, true);

        $this->setRequestData($method, array(
            'paramx' => array(),
        ));

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    public function testDoNotSubmitIfNameNotInRequestAndGetRequest()
    {
        $form = $this->getMockForm('param1', 'GET');

        $this->setRequestData('GET', array(
            'paramx' => array(),
        ));

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodProvider
     */
    public function testSubmitFormWithEmptyNameIfAtLeastOneFieldInRequest($method)
    {
        $form = $this->getMockForm('', $method);
        $form->expects($this->any())
            ->method('all')
            ->will($this->returnValue(array(
                'param1' => $this->getMockForm('param1'),
                'param2' => $this->getMockForm('param2'),
            )));

        $this->setRequestData($method, $requestData = array(
            'param1' => 'submitted value',
            'paramx' => 'submitted value',
        ));

        $form->expects($this->once())
            ->method('submit')
            ->with($requestData, 'PATCH' !== $method);

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodProvider
     */
    public function testDoNotSubmitFormWithEmptyNameIfNoFieldInRequest($method)
    {
        $form = $this->getMockForm('', $method);
        $form->expects($this->any())
            ->method('all')
            ->will($this->returnValue(array(
                'param1' => $this->getMockForm('param1'),
                'param2' => $this->getMockForm('param2'),
            )));

        $this->setRequestData($method, array(
            'paramx' => 'submitted value',
        ));

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodExceptGetProvider
     */
    public function testMergeParamsAndFiles($method)
    {
        $form = $this->getMockForm('param1', $method);
        $file = $this->getMockFile();

        $this->setRequestData($method, array(
            'param1' => array(
                'field1' => 'DATA',
            ),
        ), array(
            'param1' => array(
                'field2' => $file,
            ),
        ));

        $form->expects($this->once())
            ->method('submit')
            ->with(array(
                'field1' => 'DATA',
                'field2' => $file,
            ), 'PATCH' !== $method);

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodExceptGetProvider
     */
    public function testParamTakesPrecedenceOverFile($method)
    {
        $form = $this->getMockForm('param1', $method);
        $file = $this->getMockFile();

        $this->setRequestData($method, array(
            'param1' => 'DATA',
        ), array(
            'param1' => $file,
        ));

        $form->expects($this->once())
            ->method('submit')
            ->with('DATA', 'PATCH' !== $method);

        $this->requestHandler->handleRequest($form, $this->request);
    }

    /**
     * @dataProvider methodExceptGetProvider
     */
    public function testSubmitFileIfNoParam($method)
    {
        $form = $this->getMockForm('param1', $method);
        $file = $this->getMockFile();

        $this->setRequestData($method, array(
            'param1' => null,
        ), array(
            'param1' => $file,
        ));

        $form->expects($this->once())
            ->method('submit')
            ->with($file, 'PATCH' !== $method);

        $this->requestHandler->handleRequest($form, $this->request);
    }

    abstract protected function setRequestData($method, $data, $files = array());

    abstract protected function getRequestHandler();

    abstract protected function getMockFile();

    protected function getMockForm($name, $method = null, $compound = true)
    {
        $config = $this->getMock('Symfony\Component\Form\FormConfigInterface');
        $config->expects($this->any())
            ->method('getMethod')
            ->will($this->returnValue($method));
        $config->expects($this->any())
            ->method('getCompound')
            ->will($this->returnValue($compound));

        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $form->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($name));
        $form->expects($this->any())
            ->method('getConfig')
            ->will($this->returnValue($config));

        return $form;
    }
}
PK+1[ū@d22:Form/Symfony/Component/Form/Tests/ResolvedFormTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\ResolvedFormType;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Form;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ResolvedFormTypeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $factory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dataMapper;
    private $parentType;
    private $type;
    private $extension1;
    private $extension2;
    private $parentResolvedType;
    private $resolvedType;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->dataMapper = $this->getMock('Symfony\Component\Form\DataMapperInterface');
        $this->parentType = $this->getMockFormType();
        $this->type = $this->getMockFormType();
        $this->extension1 = $this->getMockFormTypeExtension();
        $this->extension2 = $this->getMockFormTypeExtension();
        $this->parentResolvedType = new ResolvedFormType($this->parentType);
        $this->resolvedType = new ResolvedFormType($this->type, array($this->extension1, $this->extension2), $this->parentResolvedType);
    }

    public function testGetOptionsResolver()
    {
        if (version_compare(\PHPUnit_Runner_Version::id(), '3.7', '<')) {
            $this->markTestSkipped('This test requires PHPUnit 3.7.');
        }

        $test = $this;
        $i = 0;

        $assertIndexAndAddOption = function ($index, $option, $default) use (&$i, $test) {
            return function (OptionsResolverInterface $resolver) use (&$i, $test, $index, $option, $default) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertEquals($index, $i, 'Executed at index '.$index);

                ++$i;

                $resolver->setDefaults(array($option => $default));
            };
        };

        // First the default options are generated for the super type
        $this->parentType->expects($this->once())
            ->method('setDefaultOptions')
            ->will($this->returnCallback($assertIndexAndAddOption(0, 'a', 'a_default')));

        // The form type itself
        $this->type->expects($this->once())
            ->method('setDefaultOptions')
            ->will($this->returnCallback($assertIndexAndAddOption(1, 'b', 'b_default')));

        // And its extensions
        $this->extension1->expects($this->once())
            ->method('setDefaultOptions')
            ->will($this->returnCallback($assertIndexAndAddOption(2, 'c', 'c_default')));

        $this->extension2->expects($this->once())
            ->method('setDefaultOptions')
            ->will($this->returnCallback($assertIndexAndAddOption(3, 'd', 'd_default')));

        $givenOptions = array('a' => 'a_custom', 'c' => 'c_custom');
        $resolvedOptions = array('a' => 'a_custom', 'b' => 'b_default', 'c' => 'c_custom', 'd' => 'd_default');

        $resolver = $this->resolvedType->getOptionsResolver();

        $this->assertEquals($resolvedOptions, $resolver->resolve($givenOptions));
    }

    public function testCreateBuilder()
    {
        if (version_compare(\PHPUnit_Runner_Version::id(), '3.7', '<')) {
            $this->markTestSkipped('This test requires PHPUnit 3.7.');
        }

        $givenOptions = array('a' => 'a_custom', 'c' => 'c_custom');
        $resolvedOptions = array('a' => 'a_custom', 'b' => 'b_default', 'c' => 'c_custom', 'd' => 'd_default');
        $optionsResolver = $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface');

        $this->resolvedType = $this->getMockBuilder('Symfony\Component\Form\ResolvedFormType')
            ->setConstructorArgs(array($this->type, array($this->extension1, $this->extension2), $this->parentResolvedType))
            ->setMethods(array('getOptionsResolver'))
            ->getMock();

        $this->resolvedType->expects($this->once())
            ->method('getOptionsResolver')
            ->will($this->returnValue($optionsResolver));

        $optionsResolver->expects($this->once())
            ->method('resolve')
            ->with($givenOptions)
            ->will($this->returnValue($resolvedOptions));

        $factory = $this->getMockFormFactory();
        $builder = $this->resolvedType->createBuilder($factory, 'name', $givenOptions);

        $this->assertSame($this->resolvedType, $builder->getType());
        $this->assertSame($resolvedOptions, $builder->getOptions());
        $this->assertNull($builder->getDataClass());
    }

    public function testCreateBuilderWithDataClassOption()
    {
        if (version_compare(\PHPUnit_Runner_Version::id(), '3.7', '<')) {
            $this->markTestSkipped('This test requires PHPUnit 3.7.');
        }

        $givenOptions = array('data_class' => 'Foo');
        $resolvedOptions = array('data_class' => '\stdClass');
        $optionsResolver = $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface');

        $this->resolvedType = $this->getMockBuilder('Symfony\Component\Form\ResolvedFormType')
            ->setConstructorArgs(array($this->type, array($this->extension1, $this->extension2), $this->parentResolvedType))
            ->setMethods(array('getOptionsResolver'))
            ->getMock();

        $this->resolvedType->expects($this->once())
            ->method('getOptionsResolver')
            ->will($this->returnValue($optionsResolver));

        $optionsResolver->expects($this->once())
            ->method('resolve')
            ->with($givenOptions)
            ->will($this->returnValue($resolvedOptions));

        $factory = $this->getMockFormFactory();
        $builder = $this->resolvedType->createBuilder($factory, 'name', $givenOptions);

        $this->assertSame($this->resolvedType, $builder->getType());
        $this->assertSame($resolvedOptions, $builder->getOptions());
        $this->assertSame('\stdClass', $builder->getDataClass());
    }

    public function testBuildForm()
    {
        if (version_compare(\PHPUnit_Runner_Version::id(), '3.7', '<')) {
            $this->markTestSkipped('This test requires PHPUnit 3.7.');
        }

        $test = $this;
        $i = 0;

        $assertIndex = function ($index) use (&$i, $test) {
            return function () use (&$i, $test, $index) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertEquals($index, $i, 'Executed at index '.$index);

                ++$i;
            };
        };

        $options = array('a' => 'Foo', 'b' => 'Bar');
        $builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface');

        // First the form is built for the super type
        $this->parentType->expects($this->once())
            ->method('buildForm')
            ->with($builder, $options)
            ->will($this->returnCallback($assertIndex(0)));

        // Then the type itself
        $this->type->expects($this->once())
            ->method('buildForm')
            ->with($builder, $options)
            ->will($this->returnCallback($assertIndex(1)));

        // Then its extensions
        $this->extension1->expects($this->once())
            ->method('buildForm')
            ->with($builder, $options)
            ->will($this->returnCallback($assertIndex(2)));

        $this->extension2->expects($this->once())
            ->method('buildForm')
            ->with($builder, $options)
            ->will($this->returnCallback($assertIndex(3)));

        $this->resolvedType->buildForm($builder, $options);
    }

    public function testCreateView()
    {
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');

        $view = $this->resolvedType->createView($form);

        $this->assertInstanceOf('Symfony\Component\Form\FormView', $view);
        $this->assertNull($view->parent);
    }

    public function testCreateViewWithParent()
    {
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $parentView = $this->getMock('Symfony\Component\Form\FormView');

        $view = $this->resolvedType->createView($form, $parentView);

        $this->assertInstanceOf('Symfony\Component\Form\FormView', $view);
        $this->assertSame($parentView, $view->parent);
    }

    public function testBuildView()
    {
        $options = array('a' => '1', 'b' => '2');
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $view = $this->getMock('Symfony\Component\Form\FormView');

        $test = $this;
        $i = 0;

        $assertIndex = function ($index) use (&$i, $test) {
            return function () use (&$i, $test, $index) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertEquals($index, $i, 'Executed at index '.$index);

                ++$i;
            };
        };

        // First the super type
        $this->parentType->expects($this->once())
            ->method('buildView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(0)));

        // Then the type itself
        $this->type->expects($this->once())
            ->method('buildView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(1)));

        // Then its extensions
        $this->extension1->expects($this->once())
            ->method('buildView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(2)));

        $this->extension2->expects($this->once())
            ->method('buildView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(3)));

        $this->resolvedType->buildView($view, $form, $options);
    }

    public function testFinishView()
    {
        $options = array('a' => '1', 'b' => '2');
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $view = $this->getMock('Symfony\Component\Form\FormView');

        $test = $this;
        $i = 0;

        $assertIndex = function ($index) use (&$i, $test) {
            return function () use (&$i, $test, $index) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertEquals($index, $i, 'Executed at index '.$index);

                ++$i;
            };
        };

        // First the super type
        $this->parentType->expects($this->once())
            ->method('finishView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(0)));

        // Then the type itself
        $this->type->expects($this->once())
            ->method('finishView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(1)));

        // Then its extensions
        $this->extension1->expects($this->once())
            ->method('finishView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(2)));

        $this->extension2->expects($this->once())
            ->method('finishView')
            ->with($view, $form, $options)
            ->will($this->returnCallback($assertIndex(3)));

        $this->resolvedType->finishView($view, $form, $options);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockFormType()
    {
        return $this->getMock('Symfony\Component\Form\FormTypeInterface');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockFormTypeExtension()
    {
        return $this->getMock('Symfony\Component\Form\FormTypeExtensionInterface');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getMockFormFactory()
    {
        return $this->getMock('Symfony\Component\Form\FormFactoryInterface');
    }

    /**
     * @param string $name
     * @param array $options
     *
     * @return FormBuilder
     */
    protected function getBuilder($name = 'name', array $options = array())
    {
        return new FormBuilder($name, null, $this->dispatcher, $this->factory, $options);
    }
}
PK+1[O� )KK=Form/Symfony/Component/Form/Tests/FormIntegrationTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\Test\FormIntegrationTestCase as BaseFormIntegrationTestCase;

/**
 * @deprecated Deprecated since version 2.3, to be removed in 3.0. Use Symfony\Component\Form\Test\FormIntegrationTestCase instead.
 */
abstract class FormIntegrationTestCase extends BaseFormIntegrationTestCase
{
}
PK+1[��K)ooAForm/Symfony/Component/Form/Tests/CompoundFormPerformanceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CompoundFormPerformanceTest extends \Symfony\Component\Form\Tests\FormPerformanceTestCase
{
    /**
     * Create a compound form multiple times, as happens in a collection form
     *
     * @group benchmark
     */
    public function testArrayBasedForm()
    {
        $this->setMaxRunningTime(1);

        for ($i = 0; $i < 40; ++$i) {
            $form = $this->factory->createBuilder('form')
                ->add('firstName', 'text')
                ->add('lastName', 'text')
                ->add('gender', 'choice', array(
                    'choices' => array('male' => 'Male', 'female' => 'Female'),
                    'required' => false,
                ))
                ->add('age', 'number')
                ->add('birthDate', 'birthday')
                ->add('city', 'choice', array(
                    // simulate 300 different cities
                    'choices' => range(1, 300),
                ))
                ->getForm();

            // load the form into a view
            $form->createView();
        }
    }
}
PK+1[tٴ��6Form/Symfony/Component/Form/Tests/FormRendererTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

class FormRendererTest extends \PHPUnit_Framework_TestCase
{
    public function testHumanize()
    {
        $renderer = $this->getMockBuilder('Symfony\Component\Form\FormRenderer')
            ->setMethods(null)
            ->disableOriginalConstructor()
            ->getMock()
        ;

        $this->assertEquals('Is active', $renderer->humanize('is_active'));
        $this->assertEquals('Is active', $renderer->humanize('isActive'));
    }
}
PK+1[�d�!!>Form/Symfony/Component/Form/Tests/NativeRequestHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\NativeRequestHandler;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class NativeRequestHandlerTest extends AbstractRequestHandlerTest
{
    private static $serverBackup;

    public static function setUpBeforeClass()
    {
        self::$serverBackup = $_SERVER;
    }

    protected function setUp()
    {
        parent::setUp();

        $_GET = array();
        $_POST = array();
        $_FILES = array();
        $_SERVER = array(
            // PHPUnit needs this entry
            'SCRIPT_NAME' => self::$serverBackup['SCRIPT_NAME'],
        );
    }

    protected function tearDown()
    {
        parent::tearDown();

        $_GET = array();
        $_POST = array();
        $_FILES = array();
        $_SERVER = self::$serverBackup;
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testRequestShouldBeNull()
    {
        $this->requestHandler->handleRequest($this->getMockForm('name', 'GET'), 'request');
    }

    public function testMethodOverrideHeaderTakesPrecedenceIfPost()
    {
        $form = $this->getMockForm('param1', 'PUT');

        $this->setRequestData('POST', array(
            'param1' => 'DATA',
        ));

        $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';

        $form->expects($this->once())
            ->method('submit')
            ->with('DATA');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    public function testConvertEmptyUploadedFilesToNull()
    {
        $form = $this->getMockForm('param1', 'POST', false);

        $this->setRequestData('POST', array(), array('param1' => array(
            'name' => '',
            'type' => '',
            'tmp_name' => '',
            'error' => UPLOAD_ERR_NO_FILE,
            'size' => 0
        )));

        $form->expects($this->once())
            ->method('submit')
            ->with($this->identicalTo(null));

        $this->requestHandler->handleRequest($form, $this->request);
    }

    public function testFixBuggyFilesArray()
    {
        $form = $this->getMockForm('param1', 'POST', false);

        $this->setRequestData('POST', array(), array('param1' => array(
            'name' => array(
                'field' => 'upload.txt',
            ),
            'type' => array(
                'field' => 'text/plain',
            ),
            'tmp_name' => array(
                'field' => 'owfdskjasdfsa',
            ),
            'error' => array(
                'field' => UPLOAD_ERR_OK,
            ),
            'size' => array(
                'field' => 100,
            ),
        )));

        $form->expects($this->once())
            ->method('submit')
            ->with(array(
                'field' => array(
                    'name' => 'upload.txt',
                    'type' => 'text/plain',
                    'tmp_name' => 'owfdskjasdfsa',
                    'error' => UPLOAD_ERR_OK,
                    'size' => 100,
                ),
            ));

        $this->requestHandler->handleRequest($form, $this->request);
    }

    public function testFixBuggyNestedFilesArray()
    {
        $form = $this->getMockForm('param1', 'POST');

        $this->setRequestData('POST', array(), array('param1' => array(
            'name' => array(
                'field' => array('subfield' => 'upload.txt'),
            ),
            'type' => array(
                'field' => array('subfield' => 'text/plain'),
            ),
            'tmp_name' => array(
                'field' => array('subfield' => 'owfdskjasdfsa'),
            ),
            'error' => array(
                'field' => array('subfield' => UPLOAD_ERR_OK),
            ),
            'size' => array(
                'field' => array('subfield' => 100),
            ),
        )));

        $form->expects($this->once())
            ->method('submit')
            ->with(array(
                'field' => array(
                    'subfield' => array(
                        'name' => 'upload.txt',
                        'type' => 'text/plain',
                        'tmp_name' => 'owfdskjasdfsa',
                        'error' => UPLOAD_ERR_OK,
                        'size' => 100,
                    ),
                ),
            ));

        $this->requestHandler->handleRequest($form, $this->request);
    }

    public function testMethodOverrideHeaderIgnoredIfNotPost()
    {
        $form = $this->getMockForm('param1', 'POST');

        $this->setRequestData('GET', array(
                'param1' => 'DATA',
            ));

        $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] = 'PUT';

        $form->expects($this->never())
            ->method('submit');

        $this->requestHandler->handleRequest($form, $this->request);
    }

    protected function setRequestData($method, $data, $files = array())
    {
        if ('GET' === $method) {
            $_GET = $data;
            $_FILES = array();
        } else {
            $_POST = $data;
            $_FILES = $files;
        }

        $_SERVER = array(
            'REQUEST_METHOD' => $method,
            // PHPUnit needs this entry
            'SCRIPT_NAME' => self::$serverBackup['SCRIPT_NAME'],
        );
    }

    protected function getRequestHandler()
    {
        return new NativeRequestHandler();
    }

    protected function getMockFile()
    {
        return array(
            'name' => 'upload.txt',
            'type' => 'text/plain',
            'tmp_name' => 'owfdskjasdfsa',
            'error' => UPLOAD_ERR_OK,
            'size' => 100,
        );
    }
}
PK+1[�����5Form/Symfony/Component/Form/Tests/FormBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormBuilder;

class FormBuilderTest extends \PHPUnit_Framework_TestCase
{
    private $dispatcher;

    private $factory;

    private $builder;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->builder = new FormBuilder('name', null, $this->dispatcher, $this->factory);
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->factory = null;
        $this->builder = null;
    }

    /**
     * Changing the name is not allowed, otherwise the name and property path
     * are not synchronized anymore
     *
     * @see FormType::buildForm
     */
    public function testNoSetName()
    {
        $this->assertFalse(method_exists($this->builder, 'setName'));
    }

    public function testAddNameNoStringAndNoInteger()
    {
        $this->setExpectedException('Symfony\Component\Form\Exception\UnexpectedTypeException');
        $this->builder->add(true);
    }

    public function testAddTypeNoString()
    {
        $this->setExpectedException('Symfony\Component\Form\Exception\UnexpectedTypeException');
        $this->builder->add('foo', 1234);
    }

    public function testAddWithGuessFluent()
    {
        $this->builder = new FormBuilder('name', 'stdClass', $this->dispatcher, $this->factory);
        $builder = $this->builder->add('foo');
        $this->assertSame($builder, $this->builder);
    }

    public function testAddIsFluent()
    {
        $builder = $this->builder->add('foo', 'text', array('bar' => 'baz'));
        $this->assertSame($builder, $this->builder);
    }

    public function testAdd()
    {
        $this->assertFalse($this->builder->has('foo'));
        $this->builder->add('foo', 'text');
        $this->assertTrue($this->builder->has('foo'));
    }

    public function testAddIntegerName()
    {
        $this->assertFalse($this->builder->has(0));
        $this->builder->add(0, 'text');
        $this->assertTrue($this->builder->has(0));
    }

    public function testAll()
    {
        $this->factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('foo', 'text')
            ->will($this->returnValue(new FormBuilder('foo', null, $this->dispatcher, $this->factory)));

        $this->assertCount(0, $this->builder->all());
        $this->assertFalse($this->builder->has('foo'));

        $this->builder->add('foo', 'text');
        $children = $this->builder->all();

        $this->assertTrue($this->builder->has('foo'));
        $this->assertCount(1, $children);
        $this->assertArrayHasKey('foo', $children);
    }

    /*
     * https://github.com/symfony/symfony/issues/4693
     */
    public function testMaintainOrderOfLazyAndExplicitChildren()
    {
        $this->builder->add('foo', 'text');
        $this->builder->add($this->getFormBuilder('bar'));
        $this->builder->add('baz', 'text');

        $children = $this->builder->all();

        $this->assertSame(array('foo', 'bar', 'baz'), array_keys($children));
    }

    public function testAddFormType()
    {
        $this->assertFalse($this->builder->has('foo'));
        $this->builder->add('foo', $this->getMock('Symfony\Component\Form\FormTypeInterface'));
        $this->assertTrue($this->builder->has('foo'));
    }

    public function testRemove()
    {
        $this->builder->add('foo', 'text');
        $this->builder->remove('foo');
        $this->assertFalse($this->builder->has('foo'));
    }

    public function testRemoveUnknown()
    {
        $this->builder->remove('foo');
        $this->assertFalse($this->builder->has('foo'));
    }

    // https://github.com/symfony/symfony/pull/4826
    public function testRemoveAndGetForm()
    {
        $this->builder->add('foo', 'text');
        $this->builder->remove('foo');
        $form = $this->builder->getForm();
        $this->assertInstanceOf('Symfony\Component\Form\Form', $form);
    }

    public function testCreateNoTypeNo()
    {
        $this->factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with('foo', 'text', null, array())
        ;

        $this->builder->create('foo');
    }

    public function testGetUnknown()
    {
        $this->setExpectedException('Symfony\Component\Form\Exception\InvalidArgumentException', 'The child with the name "foo" does not exist.');
        $this->builder->get('foo');
    }

    public function testGetExplicitType()
    {
        $expectedType = 'text';
        $expectedName = 'foo';
        $expectedOptions = array('bar' => 'baz');

        $this->factory->expects($this->once())
            ->method('createNamedBuilder')
            ->with($expectedName, $expectedType, null, $expectedOptions)
            ->will($this->returnValue($this->getFormBuilder()));

        $this->builder->add($expectedName, $expectedType, $expectedOptions);
        $builder = $this->builder->get($expectedName);

        $this->assertNotSame($builder, $this->builder);
    }

    public function testGetGuessedType()
    {
        $expectedName = 'foo';
        $expectedOptions = array('bar' => 'baz');

        $this->factory->expects($this->once())
            ->method('createBuilderForProperty')
            ->with('stdClass', $expectedName, null, $expectedOptions)
            ->will($this->returnValue($this->getFormBuilder()));

        $this->builder = new FormBuilder('name', 'stdClass', $this->dispatcher, $this->factory);
        $this->builder->add($expectedName, null, $expectedOptions);
        $builder = $this->builder->get($expectedName);

        $this->assertNotSame($builder, $this->builder);
    }

    public function testGetFormConfigErasesReferences()
    {
        $builder = new FormBuilder('name', null, $this->dispatcher, $this->factory);
        $builder->add(new FormBuilder('child', null, $this->dispatcher, $this->factory));

        $config = $builder->getFormConfig();
        $reflClass = new \ReflectionClass($config);
        $children = $reflClass->getProperty('children');
        $unresolvedChildren = $reflClass->getProperty('unresolvedChildren');

        $children->setAccessible(true);
        $unresolvedChildren->setAccessible(true);

        $this->assertEmpty($children->getValue($config));
        $this->assertEmpty($unresolvedChildren->getValue($config));
    }

    private function getFormBuilder($name = 'name')
    {
        $mock = $this->getMockBuilder('Symfony\Component\Form\FormBuilder')
            ->disableOriginalConstructor()
            ->getMock();

        $mock->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($name));

        return $mock;
    }
}
PK+1[RmhZTZT;Form/Symfony/Component/Form/Tests/AbstractDivLayoutTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Tests\Fixtures\AlternatingRowType;
use Symfony\Component\Security\Csrf\CsrfToken;

abstract class AbstractDivLayoutTest extends AbstractLayoutTest
{
    public function testRow()
    {
        $form = $this->factory->createNamed('name', 'text');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name"]
        /following-sibling::ul
            [./li[.="[trans]Error![/trans]"]]
            [count(./li)=1]
        /following-sibling::input[@id="name"]
    ]
'
        );
    }

    public function testRowOverrideVariables()
    {
        $view = $this->factory->createNamed('name', 'text')->createView();
        $html = $this->renderRow($view, array(
            'attr' => array('class' => 'my&class'),
            'label' => 'foo&bar',
            'label_attr' => array('class' => 'my&label&class'),
        ));

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name"][@class="my&label&class required"][.="[trans]foo&bar[/trans]"]
        /following-sibling::input[@id="name"][@class="my&class"]
    ]
'
        );
    }

    public function testRepeatedRow()
    {
        $form = $this->factory->createNamed('name', 'repeated');
        $form->addError(new FormError('[trans]Error![/trans]'));
        $view = $form->createView();
        $html = $this->renderRow($view);

        // The errors of the form are not rendered by intention!
        // In practice, repeated fields cannot have errors as all errors
        // on them are mapped to the first child.
        // (see RepeatedTypeValidatorExtension)

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name_first"]
        /following-sibling::input[@id="name_first"]
    ]
/following-sibling::div
    [
        ./label[@for="name_second"]
        /following-sibling::input[@id="name_second"]
    ]
'
        );
    }

    public function testButtonRow()
    {
        $form = $this->factory->createNamed('name', 'button');
        $view = $form->createView();
        $html = $this->renderRow($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./button[@type="button"][@name="name"]
    ]
    [count(//label)=0]
'
        );
    }

    public function testRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'repeated')
            ->add('field3', 'text')
            ->add('field4', 'text')
            ->getForm()
            ->createView();

        // Render field2 row -> does not implicitly call renderWidget because
        // it is a repeated field!
        $this->renderRow($view['field2']);

        // Render field3 widget
        $this->renderWidget($view['field3']);

        // Rest should only contain field1 and field4
        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name_field1"]
        /following-sibling::input[@type="text"][@id="name_field1"]
    ]
/following-sibling::div
    [
        ./label[@for="name_field4"]
        /following-sibling::input[@type="text"][@id="name_field4"]
    ]
    [count(../div)=2]
    [count(..//label)=2]
    [count(..//input)=3]
/following-sibling::input
    [@type="hidden"]
    [@id="name__token"]
'
        );
    }

    public function testRestWithChildrenForms()
    {
        $child1 = $this->factory->createNamedBuilder('child1', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text');

        $child2 = $this->factory->createNamedBuilder('child2', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text');

        $view = $this->factory->createNamedBuilder('parent', 'form')
            ->add($child1)
            ->add($child2)
            ->getForm()
            ->createView();

        // Render child1.field1 row
        $this->renderRow($view['child1']['field1']);

        // Render child2.field2 widget (remember that widget don't render label)
        $this->renderWidget($view['child2']['field2']);

        // Rest should only contain child1.field2 and child2.field1
        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[not(@for)]
        /following-sibling::div[@id="parent_child1"]
            [
                ./div
                    [
                        ./label[@for="parent_child1_field2"]
                        /following-sibling::input[@id="parent_child1_field2"]
                    ]
            ]
    ]

/following-sibling::div
    [
        ./label[not(@for)]
        /following-sibling::div[@id="parent_child2"]
            [
                ./div
                    [
                        ./label[@for="parent_child2_field1"]
                        /following-sibling::input[@id="parent_child2_field1"]
                    ]
            ]
    ]
    [count(//label)=4]
    [count(//input[@type="text"])=2]
/following-sibling::input[@type="hidden"][@id="parent__token"]
'
        );
    }

    public function testRestAndRepeatedWithRow()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('first', 'text')
            ->add('password', 'repeated')
            ->getForm()
            ->createView();

        $this->renderRow($view['password']);

        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name_first"]
        /following-sibling::input[@type="text"][@id="name_first"]
    ]
    [count(.//input)=1]
/following-sibling::input
    [@type="hidden"]
    [@id="name__token"]
'
        );
    }

    public function testRestAndRepeatedWithRowPerChild()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('first', 'text')
            ->add('password', 'repeated')
            ->getForm()
            ->createView();

        $this->renderRow($view['password']['first']);
        $this->renderRow($view['password']['second']);

        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name_first"]
        /following-sibling::input[@type="text"][@id="name_first"]
    ]
    [count(.//input)=1]
    [count(.//label)=1]
/following-sibling::input
    [@type="hidden"]
    [@id="name__token"]
'
        );
    }

    public function testRestAndRepeatedWithWidgetPerChild()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('first', 'text')
            ->add('password', 'repeated')
            ->getForm()
            ->createView();

        // The password form is considered as rendered as all its children
        // are rendered
        $this->renderWidget($view['password']['first']);
        $this->renderWidget($view['password']['second']);

        $html = $this->renderRest($view);

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name_first"]
        /following-sibling::input[@type="text"][@id="name_first"]
    ]
    [count(//input)=2]
    [count(//label)=1]
/following-sibling::input
    [@type="hidden"]
    [@id="name__token"]
'
        );
    }

    public function testCollection()
    {
        $form = $this->factory->createNamed('name', 'collection', array('a', 'b'), array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div[./input[@type="text"][@value="a"]]
        /following-sibling::div[./input[@type="text"][@value="b"]]
    ]
    [count(./div[./input])=2]
'
        );
    }

    // https://github.com/symfony/symfony/issues/5038
    public function testCollectionWithAlternatingRowTypes()
    {
        $data = array(
            array('title' => 'a'),
            array('title' => 'b'),
        );
        $form = $this->factory->createNamed('name', 'collection', $data, array(
            'type' => new AlternatingRowType(),
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div[./div/div/input[@type="text"][@value="a"]]
        /following-sibling::div[./div/div/textarea[.="b"]]
    ]
    [count(./div[./div/div/input])=1]
    [count(./div[./div/div/textarea])=1]
'
        );
    }

    public function testEmptyCollection()
    {
        $form = $this->factory->createNamed('name', 'collection', array(), array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [./input[@type="hidden"][@id="name__token"]]
    [count(./div)=0]
'
        );
    }

    public function testCollectionRow()
    {
        $collection = $this->factory->createNamedBuilder(
            'collection',
            'collection',
            array('a', 'b'),
            array('type' => 'text')
        );

        $form = $this->factory->createNamedBuilder('form', 'form')
          ->add($collection)
          ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [
                ./label[not(@for)]
                /following-sibling::div
                    [
                        ./div
                            [
                                ./label[@for="form_collection_0"]
                                /following-sibling::input[@type="text"][@value="a"]
                            ]
                        /following-sibling::div
                            [
                                ./label[@for="form_collection_1"]
                                /following-sibling::input[@type="text"][@value="b"]
                            ]
                    ]
            ]
        /following-sibling::input[@type="hidden"][@id="form__token"]
    ]
    [count(.//input)=3]
'
        );
    }

    public function testForm()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->setMethod('PUT')
            ->setAction('http://example.com')
            ->add('firstName', 'text')
            ->add('lastName', 'text')
            ->getForm();

        // include ampersands everywhere to validate escaping
        $html = $this->renderForm($form->createView(), array(
            'id' => 'my&id',
            'attr' => array('class' => 'my&class'),
        ));

        $this->assertMatchesXpath($html,
'/form
    [
        ./input[@type="hidden"][@name="_method"][@value="PUT"]
        /following-sibling::div
            [
                ./div
                    [
                        ./label[@for="name_firstName"]
                        /following-sibling::input[@type="text"][@id="name_firstName"]
                    ]
                /following-sibling::div
                    [
                        ./label[@for="name_lastName"]
                        /following-sibling::input[@type="text"][@id="name_lastName"]
                    ]
                /following-sibling::input[@type="hidden"][@id="name__token"]
            ]
            [count(.//input)=3]
            [@id="my&id"]
            [@class="my&class"]
    ]
    [@method="post"]
    [@action="http://example.com"]
    [@class="my&class"]
'
        );
    }

    public function testFormWidget()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add('firstName', 'text')
            ->add('lastName', 'text')
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [
                ./label[@for="name_firstName"]
                /following-sibling::input[@type="text"][@id="name_firstName"]
            ]
        /following-sibling::div
            [
                ./label[@for="name_lastName"]
                /following-sibling::input[@type="text"][@id="name_lastName"]
            ]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(.//input)=3]
'
        );
    }

    // https://github.com/symfony/symfony/issues/2308
    public function testNestedFormError()
    {
        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add($this->factory
                ->createNamedBuilder('child', 'form', null, array('error_bubbling' => false))
                ->add('grandChild', 'form')
            )
            ->getForm();

        $form->get('child')->addError(new FormError('[trans]Error![/trans]'));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div/label
        /following-sibling::ul[./li[.="[trans]Error![/trans]"]]
    ]
    [count(.//li[.="[trans]Error![/trans]"])=1]
'
        );
    }

    public function testCsrf()
    {
        $this->csrfTokenManager->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(new CsrfToken('token_id', 'foo&bar')));

        $form = $this->factory->createNamedBuilder('name', 'form')
            ->add($this->factory
                // No CSRF protection on nested forms
                ->createNamedBuilder('child', 'form')
                ->add($this->factory->createNamedBuilder('grandchild', 'text'))
            )
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
        /following-sibling::input[@type="hidden"][@id="name__token"][@value="foo&bar"]
    ]
    [count(.//input[@type="hidden"])=1]
'
        );
    }

    public function testRepeated()
    {
        $form = $this->factory->createNamed('name', 'repeated', 'foobar', array(
            'type' => 'text',
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [
                ./label[@for="name_first"]
                /following-sibling::input[@type="text"][@id="name_first"]
            ]
        /following-sibling::div
            [
                ./label[@for="name_second"]
                /following-sibling::input[@type="text"][@id="name_second"]
            ]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(.//input)=3]
'
        );
    }

    public function testRepeatedWithCustomOptions()
    {
        $form = $this->factory->createNamed('name', 'repeated', null, array(
            // the global required value cannot be overridden
            'first_options'  => array('label' => 'Test', 'required' => false),
            'second_options' => array('label' => 'Test2')
        ));

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [
                ./label[@for="name_first"][.="[trans]Test[/trans]"]
                /following-sibling::input[@type="text"][@id="name_first"][@required="required"]
            ]
        /following-sibling::div
            [
                ./label[@for="name_second"][.="[trans]Test2[/trans]"]
                /following-sibling::input[@type="text"][@id="name_second"][@required="required"]
            ]
        /following-sibling::input[@type="hidden"][@id="name__token"]
    ]
    [count(.//input)=3]
'
        );
    }

    public function testSearchInputName()
    {
        $form = $this->factory->createNamedBuilder('full', 'form')
            ->add('name', 'search')
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div
            [
                ./label[@for="full_name"]
                /following-sibling::input[@type="search"][@id="full_name"][@name="full[name]"]
            ]
        /following-sibling::input[@type="hidden"][@id="full__token"]
    ]
    [count(//input)=2]
'
        );
    }

    public function testLabelHasNoId()
    {
        $form = $this->factory->createNamed('name', 'text');
        $html = $this->renderRow($form->createView());

        $this->assertMatchesXpath($html,
'/div
    [
        ./label[@for="name"][not(@id)]
        /following-sibling::input[@id="name"]
    ]
'
        );
    }

    public function testLabelIsNotRenderedWhenSetToFalse()
    {
        $form = $this->factory->createNamed('name', 'text', null, array(
            'label' => false
        ));
        $html = $this->renderRow($form->createView());

        $this->assertMatchesXpath($html,
'/div
    [
        ./input[@id="name"]
    ]
    [count(//label)=0]
'
        );
    }

    /**
     * @dataProvider themeBlockInheritanceProvider
     */
    public function testThemeBlockInheritance($theme)
    {
        $view = $this->factory
            ->createNamed('name', 'email')
            ->createView()
        ;

        $this->setTheme($view, $theme);

        $this->assertMatchesXpath(
            $this->renderWidget($view),
            '/input[@type="email"][@rel="theme"]'
        );
    }

    /**
     * @dataProvider themeInheritanceProvider
     */
    public function testThemeInheritance($parentTheme, $childTheme)
    {
        $child = $this->factory->createNamedBuilder('child', 'form')
            ->add('field', 'text');

        $view = $this->factory->createNamedBuilder('parent', 'form')
            ->add('field', 'text')
            ->add($child)
            ->getForm()
            ->createView()
        ;

        $this->setTheme($view, $parentTheme);
        $this->setTheme($view['child'], $childTheme);

        $this->assertWidgetMatchesXpath($view, array(),
'/div
    [
        ./div
            [
                ./label[.="parent"]
                /following-sibling::input[@type="text"]
            ]
        /following-sibling::div
            [
                ./label[.="child"]
                /following-sibling::div
                    [
                        ./div
                            [
                                ./label[.="child"]
                                /following-sibling::input[@type="text"]
                            ]
                    ]
            ]
        /following-sibling::input[@type="hidden"]
    ]
'
        );
    }

    /**
     * The block "_name_child_label" should be overridden in the theme of the
     * implemented driver.
     */
    public function testCollectionRowWithCustomBlock()
    {
        $collection = array('one', 'two', 'three');
        $form = $this->factory->createNamedBuilder('name', 'collection', $collection)
            ->getForm();

        $this->assertWidgetMatchesXpath($form->createView(), array(),
'/div
    [
        ./div[./label[.="Custom label: [trans]0[/trans]"]]
        /following-sibling::div[./label[.="Custom label: [trans]1[/trans]"]]
        /following-sibling::div[./label[.="Custom label: [trans]2[/trans]"]]
    ]
'
        );
    }

    public function testFormEndWithRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text')
            ->getForm()
            ->createView();

        $this->renderWidget($view['field1']);

        // Rest should only contain field2
        $html = $this->renderEnd($view);

        // Insert the start tag, the end tag should be rendered by the helper
        $this->assertMatchesXpath('<form>' . $html,
'/form
    [
        ./div
            [
                ./label[@for="name_field2"]
                /following-sibling::input[@type="text"][@id="name_field2"]
            ]
        /following-sibling::input
            [@type="hidden"]
            [@id="name__token"]
    ]
'
        );
    }

    public function testFormEndWithoutRest()
    {
        $view = $this->factory->createNamedBuilder('name', 'form')
            ->add('field1', 'text')
            ->add('field2', 'text')
            ->getForm()
            ->createView();

        $this->renderWidget($view['field1']);

        // Rest should only contain field2, but isn't rendered
        $html = $this->renderEnd($view, array('render_rest' => false));

        $this->assertEquals('</form>', $html);
    }

    public function testWidgetContainerAttributes()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('class' => 'foobar', 'data-foo' => 'bar'),
        ));

        $form->add('text', 'text');

        $html = $this->renderWidget($form->createView());

        // compare plain HTML to check the whitespace
        $this->assertContains('<div id="form" class="foobar" data-foo="bar">', $html);
    }

    public function testWidgetContainerAttributeNameRepeatedIfTrue()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('foo' => true),
        ));

        $html = $this->renderWidget($form->createView());

        // foo="foo"
        $this->assertContains('<div id="form" foo="foo">', $html);
    }

    public function testWidgetContainerAttributeHiddenIfFalse()
    {
        $form = $this->factory->createNamed('form', 'form', null, array(
            'attr' => array('foo' => false),
        ));

        $html = $this->renderWidget($form->createView());

        // no foo
        $this->assertContains('<div id="form">', $html);
    }
}
PK+1[k/66Form/Symfony/Component/Form/Tests/AbstractFormTest.phpnu�[���<?php

    /*
    * This file is part of the Symfony package.
    *
    * (c) Fabien Potencier <fabien@symfony.com>
    *
    * For the full copyright and license information, please view the LICENSE
    * file that was distributed with this source code.
    */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\FormBuilder;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

abstract class AbstractFormTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var EventDispatcherInterface
     */
    protected $dispatcher;

    /**
     * @var \Symfony\Component\Form\FormFactoryInterface
     */
    protected $factory;

    /**
     * @var \Symfony\Component\Form\FormInterface
     */
    protected $form;

    protected function setUp()
    {
        // We need an actual dispatcher to use the deprecated
        // bindRequest() method
        $this->dispatcher = new EventDispatcher();
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->form = $this->createForm();
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->factory = null;
        $this->form = null;
    }

    /**
     * @return \Symfony\Component\Form\FormInterface
     */
    abstract protected function createForm();

    /**
     * @param string                   $name
     * @param EventDispatcherInterface $dispatcher
     * @param string                   $dataClass
     * @param array                    $options
     *
     * @return FormBuilder
     */
    protected function getBuilder($name = 'name', EventDispatcherInterface $dispatcher = null, $dataClass = null, array $options = array())
    {
        return new FormBuilder($name, $dataClass, $dispatcher ?: $this->dispatcher, $this->factory, $options);
    }

    /**
     * @param  string $name
     *
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getMockForm($name = 'name')
    {
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $config = $this->getMock('Symfony\Component\Form\FormConfigInterface');

        $form->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($name));
        $form->expects($this->any())
            ->method('getConfig')
            ->will($this->returnValue($config));

        return $form;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getDataTransformer()
    {
        return $this->getMock('Symfony\Component\Form\DataTransformerInterface');
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    protected function getFormValidator()
    {
        return $this->getMock('Symfony\Component\Form\FormValidatorInterface');
    }
}
PK+1[rM�{�{4Form/Symfony/Component/Form/Tests/SimpleFormTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer;
use Symfony\Component\Form\Tests\Fixtures\FixedFilterListener;

class SimpleFormTest_Countable implements \Countable
{
    private $count;

    public function __construct($count)
    {
        $this->count = $count;
    }

    public function count()
    {
        return $this->count;
    }
}

class SimpleFormTest_Traversable implements \IteratorAggregate
{
    private $iterator;

    public function __construct($count)
    {
        $this->iterator = new \ArrayIterator($count > 0 ? array_fill(0, $count, 'Foo') : array());
    }

    public function getIterator()
    {
        return $this->iterator;
    }
}

class SimpleFormTest extends AbstractFormTest
{
    public function testDataIsInitializedToConfiguredValue()
    {
        $model = new FixedDataTransformer(array(
            'default' => 'foo',
        ));
        $view = new FixedDataTransformer(array(
            'foo' => 'bar',
        ));

        $config = new FormConfigBuilder('name', null, $this->dispatcher);
        $config->addViewTransformer($view);
        $config->addModelTransformer($model);
        $config->setData('default');
        $form = new Form($config);

        $this->assertSame('default', $form->getData());
        $this->assertSame('foo', $form->getNormData());
        $this->assertSame('bar', $form->getViewData());
    }

    // https://github.com/symfony/symfony/commit/d4f4038f6daf7cf88ca7c7ab089473cce5ebf7d8#commitcomment-1632879
    public function testDataIsInitializedFromSubmit()
    {
        $mock = $this->getMockBuilder('\stdClass')
            ->setMethods(array('preSetData', 'preSubmit'))
            ->getMock();
        $mock->expects($this->at(0))
            ->method('preSetData');
        $mock->expects($this->at(1))
            ->method('preSubmit');

        $config = new FormConfigBuilder('name', null, $this->dispatcher);
        $config->addEventListener(FormEvents::PRE_SET_DATA, array($mock, 'preSetData'));
        $config->addEventListener(FormEvents::PRE_SUBMIT, array($mock, 'preSubmit'));
        $form = new Form($config);

        // no call to setData() or similar where the object would be
        // initialized otherwise

        $form->submit('foobar');
    }

    // https://github.com/symfony/symfony/pull/7789
    public function testFalseIsConvertedToNull()
    {
        $mock = $this->getMockBuilder('\stdClass')
            ->setMethods(array('preBind'))
            ->getMock();
        $mock->expects($this->once())
            ->method('preBind')
            ->with($this->callback(function ($event) {
                return null === $event->getData();
            }));

        $config = new FormConfigBuilder('name', null, $this->dispatcher);
        $config->addEventListener(FormEvents::PRE_BIND, array($mock, 'preBind'));
        $form = new Form($config);

        $form->bind(false);

        $this->assertTrue($form->isValid());
        $this->assertNull($form->getData());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException
     */
    public function testSubmitThrowsExceptionIfAlreadySubmitted()
    {
        $this->form->submit(array());
        $this->form->submit(array());
    }

    public function testSubmitIsIgnoredIfDisabled()
    {
        $form = $this->getBuilder()
            ->setDisabled(true)
            ->setData('initial')
            ->getForm();

        $form->submit('new');

        $this->assertEquals('initial', $form->getData());
        $this->assertTrue($form->isSubmitted());
    }

    public function testNeverRequiredIfParentNotRequired()
    {
        $parent = $this->getBuilder()->setRequired(false)->getForm();
        $child = $this->getBuilder()->setRequired(true)->getForm();

        $child->setParent($parent);

        $this->assertFalse($child->isRequired());
    }

    public function testRequired()
    {
        $parent = $this->getBuilder()->setRequired(true)->getForm();
        $child = $this->getBuilder()->setRequired(true)->getForm();

        $child->setParent($parent);

        $this->assertTrue($child->isRequired());
    }

    public function testNotRequired()
    {
        $parent = $this->getBuilder()->setRequired(true)->getForm();
        $child = $this->getBuilder()->setRequired(false)->getForm();

        $child->setParent($parent);

        $this->assertFalse($child->isRequired());
    }

    public function testAlwaysDisabledIfParentDisabled()
    {
        $parent = $this->getBuilder()->setDisabled(true)->getForm();
        $child = $this->getBuilder()->setDisabled(false)->getForm();

        $child->setParent($parent);

        $this->assertTrue($child->isDisabled());
    }

    public function testDisabled()
    {
        $parent = $this->getBuilder()->setDisabled(false)->getForm();
        $child = $this->getBuilder()->setDisabled(true)->getForm();

        $child->setParent($parent);

        $this->assertTrue($child->isDisabled());
    }

    public function testNotDisabled()
    {
        $parent = $this->getBuilder()->setDisabled(false)->getForm();
        $child = $this->getBuilder()->setDisabled(false)->getForm();

        $child->setParent($parent);

        $this->assertFalse($child->isDisabled());
    }

    public function testGetRootReturnsRootOfParent()
    {
        $parent = $this->getMockForm();
        $parent->expects($this->once())
            ->method('getRoot')
            ->will($this->returnValue('ROOT'));

        $this->form->setParent($parent);

        $this->assertEquals('ROOT', $this->form->getRoot());
    }

    public function testGetRootReturnsSelfIfNoParent()
    {
        $this->assertSame($this->form, $this->form->getRoot());
    }

    public function testEmptyIfEmptyArray()
    {
        $this->form->setData(array());

        $this->assertTrue($this->form->isEmpty());
    }

    public function testEmptyIfEmptyCountable()
    {
        $this->form = new Form(new FormConfigBuilder('name', __NAMESPACE__.'\SimpleFormTest_Countable', $this->dispatcher));

        $this->form->setData(new SimpleFormTest_Countable(0));

        $this->assertTrue($this->form->isEmpty());
    }

    public function testNotEmptyIfFilledCountable()
    {
        $this->form = new Form(new FormConfigBuilder('name', __NAMESPACE__.'\SimpleFormTest_Countable', $this->dispatcher));

        $this->form->setData(new SimpleFormTest_Countable(1));

        $this->assertFalse($this->form->isEmpty());
    }

    public function testEmptyIfEmptyTraversable()
    {
        $this->form = new Form(new FormConfigBuilder('name', __NAMESPACE__.'\SimpleFormTest_Traversable', $this->dispatcher));

        $this->form->setData(new SimpleFormTest_Traversable(0));

        $this->assertTrue($this->form->isEmpty());
    }

    public function testNotEmptyIfFilledTraversable()
    {
        $this->form = new Form(new FormConfigBuilder('name', __NAMESPACE__.'\SimpleFormTest_Traversable', $this->dispatcher));

        $this->form->setData(new SimpleFormTest_Traversable(1));

        $this->assertFalse($this->form->isEmpty());
    }

    public function testEmptyIfNull()
    {
        $this->form->setData(null);

        $this->assertTrue($this->form->isEmpty());
    }

    public function testEmptyIfEmptyString()
    {
        $this->form->setData('');

        $this->assertTrue($this->form->isEmpty());
    }

    public function testNotEmptyIfText()
    {
        $this->form->setData('foobar');

        $this->assertFalse($this->form->isEmpty());
    }

    public function testValidIfSubmitted()
    {
        $form = $this->getBuilder()->getForm();
        $form->submit('foobar');

        $this->assertTrue($form->isValid());
    }

    public function testValidIfSubmittedAndDisabled()
    {
        $form = $this->getBuilder()->setDisabled(true)->getForm();
        $form->submit('foobar');

        $this->assertTrue($form->isValid());
    }

    public function testNotValidIfNotSubmitted()
    {
        $this->assertFalse($this->form->isValid());
    }

    public function testNotValidIfErrors()
    {
        $form = $this->getBuilder()->getForm();
        $form->submit('foobar');
        $form->addError(new FormError('Error!'));

        $this->assertFalse($form->isValid());
    }

    public function testHasErrors()
    {
        $this->form->addError(new FormError('Error!'));

        $this->assertCount(1, $this->form->getErrors());
    }

    public function testHasNoErrors()
    {
        $this->assertCount(0, $this->form->getErrors());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException
     */
    public function testSetParentThrowsExceptionIfAlreadySubmitted()
    {
        $this->form->submit(array());
        $this->form->setParent($this->getBuilder('parent')->getForm());
    }

    public function testSubmitted()
    {
        $form = $this->getBuilder()->getForm();
        $form->submit('foobar');

        $this->assertTrue($form->isSubmitted());
    }

    public function testNotSubmitted()
    {
        $this->assertFalse($this->form->isSubmitted());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\AlreadySubmittedException
     */
    public function testSetDataThrowsExceptionIfAlreadySubmitted()
    {
        $this->form->submit(array());
        $this->form->setData(null);
    }

    public function testSetDataClonesObjectIfNotByReference()
    {
        $data = new \stdClass();
        $form = $this->getBuilder('name', null, '\stdClass')->setByReference(false)->getForm();
        $form->setData($data);

        $this->assertNotSame($data, $form->getData());
        $this->assertEquals($data, $form->getData());
    }

    public function testSetDataDoesNotCloneObjectIfByReference()
    {
        $data = new \stdClass();
        $form = $this->getBuilder('name', null, '\stdClass')->setByReference(true)->getForm();
        $form->setData($data);

        $this->assertSame($data, $form->getData());
    }

    public function testSetDataExecutesTransformationChain()
    {
        // use real event dispatcher now
        $form = $this->getBuilder('name', new EventDispatcher())
            ->addEventSubscriber(new FixedFilterListener(array(
                'preSetData' => array(
                    'app' => 'filtered',
                ),
            )))
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                'filtered' => 'norm',
            )))
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'norm' => 'client',
            )))
            ->getForm();

        $form->setData('app');

        $this->assertEquals('filtered', $form->getData());
        $this->assertEquals('norm', $form->getNormData());
        $this->assertEquals('client', $form->getViewData());
    }

    public function testSetDataExecutesViewTransformersInOrder()
    {
        $form = $this->getBuilder()
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'first' => 'second',
            )))
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'second' => 'third',
            )))
            ->getForm();

        $form->setData('first');

        $this->assertEquals('third', $form->getViewData());
    }

    public function testSetDataExecutesModelTransformersInReverseOrder()
    {
        $form = $this->getBuilder()
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                'second' => 'third',
            )))
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                'first' => 'second',
            )))
            ->getForm();

        $form->setData('first');

        $this->assertEquals('third', $form->getNormData());
    }

    /*
     * When there is no data transformer, the data must have the same format
     * in all three representations
     */
    public function testSetDataConvertsScalarToStringIfNoTransformer()
    {
        $form = $this->getBuilder()->getForm();

        $form->setData(1);

        $this->assertSame('1', $form->getData());
        $this->assertSame('1', $form->getNormData());
        $this->assertSame('1', $form->getViewData());
    }

    /*
     * Data in client format should, if possible, always be a string to
     * facilitate differentiation between '0' and ''
     */
    public function testSetDataConvertsScalarToStringIfOnlyModelTransformer()
    {
        $form = $this->getBuilder()
            ->addModelTransformer(new FixedDataTransformer(array(
            '' => '',
            1 => 23,
        )))
            ->getForm();

        $form->setData(1);

        $this->assertSame(1, $form->getData());
        $this->assertSame(23, $form->getNormData());
        $this->assertSame('23', $form->getViewData());
    }

    /*
     * NULL remains NULL in app and norm format to remove the need to treat
     * empty values and NULL explicitly in the application
     */
    public function testSetDataConvertsNullToStringIfNoTransformer()
    {
        $form = $this->getBuilder()->getForm();

        $form->setData(null);

        $this->assertNull($form->getData());
        $this->assertNull($form->getNormData());
        $this->assertSame('', $form->getViewData());
    }

    public function testSetDataIsIgnoredIfDataIsLocked()
    {
        $form = $this->getBuilder()
            ->setData('default')
            ->setDataLocked(true)
            ->getForm();

        $form->setData('foobar');

        $this->assertSame('default', $form->getData());
    }

    public function testSubmitConvertsEmptyToNullIfNoTransformer()
    {
        $form = $this->getBuilder()->getForm();

        $form->submit('');

        $this->assertNull($form->getData());
        $this->assertNull($form->getNormData());
        $this->assertSame('', $form->getViewData());
    }

    public function testSubmitExecutesTransformationChain()
    {
        // use real event dispatcher now
        $form = $this->getBuilder('name', new EventDispatcher())
            ->addEventSubscriber(new FixedFilterListener(array(
                'preSubmit' => array(
                    'client' => 'filteredclient',
                ),
                'onSubmit' => array(
                    'norm' => 'filterednorm',
                ),
            )))
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                // direction is reversed!
                'norm' => 'filteredclient',
                'filterednorm' => 'cleanedclient'
            )))
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                // direction is reversed!
                'app' => 'filterednorm',
            )))
            ->getForm();

        $form->submit('client');

        $this->assertEquals('app', $form->getData());
        $this->assertEquals('filterednorm', $form->getNormData());
        $this->assertEquals('cleanedclient', $form->getViewData());
    }

    public function testSubmitExecutesViewTransformersInReverseOrder()
    {
        $form = $this->getBuilder()
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'third' => 'second',
            )))
            ->addViewTransformer(new FixedDataTransformer(array(
                '' => '',
                'second' => 'first',
            )))
            ->getForm();

        $form->submit('first');

        $this->assertEquals('third', $form->getNormData());
    }

    public function testSubmitExecutesModelTransformersInOrder()
    {
        $form = $this->getBuilder()
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                'second' => 'first',
            )))
            ->addModelTransformer(new FixedDataTransformer(array(
                '' => '',
                'third' => 'second',
            )))
            ->getForm();

        $form->submit('first');

        $this->assertEquals('third', $form->getData());
    }

    public function testSynchronizedByDefault()
    {
        $this->assertTrue($this->form->isSynchronized());
    }

    public function testSynchronizedAfterSubmission()
    {
        $this->form->submit('foobar');

        $this->assertTrue($this->form->isSynchronized());
    }

    public function testNotSynchronizedIfViewReverseTransformationFailed()
    {
        $transformer = $this->getDataTransformer();
        $transformer->expects($this->once())
            ->method('reverseTransform')
            ->will($this->throwException(new TransformationFailedException()));

        $form = $this->getBuilder()
            ->addViewTransformer($transformer)
            ->getForm();

        $form->submit('foobar');

        $this->assertFalse($form->isSynchronized());
    }

    public function testNotSynchronizedIfModelReverseTransformationFailed()
    {
        $transformer = $this->getDataTransformer();
        $transformer->expects($this->once())
            ->method('reverseTransform')
            ->will($this->throwException(new TransformationFailedException()));

        $form = $this->getBuilder()
            ->addModelTransformer($transformer)
            ->getForm();

        $form->submit('foobar');

        $this->assertFalse($form->isSynchronized());
    }

    public function testEmptyDataCreatedBeforeTransforming()
    {
        $form = $this->getBuilder()
            ->setEmptyData('foo')
            ->addViewTransformer(new FixedDataTransformer(array(
            '' => '',
            // direction is reversed!
            'bar' => 'foo',
        )))
            ->getForm();

        $form->submit('');

        $this->assertEquals('bar', $form->getData());
    }

    public function testEmptyDataFromClosure()
    {
        $test = $this;
        $form = $this->getBuilder()
            ->setEmptyData(function ($form) use ($test) {
            // the form instance is passed to the closure to allow use
            // of form data when creating the empty value
            $test->assertInstanceOf('Symfony\Component\Form\FormInterface', $form);

            return 'foo';
        })
            ->addViewTransformer(new FixedDataTransformer(array(
            '' => '',
            // direction is reversed!
            'bar' => 'foo',
        )))
            ->getForm();

        $form->submit('');

        $this->assertEquals('bar', $form->getData());
    }

    public function testSubmitResetsErrors()
    {
        $this->form->addError(new FormError('Error!'));
        $this->form->submit('foobar');

        $this->assertSame(array(), $this->form->getErrors());
    }

    public function testCreateView()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $view = $this->getMock('Symfony\Component\Form\FormView');
        $form = $this->getBuilder()->setType($type)->getForm();

        $type->expects($this->once())
            ->method('createView')
            ->with($form)
            ->will($this->returnValue($view));

        $this->assertSame($view, $form->createView());
    }

    public function testCreateViewWithParent()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $view = $this->getMock('Symfony\Component\Form\FormView');
        $parentForm = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $parentView = $this->getMock('Symfony\Component\Form\FormView');
        $form = $this->getBuilder()->setType($type)->getForm();
        $form->setParent($parentForm);

        $parentForm->expects($this->once())
            ->method('createView')
            ->will($this->returnValue($parentView));

        $type->expects($this->once())
            ->method('createView')
            ->with($form, $parentView)
            ->will($this->returnValue($view));

        $this->assertSame($view, $form->createView());
    }

    public function testCreateViewWithExplicitParent()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $view = $this->getMock('Symfony\Component\Form\FormView');
        $parentView = $this->getMock('Symfony\Component\Form\FormView');
        $form = $this->getBuilder()->setType($type)->getForm();

        $type->expects($this->once())
            ->method('createView')
            ->with($form, $parentView)
            ->will($this->returnValue($view));

        $this->assertSame($view, $form->createView($parentView));
    }

    public function testGetErrorsAsString()
    {
        $this->form->addError(new FormError('Error!'));

        $this->assertEquals("ERROR: Error!\n", $this->form->getErrorsAsString());
    }

    public function testFormCanHaveEmptyName()
    {
        $form = $this->getBuilder('')->getForm();

        $this->assertEquals('', $form->getName());
    }

    public function testSetNullParentWorksWithEmptyName()
    {
        $form = $this->getBuilder('')->getForm();
        $form->setParent(null);

        $this->assertNull($form->getParent());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\LogicException
     * @expectedExceptionMessage A form with an empty name cannot have a parent form.
     */
    public function testFormCannotHaveEmptyNameNotInRootLevel()
    {
        $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->add($this->getBuilder(''))
            ->getForm();
    }

    public function testGetPropertyPathReturnsConfiguredPath()
    {
        $form = $this->getBuilder()->setPropertyPath('address.street')->getForm();

        $this->assertEquals(new PropertyPath('address.street'), $form->getPropertyPath());
    }

    // see https://github.com/symfony/symfony/issues/3903
    public function testGetPropertyPathDefaultsToNameIfParentHasDataClass()
    {
        $parent = $this->getBuilder(null, null, 'stdClass')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getBuilder('name')->getForm();
        $parent->add($form);

        $this->assertEquals(new PropertyPath('name'), $form->getPropertyPath());
    }

    // see https://github.com/symfony/symfony/issues/3903
    public function testGetPropertyPathDefaultsToIndexedNameIfParentDataClassIsNull()
    {
        $parent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getBuilder('name')->getForm();
        $parent->add($form);

        $this->assertEquals(new PropertyPath('[name]'), $form->getPropertyPath());
    }

    public function testGetPropertyPathDefaultsToNameIfFirstParentWithoutInheritDataHasDataClass()
    {
        $grandParent = $this->getBuilder(null, null, 'stdClass')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $parent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setInheritData(true)
            ->getForm();
        $form = $this->getBuilder('name')->getForm();
        $grandParent->add($parent);
        $parent->add($form);

        $this->assertEquals(new PropertyPath('name'), $form->getPropertyPath());
    }

    public function testGetPropertyPathDefaultsToIndexedNameIfDataClassOfFirstParentWithoutInheritDataIsNull()
    {
        $grandParent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $parent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setInheritData(true)
            ->getForm();
        $form = $this->getBuilder('name')->getForm();
        $grandParent->add($parent);
        $parent->add($form);

        $this->assertEquals(new PropertyPath('[name]'), $form->getPropertyPath());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\LogicException
     */
    public function testViewDataMustNotBeObjectIfDataClassIsNull()
    {
        $config = new FormConfigBuilder('name', null, $this->dispatcher);
        $config->addViewTransformer(new FixedDataTransformer(array(
            '' => '',
            'foo' => new \stdClass(),
        )));
        $form = new Form($config);

        $form->setData('foo');
    }

    public function testViewDataMayBeArrayAccessIfDataClassIsNull()
    {
        $arrayAccess = $this->getMock('\ArrayAccess');
        $config = new FormConfigBuilder('name', null, $this->dispatcher);
        $config->addViewTransformer(new FixedDataTransformer(array(
            '' => '',
            'foo' => $arrayAccess,
        )));
        $form = new Form($config);

        $form->setData('foo');

        $this->assertSame($arrayAccess, $form->getViewData());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\LogicException
     */
    public function testViewDataMustBeObjectIfDataClassIsSet()
    {
        $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher);
        $config->addViewTransformer(new FixedDataTransformer(array(
            '' => '',
            'foo' => array('bar' => 'baz'),
        )));
        $form = new Form($config);

        $form->setData('foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testSetDataCannotInvokeItself()
    {
        // Cycle detection to prevent endless loops
        $config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher);
        $config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $event->getForm()->setData('bar');
        });
        $form = new Form($config);

        $form->setData('foo');
    }

    public function testSubmittingWrongDataIsIgnored()
    {
        $test = $this;

        $child = $this->getBuilder('child', $this->dispatcher);
        $child->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($test) {
            // child form doesn't receive the wrong data that is submitted on parent
            $test->assertNull($event->getData());
        });

        $parent = $this->getBuilder('parent', new EventDispatcher())
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->add($child)
            ->getForm();

        $parent->submit('not-an-array');
    }

    public function testHandleRequestForwardsToRequestHandler()
    {
        $handler = $this->getMock('Symfony\Component\Form\RequestHandlerInterface');

        $form = $this->getBuilder()
            ->setRequestHandler($handler)
            ->getForm();

        $handler->expects($this->once())
            ->method('handleRequest')
            ->with($this->identicalTo($form), 'REQUEST');

        $this->assertSame($form, $form->handleRequest('REQUEST'));
    }

    public function testFormInheritsParentData()
    {
        $child = $this->getBuilder('child')
            ->setInheritData(true);

        $parent = $this->getBuilder('parent')
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->setData('foo')
            ->addModelTransformer(new FixedDataTransformer(array(
                'foo' => 'norm[foo]',
            )))
            ->addViewTransformer(new FixedDataTransformer(array(
                'norm[foo]' => 'view[foo]',
            )))
            ->add($child)
            ->getForm();

        $this->assertSame('foo', $parent->get('child')->getData());
        $this->assertSame('norm[foo]', $parent->get('child')->getNormData());
        $this->assertSame('view[foo]', $parent->get('child')->getViewData());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testInheritDataDisallowsSetData()
    {
        $form = $this->getBuilder()
            ->setInheritData(true)
            ->getForm();

        $form->setData('foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testGetDataRequiresParentToBeSetIfInheritData()
    {
        $form = $this->getBuilder()
            ->setInheritData(true)
            ->getForm();

        $form->getData();
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testGetNormDataRequiresParentToBeSetIfInheritData()
    {
        $form = $this->getBuilder()
            ->setInheritData(true)
            ->getForm();

        $form->getNormData();
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testGetViewDataRequiresParentToBeSetIfInheritData()
    {
        $form = $this->getBuilder()
            ->setInheritData(true)
            ->getForm();

        $form->getViewData();
    }

    public function testPostSubmitDataIsNullIfInheritData()
    {
        $test = $this;
        $form = $this->getBuilder()
            ->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($test) {
                $test->assertNull($event->getData());
            })
            ->setInheritData(true)
            ->getForm();

        $form->submit('foo');
    }

    public function testSubmitIsNeverFiredIfInheritData()
    {
        $test = $this;
        $form = $this->getBuilder()
            ->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($test) {
                $test->fail('The SUBMIT event should not be fired');
            })
            ->setInheritData(true)
            ->getForm();

        $form->submit('foo');
    }

    public function testInitializeSetsDefaultData()
    {
        $config = $this->getBuilder()->setData('DEFAULT')->getFormConfig();
        $form = $this->getMock('Symfony\Component\Form\Form', array('setData'), array($config));

        $form->expects($this->once())
            ->method('setData')
            ->with($this->identicalTo('DEFAULT'));

        /* @var Form $form */
        $form->initialize();
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testInitializeFailsIfParent()
    {
        $parent = $this->getBuilder()->setRequired(false)->getForm();
        $child = $this->getBuilder()->setRequired(true)->getForm();

        $child->setParent($parent);

        $child->initialize();
    }

    protected function createForm()
    {
        return $this->getBuilder()->getForm();
    }
}
PK,1[ۿt��^Form/Symfony/Component/Form/Tests/Extension/Validator/EventListener/ValidationListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\EventListener;

use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Validator\Constraints\Form;
use Symfony\Component\Form\Extension\Validator\EventListener\ValidationListener;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;

class ValidationListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $factory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $validator;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $violationMapper;

    /**
     * @var ValidationListener
     */
    private $listener;

    private $message;

    private $messageTemplate;

    private $params;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->validator = $this->getMock('Symfony\Component\Validator\ValidatorInterface');
        $this->violationMapper = $this->getMock('Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapperInterface');
        $this->listener = new ValidationListener($this->validator, $this->violationMapper);
        $this->message = 'Message';
        $this->messageTemplate = 'Message template';
        $this->params = array('foo' => 'bar');
    }

    private function getConstraintViolation($code = null)
    {
        return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, null, 'prop.path', null, null, $code);
    }

    private function getBuilder($name = 'name', $propertyPath = null, $dataClass = null)
    {
        $builder = new FormBuilder($name, $dataClass, $this->dispatcher, $this->factory);
        $builder->setPropertyPath(new PropertyPath($propertyPath ?: $name));
        $builder->setAttribute('error_mapping', array());
        $builder->setErrorBubbling(false);
        $builder->setMapped(true);

        return $builder;
    }

    private function getForm($name = 'name', $propertyPath = null, $dataClass = null)
    {
        return $this->getBuilder($name, $propertyPath, $dataClass)->getForm();
    }

    private function getMockForm()
    {
        return $this->getMock('Symfony\Component\Form\Test\FormInterface');
    }

    // More specific mapping tests can be found in ViolationMapperTest
    public function testMapViolation()
    {
        $violation = $this->getConstraintViolation();
        $form = $this->getForm('street');

        $this->validator->expects($this->once())
            ->method('validate')
            ->will($this->returnValue(array($violation)));

        $this->violationMapper->expects($this->once())
            ->method('mapViolation')
            ->with($violation, $form, false);

        $this->listener->validateForm(new FormEvent($form, null));
    }

    public function testMapViolationAllowsNonSyncIfInvalid()
    {
        $violation = $this->getConstraintViolation(Form::ERR_INVALID);
        $form = $this->getForm('street');

        $this->validator->expects($this->once())
            ->method('validate')
            ->will($this->returnValue(array($violation)));

        $this->violationMapper->expects($this->once())
            ->method('mapViolation')
            // pass true now
            ->with($violation, $form, true);

        $this->listener->validateForm(new FormEvent($form, null));
    }

    public function testValidateIgnoresNonRoot()
    {
        $form = $this->getMockForm();
        $form->expects($this->once())
            ->method('isRoot')
            ->will($this->returnValue(false));

        $this->validator->expects($this->never())
            ->method('validate');

        $this->violationMapper->expects($this->never())
            ->method('mapViolation');

        $this->listener->validateForm(new FormEvent($form, null));
    }

    public function testValidateWithEmptyViolationList()
    {
        $form = $this->getMockForm();
        $form->expects($this->once())
            ->method('isRoot')
            ->will($this->returnValue(true));

        $this->validator
            ->expects($this->once())
            ->method('validate')
            ->will($this->returnValue(new ConstraintViolationList()));

        $this->violationMapper
            ->expects($this->never())
            ->method('mapViolation');

        $this->listener->validateForm(new FormEvent($form, null));
    }
}
PK,1[�EY޵�OForm/Symfony/Component/Form/Tests/Extension/Validator/Util/ServerParamsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Util;

class ServerParamsTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getGetPostMaxSizeTestData */
    public function testGetPostMaxSize($size, $bytes)
    {
        $serverParams = $this->getMock('Symfony\Component\Form\Extension\Validator\Util\ServerParams', array('getNormalizedIniPostMaxSize'));
        $serverParams
            ->expects($this->any())
            ->method('getNormalizedIniPostMaxSize')
            ->will($this->returnValue(strtoupper($size)));

        $this->assertEquals($bytes, $serverParams->getPostMaxSize());
    }

    public function getGetPostMaxSizeTestData()
    {
        return array(
            array('2k', 2048),
            array('2 k', 2048),
            array('8m', 8 * 1024 * 1024),
            array('+2 k', 2048),
            array('+2???k', 2048),
            array('0x10', 16),
            array('0xf', 15),
            array('010', 8),
            array('+0x10 k', 16 * 1024),
            array('1g', 1024 * 1024 * 1024),
            array('-1', -1),
            array('0', 0),
            array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
        );
    }
}
PK,1[�l"�	�	RForm/Symfony/Component/Form/Tests/Extension/Validator/ValidatorTypeGuesserTest.phpnu�[���<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Tests\Extension\Validator;

use Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser;
use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Type;

/**
* @author franek <franek@chicour.net>
*/
class ValidatorTypeGuesserTest extends \PHPUnit_Framework_TestCase
{
    private $typeGuesser;

    public function setUp()
    {
        if (!class_exists('Symfony\Component\Validator\Constraint')) {
            $this->markTestSkipped('The "Validator" component is not available');
        }

        $metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');

        $this->typeGuesser = new ValidatorTypeGuesser($metadataFactory);
    }

    public function testGuessMaxLengthForConstraintWithMaxValue()
    {
        $constraint = new Length(array('max' => '2'));

        $result = $this->typeGuesser->guessMaxLengthForConstraint($constraint);
        $this->assertInstanceOf('Symfony\Component\Form\Guess\ValueGuess', $result);
        $this->assertEquals(2, $result->getValue());
        $this->assertEquals(Guess::HIGH_CONFIDENCE, $result->getConfidence());
    }

    public function testGuessMaxLengthForConstraintWithMinValue()
    {
        $constraint = new Length(array('min' => '2'));

        $result = $this->typeGuesser->guessMaxLengthForConstraint($constraint);
        $this->assertNull($result);
    }

    /**
* @dataProvider dataProviderTestGuessMaxLengthForConstraintWithType
*/
    public function testGuessMaxLengthForConstraintWithType($type)
    {
        $constraint = new Type($type);

        $result = $this->typeGuesser->guessMaxLengthForConstraint($constraint);
        $this->assertInstanceOf('Symfony\Component\Form\Guess\ValueGuess', $result);
        $this->assertEquals(null, $result->getValue());
        $this->assertEquals(Guess::MEDIUM_CONFIDENCE, $result->getConfidence());
    }

    public static function dataProviderTestGuessMaxLengthForConstraintWithType()
    {
        return array (
            array('double'),
            array('float'),
            array('numeric'),
            array('real')
        );
    }
}
PK,1[��
bForm/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Constraints;

use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
use Symfony\Component\Form\Test\FormPerformanceTestCase;
use Symfony\Component\Validator\Validation;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormValidatorPerformanceTest extends FormPerformanceTestCase
{
    protected function getExtensions()
    {
        return array(
            new ValidatorExtension(Validation::createValidator()),
        );
    }

    /**
     * findClickedButton() used to have an exponential number of calls
     *
     * @group benchmark
     */
    public function testValidationPerformance()
    {
        $this->setMaxRunningTime(1);

        $builder = $this->factory->createBuilder('form');

        for ($i = 0; $i < 40; ++$i) {
            $builder->add($i, 'form');

            $builder->get($i)
                ->add('a')
                ->add('b')
                ->add('c');
        }

        $form = $builder->getForm();

        $form->submit(null);
    }
}
PK,1[ِ�GbGbWForm/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Constraints;

use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Validator\Constraints\Form;
use Symfony\Component\Form\Extension\Validator\Constraints\FormValidator;
use Symfony\Component\Form\SubmitButtonBuilder;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormValidatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $factory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $serverParams;

    /**
     * @var FormValidator
     */
    private $validator;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->serverParams = $this->getMock(
            'Symfony\Component\Form\Extension\Validator\Util\ServerParams',
            array('getNormalizedIniPostMaxSize', 'getContentLength')
        );
        $this->validator = new FormValidator($this->serverParams);
    }

    public function testValidate()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $options = array('validation_groups' => array('group1', 'group2'));
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testValidateConstraints()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $constraint1 = new NotNull(array('groups' => array('group1', 'group2')));
        $constraint2 = new NotBlank(array('groups' => 'group2'));

        $options = array(
            'validation_groups' => array('group1', 'group2'),
            'constraints' => array($constraint1, $constraint2),
        );
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        // First default constraints
        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        // Then custom constraints
        $context->expects($this->at(2))
            ->method('validateValue')
            ->with($object, $constraint1, 'data', 'group1');
        $context->expects($this->at(3))
            ->method('validateValue')
            ->with($object, $constraint2, 'data', 'group2');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontValidateIfParentWithoutCascadeValidation()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parent = $this->getBuilder('parent', null, array('cascade_validation' => false))
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $options = array('validation_groups' => array('group1', 'group2'));
        $form = $this->getBuilder('name', '\stdClass', $options)->getForm();
        $parent->add($form);

        $form->setData($object);

        $context->expects($this->never())
            ->method('validate');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testValidateConstraintsEvenIfNoCascadeValidation()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $constraint1 = new NotNull(array('groups' => array('group1', 'group2')));
        $constraint2 = new NotBlank(array('groups' => 'group2'));

        $parent = $this->getBuilder('parent', null, array('cascade_validation' => false))
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $options = array(
            'validation_groups' => array('group1', 'group2'),
            'constraints' => array($constraint1, $constraint2),
        );
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();
        $parent->add($form);

        $context->expects($this->at(0))
            ->method('validateValue')
            ->with($object, $constraint1, 'data', 'group1');
        $context->expects($this->at(1))
            ->method('validateValue')
            ->with($object, $constraint2, 'data', 'group2');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontValidateIfNoValidationGroups()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $form = $this->getBuilder('name', '\stdClass', array(
                'validation_groups' => array(),
            ))
            ->setData($object)
            ->getForm();

        $form->setData($object);

        $context->expects($this->never())
            ->method('validate');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontValidateConstraintsIfNoValidationGroups()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $constraint1 = $this->getMock('Symfony\Component\Validator\Constraint');
        $constraint2 = $this->getMock('Symfony\Component\Validator\Constraint');

        $options = array(
            'validation_groups' => array(),
            'constraints' => array($constraint1, $constraint2),
        );
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        // Launch transformer
        $form->submit(array());

        $context->expects($this->never())
            ->method('validate');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontValidateIfNotSynchronized()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $form = $this->getBuilder('name', '\stdClass', array(
                'invalid_message' => 'invalid_message_key',
                // Invalid message parameters must be supported, because the
                // invalid message can be a translation key
                // see https://github.com/symfony/symfony/issues/5144
                'invalid_message_parameters' => array('{{ foo }}' => 'bar'),
            ))
            ->setData($object)
            ->addViewTransformer(new CallbackTransformer(
                function ($data) { return $data; },
                function () { throw new TransformationFailedException(); }
            ))
            ->getForm();

        // Launch transformer
        $form->submit('foo');

        $context->expects($this->never())
            ->method('validate');

        $context->expects($this->once())
            ->method('addViolation')
            ->with(
                'invalid_message_key',
                array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'),
                'foo'
            );
        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testAddInvalidErrorEvenIfNoValidationGroups()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $form = $this->getBuilder('name', '\stdClass', array(
                'invalid_message' => 'invalid_message_key',
                // Invalid message parameters must be supported, because the
                // invalid message can be a translation key
                // see https://github.com/symfony/symfony/issues/5144
                'invalid_message_parameters' => array('{{ foo }}' => 'bar'),
                'validation_groups' => array(),
            ))
            ->setData($object)
            ->addViewTransformer(new CallbackTransformer(
                    function ($data) { return $data; },
                    function () { throw new TransformationFailedException(); }
                ))
            ->getForm();

        // Launch transformer
        $form->submit('foo');

        $context->expects($this->never())
            ->method('validate');

        $context->expects($this->once())
            ->method('addViolation')
            ->with(
                'invalid_message_key',
                array('{{ value }}' => 'foo', '{{ foo }}' => 'bar'),
                'foo'
            );
        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontValidateConstraintsIfNotSynchronized()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $constraint1 = $this->getMock('Symfony\Component\Validator\Constraint');
        $constraint2 = $this->getMock('Symfony\Component\Validator\Constraint');

        $options = array(
            'validation_groups' => array('group1', 'group2'),
            'constraints' => array($constraint1, $constraint2),
        );
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->addViewTransformer(new CallbackTransformer(
                function ($data) { return $data; },
                function () { throw new TransformationFailedException(); }
            ))
            ->getForm();

        // Launch transformer
        $form->submit(array());

        $context->expects($this->never())
            ->method('validate');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    // https://github.com/symfony/symfony/issues/4359
    public function testDontMarkInvalidIfAnyChildIsNotSynchronized()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $failingTransformer = new CallbackTransformer(
            function ($data) { return $data; },
            function () { throw new TransformationFailedException(); }
        );

        $form = $this->getBuilder('name', '\stdClass')
            ->setData($object)
            ->addViewTransformer($failingTransformer)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->add(
                $this->getBuilder('child')
                    ->addViewTransformer($failingTransformer)
            )
            ->getForm();

        // Launch transformer
        $form->submit(array('child' => 'foo'));

        $context->expects($this->never())
            ->method('addViolation');
        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testHandleCallbackValidationGroups()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $options = array('validation_groups' => array($this, 'getValidationGroups'));
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontExecuteFunctionNames()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $options = array('validation_groups' => 'header');
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        $context->expects($this->once())
            ->method('validate')
            ->with($object, 'data', 'header', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testHandleClosureValidationGroups()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $options = array('validation_groups' => function (FormInterface $form) {
            return array('group1', 'group2');
        });
        $form = $this->getBuilder('name', '\stdClass', $options)
            ->setData($object)
            ->getForm();

        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testUseValidationGroupOfClickedButton()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parent = $this->getBuilder('parent', null, array('cascade_validation' => true))
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getForm('name', '\stdClass', array(
            'validation_groups' => 'form_group',
        ));

        $parent->add($form);
        $parent->add($this->getSubmitButton('submit', array(
            'validation_groups' => 'button_group',
        )));

        $parent->submit(array('name' => $object, 'submit' => ''));

        $context->expects($this->once())
            ->method('validate')
            ->with($object, 'data', 'button_group', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontUseValidationGroupOfUnclickedButton()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parent = $this->getBuilder('parent', null, array('cascade_validation' => true))
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getForm('name', '\stdClass', array(
            'validation_groups' => 'form_group',
        ));

        $parent->add($form);
        $parent->add($this->getSubmitButton('submit', array(
            'validation_groups' => 'button_group',
        )));

        $form->setData($object);

        $context->expects($this->once())
            ->method('validate')
            ->with($object, 'data', 'form_group', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testUseInheritedValidationGroup()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parentOptions = array(
            'validation_groups' => 'group',
            'cascade_validation' => true,
        );
        $parent = $this->getBuilder('parent', null, $parentOptions)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getBuilder('name', '\stdClass')->getForm();
        $parent->add($form);

        $form->setData($object);

        $context->expects($this->once())
            ->method('validate')
            ->with($object, 'data', 'group', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testUseInheritedCallbackValidationGroup()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parentOptions = array(
            'validation_groups' => array($this, 'getValidationGroups'),
            'cascade_validation' => true,
        );
        $parent = $this->getBuilder('parent', null, $parentOptions)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getBuilder('name', '\stdClass')->getForm();
        $parent->add($form);

        $form->setData($object);

        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testUseInheritedClosureValidationGroup()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');

        $parentOptions = array(
            'validation_groups' => function (FormInterface $form) {
                return array('group1', 'group2');
            },
            'cascade_validation' => true,
        );
        $parent = $this->getBuilder('parent', null, $parentOptions)
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getBuilder('name', '\stdClass')->getForm();
        $parent->add($form);

        $form->setData($object);

        $context->expects($this->at(0))
            ->method('validate')
            ->with($object, 'data', 'group1', true);
        $context->expects($this->at(1))
            ->method('validate')
            ->with($object, 'data', 'group2', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testAppendPropertyPath()
    {
        $context = $this->getMockExecutionContext();
        $object = $this->getMock('\stdClass');
        $form = $this->getBuilder('name', '\stdClass')
            ->setData($object)
            ->getForm();

        $context->expects($this->once())
            ->method('validate')
            ->with($object, 'data', 'Default', true);

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testDontWalkScalars()
    {
        $context = $this->getMockExecutionContext();

        $form = $this->getBuilder()
            ->setData('scalar')
            ->getForm();

        $context->expects($this->never())
            ->method('validate');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function testViolationIfExtraData()
    {
        $context = $this->getMockExecutionContext();

        $form = $this->getBuilder('parent', null, array('extra_fields_message' => 'Extra!'))
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->add($this->getBuilder('child'))
            ->getForm();

        $form->submit(array('foo' => 'bar'));

        $context->expects($this->once())
            ->method('addViolation')
            ->with(
                'Extra!',
                array('{{ extra_fields }}' => 'foo'),
                array('foo' => 'bar')
            );
        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    /**
     * @dataProvider getPostMaxSizeFixtures
     */
    public function testPostMaxSizeViolation($contentLength, $iniMax, $nbViolation, array $params = array())
    {
        $this->serverParams->expects($this->once())
            ->method('getContentLength')
            ->will($this->returnValue($contentLength));
        $this->serverParams->expects($this->any())
            ->method('getNormalizedIniPostMaxSize')
            ->will($this->returnValue($iniMax));

        $context = $this->getMockExecutionContext();
        $options = array('post_max_size_message' => 'Max {{ max }}!');
        $form = $this->getBuilder('name', null, $options)->getForm();

        for ($i = 0; $i < $nbViolation; ++$i) {
            if (0 === $i && count($params) > 0) {
                $context->expects($this->at($i))
                    ->method('addViolation')
                    ->with($options['post_max_size_message'], $params);
            } else {
                $context->expects($this->at($i))
                    ->method('addViolation');
            }
        }

        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    public function getPostMaxSizeFixtures()
    {
        return array(
            array(pow(1024, 3) + 1, '1G', 1, array('{{ max }}' => '1G')),
            array(pow(1024, 3), '1G', 0),
            array(pow(1024, 2) + 1, '1M', 1, array('{{ max }}' => '1M')),
            array(pow(1024, 2), '1M', 0),
            array(1024 + 1, '1K', 1, array('{{ max }}' => '1K')),
            array(1024, '1K', 0),
            array(null, '1K', 0),
            array(1024, '', 0),
            array(1024, 0, 0),
        );
    }

    public function testNoViolationIfNotRoot()
    {
        $this->serverParams->expects($this->once())
            ->method('getContentLength')
            ->will($this->returnValue(1025));
        $this->serverParams->expects($this->never())
            ->method('getNormalizedIniPostMaxSize');

        $context = $this->getMockExecutionContext();
        $parent = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
        $form = $this->getForm();
        $parent->add($form);

        $context->expects($this->never())
            ->method('addViolation');
        $context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->initialize($context);
        $this->validator->validate($form, new Form());
    }

    /**
     * Access has to be public, as this method is called via callback array
     * in {@link testValidateFormDataCanHandleCallbackValidationGroups()}
     * and {@link testValidateFormDataUsesInheritedCallbackValidationGroup()}
     */
    public function getValidationGroups(FormInterface $form)
    {
        return array('group1', 'group2');
    }

    private function getMockExecutionContext()
    {
        return $this->getMock('Symfony\Component\Validator\ExecutionContextInterface');
    }

    /**
     * @param string $name
     * @param string $dataClass
     * @param array  $options
     *
     * @return FormBuilder
     */
    private function getBuilder($name = 'name', $dataClass = null, array $options = array())
    {
        $options = array_replace(array(
            'constraints' => array(),
            'invalid_message_parameters' => array(),
        ), $options);

        return new FormBuilder($name, $dataClass, $this->dispatcher, $this->factory, $options);
    }

    private function getForm($name = 'name', $dataClass = null, array $options = array())
    {
        return $this->getBuilder($name, $dataClass, $options)->getForm();
    }

    private function getSubmitButton($name = 'name', array $options = array())
    {
        $builder = new SubmitButtonBuilder($name, $options);

        return $builder->getForm();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }
}
PK,1[�$�Ǵ�[Form/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\ViolationMapper;

use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationPath;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ViolationPathTest extends \PHPUnit_Framework_TestCase
{
    public function providePaths()
    {
        return array(
            array('children[address]', array(
                array('address', true, true),
            )),
            array('children[address].children[street]', array(
                array('address', true, true),
                array('street', true, true),
            )),
            array('children[address][street]', array(
                array('address', true, true),
            ), 'children[address]'),
            array('children[address].data', array(
                array('address', true, true),
            ), 'children[address]'),
            array('children[address].data.street', array(
                array('address', true, true),
                array('street', false, false),
            )),
            array('children[address].data[street]', array(
                array('address', true, true),
                array('street', false, true),
            )),
            array('children[address].children[street].data.name', array(
                array('address', true, true),
                array('street', true, true),
                array('name', false, false),
            )),
            array('children[address].children[street].data[name]', array(
                array('address', true, true),
                array('street', true, true),
                array('name', false, true),
            )),
            array('data.address', array(
                array('address', false, false),
            )),
            array('data[address]', array(
                array('address', false, true),
            )),
            array('data.address.street', array(
                array('address', false, false),
                array('street', false, false),
            )),
            array('data[address].street', array(
                array('address', false, true),
                array('street', false, false),
            )),
            array('data.address[street]', array(
                array('address', false, false),
                array('street', false, true),
            )),
            array('data[address][street]', array(
                array('address', false, true),
                array('street', false, true),
            )),
            // A few invalid examples
            array('data', array(), ''),
            array('children', array(), ''),
            array('children.address', array(), ''),
            array('children.address[street]', array(), ''),
        );
    }

    /**
     * @dataProvider providePaths
     */
    public function testCreatePath($string, $entries, $slicedPath = null)
    {
        if (null === $slicedPath) {
            $slicedPath = $string;
        }

        $path = new ViolationPath($string);

        $this->assertSame($slicedPath, $path->__toString());
        $this->assertSame(count($entries), count($path->getElements()));
        $this->assertSame(count($entries), $path->getLength());

        foreach ($entries as $index => $entry) {
            $this->assertEquals($entry[0], $path->getElement($index));
            $this->assertSame($entry[1], $path->mapsForm($index));
            $this->assertSame($entry[2], $path->isIndex($index));
            $this->assertSame(!$entry[2], $path->isProperty($index));
        }
    }

    public function provideParents()
    {
        return array(
            array('children[address]', null),
            array('children[address].children[street]', 'children[address]'),
            array('children[address].data.street', 'children[address]'),
            array('children[address].data[street]', 'children[address]'),
            array('data.address', null),
            array('data.address.street', 'data.address'),
            array('data.address[street]', 'data.address'),
            array('data[address].street', 'data[address]'),
            array('data[address][street]', 'data[address]'),
        );
    }

    /**
     * @dataProvider provideParents
     */
    public function testGetParent($violationPath, $parentPath)
    {
        $path = new ViolationPath($violationPath);
        $parent = $parentPath === null ? null : new ViolationPath($parentPath);

        $this->assertEquals($parent, $path->getParent());
    }

    public function testGetElement()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $this->assertEquals('street', $path->getElement(1));
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetElementDoesNotAcceptInvalidIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->getElement(3);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetElementDoesNotAcceptNegativeIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->getElement(-1);
    }

    public function testIsProperty()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $this->assertFalse($path->isProperty(1));
        $this->assertTrue($path->isProperty(2));
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testIsPropertyDoesNotAcceptInvalidIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->isProperty(3);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testIsPropertyDoesNotAcceptNegativeIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->isProperty(-1);
    }

    public function testIsIndex()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $this->assertTrue($path->isIndex(1));
        $this->assertFalse($path->isIndex(2));
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testIsIndexDoesNotAcceptInvalidIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->isIndex(3);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testIsIndexDoesNotAcceptNegativeIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->isIndex(-1);
    }

    public function testMapsForm()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $this->assertTrue($path->mapsForm(0));
        $this->assertFalse($path->mapsForm(1));
        $this->assertFalse($path->mapsForm(2));
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testMapsFormDoesNotAcceptInvalidIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->mapsForm(3);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testMapsFormDoesNotAcceptNegativeIndices()
    {
        $path = new ViolationPath('children[address].data[street].name');

        $path->mapsForm(-1);
    }
}
PK,1[�@1�,�,]Form/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\ViolationMapper;

use Symfony\Component\Form\Extension\Validator\ViolationMapper\ViolationMapper;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Validator\ConstraintViolation;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ViolationMapperTest extends \PHPUnit_Framework_TestCase
{
    const LEVEL_0 = 0;

    const LEVEL_1 = 1;

    const LEVEL_1B = 2;

    const LEVEL_2 = 3;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var ViolationMapper
     */
    private $mapper;

    /**
     * @var string
     */
    private $message;

    /**
     * @var string
     */
    private $messageTemplate;

    /**
     * @var array
     */
    private $params;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->mapper = new ViolationMapper();
        $this->message = 'Message';
        $this->messageTemplate = 'Message template';
        $this->params = array('foo' => 'bar');
    }

    protected function getForm($name = 'name', $propertyPath = null, $dataClass = null, $errorMapping = array(), $inheritData = false, $synchronized = true)
    {
        $config = new FormConfigBuilder($name, $dataClass, $this->dispatcher, array(
            'error_mapping' => $errorMapping,
        ));
        $config->setMapped(true);
        $config->setInheritData($inheritData);
        $config->setPropertyPath($propertyPath);
        $config->setCompound(true);
        $config->setDataMapper($this->getDataMapper());

        if (!$synchronized) {
            $config->addViewTransformer(new CallbackTransformer(
                function ($normData) { return $normData; },
                function () { throw new TransformationFailedException(); }
            ));
        }

        return new Form($config);
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }

    /**
     * @param $propertyPath
     *
     * @return ConstraintViolation
     */
    protected function getConstraintViolation($propertyPath)
    {
        return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, null, $propertyPath, null);
    }

    /**
     * @return FormError
     */
    protected function getFormError()
    {
        return new FormError($this->message, $this->messageTemplate, $this->params);
    }

    public function testMapToFormInheritingParentDataIfDataDoesNotMatch()
    {
        $violation = $this->getConstraintViolation('children[address].data.foo');
        $parent = $this->getForm('parent');
        $child = $this->getForm('address', 'address', null, array(), true);
        $grandChild = $this->getForm('street');

        $parent->add($child);
        $child->add($grandChild);

        $this->mapper->mapViolation($violation, $parent);

        $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
        $this->assertEquals(array($this->getFormError()), $child->getErrors(), $child->getName().' should have an error, but has none');
        $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
    }

    public function testFollowDotRules()
    {
        $violation = $this->getConstraintViolation('data.foo');
        $parent = $this->getForm('parent', null, null, array(
            'foo' => 'address',
        ));
        $child = $this->getForm('address', null, null, array(
            '.' => 'street',
        ));
        $grandChild = $this->getForm('street', null, null, array(
            '.' => 'name',
        ));
        $grandGrandChild = $this->getForm('name');

        $parent->add($child);
        $child->add($grandChild);
        $grandChild->add($grandGrandChild);

        $this->mapper->mapViolation($violation, $parent);

        $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
        $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
        $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
        $this->assertEquals(array($this->getFormError()), $grandGrandChild->getErrors(), $grandGrandChild->getName().' should have an error, but has none');
    }

    public function testAbortMappingIfNotSynchronized()
    {
        $violation = $this->getConstraintViolation('children[address].data.street');
        $parent = $this->getForm('parent');
        $child = $this->getForm('address', 'address', null, array(), false, false);
        // even though "street" is synchronized, it should not have any errors
        // due to its parent not being synchronized
        $grandChild = $this->getForm('street' , 'street');

        $parent->add($child);
        $child->add($grandChild);

        // submit to invoke the transformer and mark the form unsynchronized
        $parent->submit(array());

        $this->mapper->mapViolation($violation, $parent);

        $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
        $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
        $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
    }

    public function testAbortDotRuleMappingIfNotSynchronized()
    {
        $violation = $this->getConstraintViolation('data.address');
        $parent = $this->getForm('parent');
        $child = $this->getForm('address', 'address', null, array(
            '.' => 'street',
        ), false, false);
        // even though "street" is synchronized, it should not have any errors
        // due to its parent not being synchronized
        $grandChild = $this->getForm('street');

        $parent->add($child);
        $child->add($grandChild);

        // submit to invoke the transformer and mark the form unsynchronized
        $parent->submit(array());

        $this->mapper->mapViolation($violation, $parent);

        $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
        $this->assertCount(0, $child->getErrors(), $child->getName().' should not have an error, but has one');
        $this->assertCount(0, $grandChild->getErrors(), $grandChild->getName().' should not have an error, but has one');
    }

    public function provideDefaultTests()
    {
        // The mapping must be deterministic! If a child has the property path "[street]",
        // "data[street]" should be mapped, but "data.street" should not!
        return array(
            // mapping target, child name, its property path, grand child name, its property path, violation path
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', ''),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data'),

            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'data.person.address.street'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', 'street', 'data.person.address.street.prop'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'data.person.address[street]'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', 'street', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'data.person.address.street'),
            array(self::LEVEL_1, 'address', 'person.address', 'street', '[street]', 'data.person.address.street.prop'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'data.person.address[street]'),
            array(self::LEVEL_2, 'address', 'person.address', 'street', '[street]', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', '[street]', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data.person.address[street].prop'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'data.person[address].street'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', 'street', 'data.person[address].street.prop'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'data.person[address][street]'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', 'street', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', 'street', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data.person.address[street].prop'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'data.person[address].street'),
            array(self::LEVEL_1, 'address', 'person[address]', 'street', '[street]', 'data.person[address].street.prop'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'data.person[address][street]'),
            array(self::LEVEL_2, 'address', 'person[address]', 'street', '[street]', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', 'person[address]', 'street', '[street]', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data.person[address][street].prop'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'data[person].address.street'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', 'street', 'data[person].address.street.prop'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'data[person].address[street]'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', 'street', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', 'street', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data.person[address][street].prop'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'data[person].address.street'),
            array(self::LEVEL_1, 'address', '[person].address', 'street', '[street]', 'data[person].address.street.prop'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'data[person].address[street]'),
            array(self::LEVEL_2, 'address', '[person].address', 'street', '[street]', 'data[person].address[street].prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address].street'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address].street.prop'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address][street]'),
            array(self::LEVEL_0, 'address', '[person].address', 'street', '[street]', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address]'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', 'street', 'data[person].address[street].prop'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'data[person][address].street'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', 'street', 'data[person][address].street.prop'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'data[person][address][street]'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', 'street', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'children[address].data[street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address.street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address.street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address[street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person.address[street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address].street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address].street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address][street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data.person[address][street].prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address.street'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address.street.prop'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address[street]'),
            array(self::LEVEL_0, 'address', '[person][address]', 'street', '[street]', 'data[person].address[street].prop'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'data[person][address].street'),
            array(self::LEVEL_1, 'address', '[person][address]', 'street', '[street]', 'data[person][address].street.prop'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'data[person][address][street]'),
            array(self::LEVEL_2, 'address', '[person][address]', 'street', '[street]', 'data[person][address][street].prop'),

            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].data.office.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data[office][street].prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'data.address.office.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office.street', 'data.address.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address[office][street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office.street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address].office[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office.street', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].data.office.street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'children[address].data[office][street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address.office[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office].street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office].street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office][street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office.street', 'data.address[office][street].prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'data[address].office.street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office.street', 'data[address].office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address].office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address].office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office.street', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data.office.street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].data.office[street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'children[address].data[office][street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address.office.street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'data.address.office[street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'office[street]', 'data.address.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office[street]', 'data.address[office][street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office.street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address].office[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'office[street]', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office.street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office[street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'children[address].data[office][street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address.office[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office].street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office].street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office][street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', 'office[street]', 'data.address[office][street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address].office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address].office.street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'data[address].office[street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', 'office[street]', 'data[address].office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'office[street]', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office]'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].data[office].street'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'children[address].data[office][street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address.office[street].prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'data.address[office].street'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office].street', 'data.address[office].street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address[office][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office].street', 'data.address[office][street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office.street'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address].office[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office].street', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].data[office].street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'children[address].data[office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'children[address].data[office][street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address.office[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office].street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office].street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office][street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office].street', 'data.address[office][street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address].office[street].prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'data[address][office].street'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office].street', 'data[address][office].street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address][office][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office].street', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'children[address].data[office].street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].data[office][street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'children[address].data[office][street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address.office[street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address[office].street'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[office][street]', 'data.address[office].street.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'data.address[office][street]'),
            array(self::LEVEL_2, 'address', 'address', 'street', '[office][street]', 'data.address[office][street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office.street'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address].office[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', '[office][street]', 'data[address][office][street].prop'),

            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data.office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office].street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office][street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'children[address].data[office][street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office.street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office.street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office[street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address.office[street].prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office].street'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office].street.prop'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office][street]'),
            array(self::LEVEL_0, 'address', '[address]', 'street', '[office][street]', 'data.address[office][street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office.street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office.street.prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office[street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address].office[street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address][office].street'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[office][street]', 'data[address][office].street.prop'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'data[address][office][street]'),
            array(self::LEVEL_2, 'address', '[address]', 'street', '[office][street]', 'data[address][office][street].prop'),

            // Edge cases which must not occur
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address][street].prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address][street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', '[street]', 'children[address][street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', 'street', 'children[address][street].prop'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address][street]'),
            array(self::LEVEL_1, 'address', '[address]', 'street', '[street]', 'children[address][street].prop'),

            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].children[address].children[street]'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].children[address].data.street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'children[person].data.address.street'),
            array(self::LEVEL_0, 'address', 'person.address', 'street', 'street', 'data.address.street'),

            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].children[office].children[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].children[office].data.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'children[address].data.street'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'office.street', 'data.address.street'),
        );
    }

    /**
     * @dataProvider provideDefaultTests
     */
    public function testDefaultErrorMapping($target, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
    {
        $violation = $this->getConstraintViolation($violationPath);
        $parent = $this->getForm('parent');
        $child = $this->getForm($childName, $childPath);
        $grandChild = $this->getForm($grandChildName, $grandChildPath);

        $parent->add($child);
        $child->add($grandChild);

        $this->mapper->mapViolation($violation, $parent);

        if (self::LEVEL_0 === $target) {
            $this->assertEquals(array($this->getFormError()), $parent->getErrors(), $parent->getName().' should have an error, but has none');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } elseif (self::LEVEL_1 === $target) {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $child->getErrors(), $childName.' should have an error, but has none');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } else {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $grandChild->getErrors(), $grandChildName.' should have an error, but has none');
        }
    }

    public function provideCustomDataErrorTests()
    {
        return array(
            // mapping target, error mapping, child name, its property path, grand child name, its property path, violation path
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_1, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', 'address', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),

            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street].prop'),

            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),

            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[street].prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].street.prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street]'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][street].prop'),

            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', 'street', 'data[address][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.foo[street].prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo].street.prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street]'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[foo][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data.address[street].prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address].street.prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street]'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', '[address]', 'street', '[street]', 'data[address][street].prop'),

            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),

            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),

            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),

            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),

            array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
            array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),

            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
            array(self::LEVEL_1, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
            array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
            array(self::LEVEL_2, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
            array(self::LEVEL_0, 'foo.bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
            array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
            array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
            array(self::LEVEL_1, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
            array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
            array(self::LEVEL_2, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
            array(self::LEVEL_0, 'foo[bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
            array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
            array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
            array(self::LEVEL_1, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
            array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
            array(self::LEVEL_2, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
            array(self::LEVEL_0, '[foo].bar', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo].bar[street].prop'),
            array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street'),
            array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar].street.prop'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street]'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', 'street', 'data[foo][bar][street].prop'),

            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar.street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo.bar[street].prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar].street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data.foo[bar][street].prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar.street.prop'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street]'),
            array(self::LEVEL_0, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo].bar[street].prop'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street'),
            array(self::LEVEL_1, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar].street.prop'),
            array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street]'),
            array(self::LEVEL_2, '[foo][bar]', 'address', 'address', 'address', 'street', '[street]', 'data[foo][bar][street].prop'),

            array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', 'street', 'data.foo'),
            array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo'),
            array(self::LEVEL_2, 'foo', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.prop'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo]'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].prop'),

            array(self::LEVEL_2, 'foo', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo'),
            array(self::LEVEL_2, 'foo', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.prop'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo]'),
            array(self::LEVEL_2, '[foo]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].prop'),

            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', 'street', 'data[foo][bar].prop'),

            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.bar'),
            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo.bar.prop'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo[bar]'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data.foo[bar].prop'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].bar'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo].bar.prop'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo][bar]'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', 'address', 'street', '[street]', 'data[foo][bar].prop'),

            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.bar'),
            array(self::LEVEL_2, 'foo.bar', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo.bar.prop'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo[bar]'),
            array(self::LEVEL_2, 'foo[bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data.foo[bar].prop'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].bar'),
            array(self::LEVEL_2, '[foo].bar', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo].bar.prop'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo][bar]'),
            array(self::LEVEL_2, '[foo][bar]', 'address.street', 'address', '[address]', 'street', 'street', 'data[foo][bar].prop'),

            // Edge cases
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_2, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_0, 'foo', 'address', 'address', '[address]', 'street', 'street', 'data[foo][street].prop'),

            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo.street.prop'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street]'),
            array(self::LEVEL_0, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data.foo[street].prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street'),
            array(self::LEVEL_2, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo].street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'address', 'address', 'street', 'street', 'data[foo][street].prop'),
        );
    }

    /**
     * @dataProvider provideCustomDataErrorTests
     */
    public function testCustomDataErrorMapping($target, $mapFrom, $mapTo, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
    {
        $violation = $this->getConstraintViolation($violationPath);
        $parent = $this->getForm('parent', null, null, array($mapFrom => $mapTo));
        $child = $this->getForm($childName, $childPath);
        $grandChild = $this->getForm($grandChildName, $grandChildPath);

        $parent->add($child);
        $child->add($grandChild);

        // Add a field mapped to the first element of $mapFrom
        // to try to distract the algorithm
        // Only add it if we expect the error to come up on a different
        // level than LEVEL_0, because in this case the error would
        // (correctly) be mapped to the distraction field
        if ($target !== self::LEVEL_0) {
            $mapFromPath = new PropertyPath($mapFrom);
            $mapFromPrefix = $mapFromPath->isIndex(0)
                ? '['.$mapFromPath->getElement(0).']'
                : $mapFromPath->getElement(0);
            $distraction = $this->getForm('distraction', $mapFromPrefix);

            $parent->add($distraction);
        }

        $this->mapper->mapViolation($violation, $parent);

        if ($target !== self::LEVEL_0) {
            $this->assertCount(0, $distraction->getErrors(), 'distraction should not have an error, but has one');
        }

        if (self::LEVEL_0 === $target) {
            $this->assertEquals(array($this->getFormError()), $parent->getErrors(), $parent->getName().' should have an error, but has none');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } elseif (self::LEVEL_1 === $target) {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $child->getErrors(), $childName.' should have an error, but has none');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } else {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $grandChild->getErrors(), $grandChildName.' should have an error, but has none');
        }
    }

    public function provideCustomFormErrorTests()
    {
        // This case is different than the data errors, because here the
        // left side of the mapping refers to the property path of the actual
        // children. In other words, a child error only works if
        // 1) the error actually maps to an existing child and
        // 2) the property path of that child (relative to the form providing
        //    the mapping) matches the left side of the mapping
        return array(
            // mapping target, map from, map to, child name, its property path, grand child name, its property path, violation path
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),

            // Property path of the erroneous field and mapping must match exactly
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
            array(self::LEVEL_1B, 'foo', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),

            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
            array(self::LEVEL_1B, '[foo]', 'address', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),

            array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data'),
            array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_2, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street'),
            array(self::LEVEL_2, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data.street.prop'),
            array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street]'),
            array(self::LEVEL_1, '[foo]', 'address', 'foo', '[foo]', 'address', 'address', 'street', 'street', 'children[foo].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data.street'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street].prop'),

            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].children[street].data'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data.street'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].children[street].data.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data.street'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo].data[street].prop'),

            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street].data.prop'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street.prop'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'foo', 'address', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street].prop'),

            // Map to a nested child
            array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[foo]'),
            array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[foo]'),
            array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[foo]'),
            array(self::LEVEL_2, 'foo', 'address.street', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[foo]'),

            // Map from a nested child
            array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1B, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, 'address.street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),

            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1B, 'address[street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, 'address[street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),

            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1B, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, '[address].street', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),

            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', 'address', 'street', '[street]', 'children[address].data[street]'),
            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].children[street]'),
            array(self::LEVEL_2, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].children[street]'),
            array(self::LEVEL_1, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data.street'),
            array(self::LEVEL_1B, '[address][street]', 'foo', 'foo', 'foo', 'address', '[address]', 'street', '[street]', 'children[address].data[street]'),
        );
    }

    /**
     * @dataProvider provideCustomFormErrorTests
     */
    public function testCustomFormErrorMapping($target, $mapFrom, $mapTo, $errorName, $errorPath, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
    {
        $violation = $this->getConstraintViolation($violationPath);
        $parent = $this->getForm('parent', null, null, array($mapFrom => $mapTo));
        $child = $this->getForm($childName, $childPath);
        $grandChild = $this->getForm($grandChildName, $grandChildPath);
        $errorChild = $this->getForm($errorName, $errorPath);

        $parent->add($child);
        $parent->add($errorChild);
        $child->add($grandChild);

        $this->mapper->mapViolation($violation, $parent);

        if (self::LEVEL_0 === $target) {
            $this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $parent->getErrors(), $parent->getName().' should have an error, but has none');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } elseif (self::LEVEL_1 === $target) {
            $this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $child->getErrors(), $childName.' should have an error, but has none');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } elseif (self::LEVEL_1B === $target) {
            $this->assertEquals(array($this->getFormError()), $errorChild->getErrors(), $errorName.' should have an error, but has none');
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } else {
            $this->assertCount(0, $errorChild->getErrors(), $errorName.' should not have an error, but has one');
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $grandChild->getErrors(), $grandChildName.' should have an error, but has none');
        }
    }

    public function provideErrorTestsForFormInheritingParentData()
    {
        return array(
            // mapping target, child name, its property path, grand child name, its property path, violation path
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].children[street].data.prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'children[address].data.street.prop'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street]'),
            array(self::LEVEL_1, 'address', 'address', 'street', 'street', 'children[address].data[street].prop'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.street'),
            array(self::LEVEL_2, 'address', 'address', 'street', 'street', 'data.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address.street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address.street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address[street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data.address[street].prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address].street.prop'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street]'),
            array(self::LEVEL_0, 'address', 'address', 'street', 'street', 'data[address][street].prop'),
        );
    }

    /**
     * @dataProvider provideErrorTestsForFormInheritingParentData
     */
    public function testErrorMappingForFormInheritingParentData($target, $childName, $childPath, $grandChildName, $grandChildPath, $violationPath)
    {
        $violation = $this->getConstraintViolation($violationPath);
        $parent = $this->getForm('parent');
        $child = $this->getForm($childName, $childPath, null, array(), true);
        $grandChild = $this->getForm($grandChildName, $grandChildPath);

        $parent->add($child);
        $child->add($grandChild);

        $this->mapper->mapViolation($violation, $parent);

        if (self::LEVEL_0 === $target) {
            $this->assertEquals(array($this->getFormError()), $parent->getErrors(), $parent->getName().' should have an error, but has none');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } elseif (self::LEVEL_1 === $target) {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $child->getErrors(), $childName.' should have an error, but has none');
            $this->assertCount(0, $grandChild->getErrors(), $grandChildName.' should not have an error, but has one');
        } else {
            $this->assertCount(0, $parent->getErrors(), $parent->getName().' should not have an error, but has one');
            $this->assertCount(0, $child->getErrors(), $childName.' should not have an error, but has one');
            $this->assertEquals(array($this->getFormError()), $grandChild->getErrors(), $grandChildName.' should have an error, but has none');
        }
    }
}
PK,1[`f�[��KForm/Symfony/Component/Form/Tests/Extension/Validator/Type/TypeTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Type;

use Symfony\Component\Form\Test\TypeTestCase as BaseTypeTestCase;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;

abstract class TypeTestCase extends BaseTypeTestCase
{
    protected $validator;

    protected function setUp()
    {
        $this->validator = $this->getMock('Symfony\Component\Validator\ValidatorInterface');
        $metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');
        $this->validator->expects($this->once())->method('getMetadataFactory')->will($this->returnValue($metadataFactory));
        $metadata = $this->getMockBuilder('Symfony\Component\Validator\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $metadataFactory->expects($this->once())->method('getMetadataFor')->will($this->returnValue($metadata));

        parent::setUp();
    }

    protected function tearDown()
    {
        $this->validator = null;

        parent::tearDown();
    }

    protected function getExtensions()
    {
        return array_merge(parent::getExtensions(), array(
            new ValidatorExtension($this->validator),
        ));
    }
}
PK,1[Y��
xxYForm/Symfony/Component/Form/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Type;

use Symfony\Component\Form\Test\FormInterface;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class BaseValidatorExtensionTest extends TypeTestCase
{
    public function testValidationGroupNullByDefault()
    {
        $form = $this->createForm();

        $this->assertNull($form->getConfig()->getOption('validation_groups'));
    }

    public function testValidationGroupsTransformedToArray()
    {
        $form = $this->createForm(array(
            'validation_groups' => 'group',
        ));

        $this->assertEquals(array('group'), $form->getConfig()->getOption('validation_groups'));
    }

    public function testValidationGroupsCanBeSetToArray()
    {
        $form = $this->createForm(array(
            'validation_groups' => array('group1', 'group2'),
        ));

        $this->assertEquals(array('group1', 'group2'), $form->getConfig()->getOption('validation_groups'));
    }

    public function testValidationGroupsCanBeSetToFalse()
    {
        $form = $this->createForm(array(
            'validation_groups' => false,
        ));

        $this->assertEquals(array(), $form->getConfig()->getOption('validation_groups'));
    }

    public function testValidationGroupsCanBeSetToCallback()
    {
        $form = $this->createForm(array(
            'validation_groups' => array($this, 'testValidationGroupsCanBeSetToCallback'),
        ));

        $this->assertTrue(is_callable($form->getConfig()->getOption('validation_groups')));
    }

    public function testValidationGroupsCanBeSetToClosure()
    {
        $form = $this->createForm(array(
            'validation_groups' => function (FormInterface $form) { return null; },
        ));

        $this->assertTrue(is_callable($form->getConfig()->getOption('validation_groups')));
    }

    abstract protected function createForm(array $options = array());
}
PK,1[S�m�_Form/Symfony/Component/Form/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Type;

class SubmitTypeValidatorExtensionTest extends BaseValidatorExtensionTest
{
    protected function createForm(array $options = array())
    {
        return $this->factory->create('submit', null, $options);
    }
}
PK,1[7>lˉ�]Form/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Validator\Type;

use Symfony\Component\Validator\ConstraintViolationList;

class FormTypeValidatorExtensionTest extends BaseValidatorExtensionTest
{
    public function testSubmitValidatesData()
    {
        $builder = $this->factory->createBuilder(
            'form',
            null,
            array(
                'validation_groups' => 'group',
            )
        );
        $builder->add('firstName', 'form');
        $form = $builder->getForm();

        $this->validator->expects($this->once())
            ->method('validate')
            ->with($this->equalTo($form))
            ->will($this->returnValue(new ConstraintViolationList()));

        // specific data is irrelevant
        $form->submit(array());
    }

    protected function createForm(array $options = array())
    {
        return $this->factory->create('form', null, $options);
    }
}
PK,1[1���� � dForm/Symfony/Component/Form/Tests/Extension/HttpFoundation/EventListener/BindRequestListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\HttpFoundation\EventListener;

use Symfony\Component\Form\Extension\HttpFoundation\EventListener\BindRequestListener;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Test\DeprecationErrorHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class BindRequestListenerTest extends \PHPUnit_Framework_TestCase
{
    private $values;

    private $filesPlain;

    private $filesNested;

    /**
     * @var UploadedFile
     */
    private $uploadedFile;

    protected function setUp()
    {
        $path = tempnam(sys_get_temp_dir(), 'sf2');
        touch($path);

        $this->values = array(
            'name' => 'Bernhard',
            'image' => array('filename' => 'foobar.png'),
        );

        $this->filesPlain = array(
            'image' => array(
                'error' => UPLOAD_ERR_OK,
                'name' => 'upload.png',
                'size' => 123,
                'tmp_name' => $path,
                'type' => 'image/png'
            ),
        );

        $this->filesNested = array(
            'error' => array('image' => UPLOAD_ERR_OK),
            'name' => array('image' => 'upload.png'),
            'size' => array('image' => 123),
            'tmp_name' => array('image' => $path),
            'type' => array('image' => 'image/png'),
        );

        $this->uploadedFile = new UploadedFile($path, 'upload.png', 'image/png', 123, UPLOAD_ERR_OK);
    }

    protected function tearDown()
    {
        unlink($this->uploadedFile->getRealPath());
    }

    public function requestMethodProvider()
    {
        return array(
            array('POST'),
            array('PUT'),
            array('DELETE'),
            array('PATCH'),
        );
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitRequest($method)
    {
        $values = array('author' => $this->values);
        $files = array('author' => $this->filesNested);
        $request = new Request(array(), $values, array(), array(), $files, array(
            'REQUEST_METHOD' => $method,
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertEquals(array(
            'name' => 'Bernhard',
            'image' => $this->uploadedFile,
        ), $event->getData());
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitRequestWithEmptyName($method)
    {
        $request = new Request(array(), $this->values, array(), array(), $this->filesPlain, array(
            'REQUEST_METHOD' => $method,
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('', null, $dispatcher);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertEquals(array(
            'name' => 'Bernhard',
            'image' => $this->uploadedFile,
        ), $event->getData());
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitEmptyRequestToCompoundForm($method)
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'REQUEST_METHOD' => $method,
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $config->setCompound(true);
        $config->setDataMapper($this->getMock('Symfony\Component\Form\DataMapperInterface'));
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        // Default to empty array
        $this->assertEquals(array(), $event->getData());
    }

    /**
     * @dataProvider requestMethodProvider
     */
    public function testSubmitEmptyRequestToSimpleForm($method)
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'REQUEST_METHOD' => $method,
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $config->setCompound(false);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        // Default to null
        $this->assertNull($event->getData());
    }

    public function testSubmitGetRequest()
    {
        $values = array('author' => $this->values);
        $request = new Request($values, array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertEquals(array(
            'name' => 'Bernhard',
            'image' => array('filename' => 'foobar.png'),
        ), $event->getData());
    }

    public function testSubmitGetRequestWithEmptyName()
    {
        $request = new Request($this->values, array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('', null, $dispatcher);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertEquals(array(
            'name' => 'Bernhard',
            'image' => array('filename' => 'foobar.png'),
        ), $event->getData());
    }

    public function testSubmitEmptyGetRequestToCompoundForm()
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $config->setCompound(true);
        $config->setDataMapper($this->getMock('Symfony\Component\Form\DataMapperInterface'));
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertEquals(array(), $event->getData());
    }

    public function testSubmitEmptyGetRequestToSimpleForm()
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'REQUEST_METHOD' => 'GET',
        ));

        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $config = new FormConfigBuilder('author', null, $dispatcher);
        $config->setCompound(false);
        $form = new Form($config);
        $event = new FormEvent($form, $request);

        $listener = new BindRequestListener();
        DeprecationErrorHandler::preBind($listener, $event);

        $this->assertNull($event->getData());
    }
}
PK,1[f͍ff_Form/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\HttpFoundation;

use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationRequestHandler;
use Symfony\Component\Form\Tests\AbstractRequestHandlerTest;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class HttpFoundationRequestHandlerTest extends AbstractRequestHandlerTest
{
    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testRequestShouldNotBeNull()
    {
        $this->requestHandler->handleRequest($this->getMockForm('name', 'GET'));
    }
    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testRequestShouldBeInstanceOfRequest()
    {
        $this->requestHandler->handleRequest($this->getMockForm('name', 'GET'), new \stdClass());
    }

    protected function setRequestData($method, $data, $files = array())
    {
        $this->request = Request::create('http://localhost', $method, $data, array(), $files);
    }

    protected function getRequestHandler()
    {
        return new HttpFoundationRequestHandler();
    }

    protected function getMockFile()
    {
        return $this->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
            ->disableOriginalConstructor()
            ->getMock();
    }
}
PK,1[%u����YForm/Symfony/Component/Form/Tests/Extension/Csrf/CsrfProvider/SessionCsrfProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Csrf\CsrfProvider;

use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider;

class SessionCsrfProviderTest extends \PHPUnit_Framework_TestCase
{
    protected $provider;
    protected $session;

    protected function setUp()
    {
        $this->session = $this->getMock(
            'Symfony\Component\HttpFoundation\Session\Session',
            array(),
            array(),
            '',
            false // don't call constructor
        );
        $this->provider = new SessionCsrfProvider($this->session, 'SECRET');
    }

    protected function tearDown()
    {
        $this->provider = null;
        $this->session = null;
    }

    public function testGenerateCsrfToken()
    {
        $this->session->expects($this->once())
                ->method('getId')
                ->will($this->returnValue('ABCDEF'));

        $token = $this->provider->generateCsrfToken('foo');

        $this->assertEquals(sha1('SECRET'.'foo'.'ABCDEF'), $token);
    }

    public function testIsCsrfTokenValidSucceeds()
    {
        $this->session->expects($this->once())
                ->method('getId')
                ->will($this->returnValue('ABCDEF'));

        $token = sha1('SECRET'.'foo'.'ABCDEF');

        $this->assertTrue($this->provider->isCsrfTokenValid('foo', $token));
    }

    public function testIsCsrfTokenValidFails()
    {
        $this->session->expects($this->once())
                ->method('getId')
                ->will($this->returnValue('ABCDEF'));

        $token = sha1('SECRET'.'bar'.'ABCDEF');

        $this->assertFalse($this->provider->isCsrfTokenValid('foo', $token));
    }
}
PK,1[_Nn���YForm/Symfony/Component/Form/Tests/Extension/Csrf/CsrfProvider/DefaultCsrfProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Csrf\CsrfProvider;

use Symfony\Component\Form\Extension\Csrf\CsrfProvider\DefaultCsrfProvider;

/**
 * @runTestsInSeparateProcesses
 */
class DefaultCsrfProviderTest extends \PHPUnit_Framework_TestCase
{
    protected $provider;

    public static function setUpBeforeClass()
    {
        ini_set('session.save_handler', 'files');
        ini_set('session.save_path', sys_get_temp_dir());
    }

    protected function setUp()
    {
        $this->provider = new DefaultCsrfProvider('SECRET');
    }

    protected function tearDown()
    {
        $this->provider = null;
    }

    public function testGenerateCsrfToken()
    {
        session_start();

        $token = $this->provider->generateCsrfToken('foo');

        $this->assertEquals(sha1('SECRET'.'foo'.session_id()), $token);
    }

    public function testGenerateCsrfTokenOnUnstartedSession()
    {
        session_id('touti');

        if (!version_compare(PHP_VERSION, '5.4', '>=')) {
            $this->markTestSkipped('This test requires PHP >= 5.4');
        }

        $this->assertSame(PHP_SESSION_NONE, session_status());

        $token = $this->provider->generateCsrfToken('foo');

        $this->assertEquals(sha1('SECRET'.'foo'.session_id()), $token);
        $this->assertSame(PHP_SESSION_ACTIVE, session_status());
    }

    public function testIsCsrfTokenValidSucceeds()
    {
        session_start();

        $token = sha1('SECRET'.'foo'.session_id());

        $this->assertTrue($this->provider->isCsrfTokenValid('foo', $token));
    }

    public function testIsCsrfTokenValidFails()
    {
        session_start();

        $token = sha1('SECRET'.'bar'.session_id());

        $this->assertFalse($this->provider->isCsrfTokenValid('foo', $token));
    }
}
PK,1[�A��]Form/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Csrf\EventListener;

use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Csrf\EventListener\CsrfValidationListener;

class CsrfValidationListenerTest extends \PHPUnit_Framework_TestCase
{
    protected $dispatcher;
    protected $factory;
    protected $tokenManager;
    protected $form;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->tokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $this->form = $this->getBuilder('post')
            ->setDataMapper($this->getDataMapper())
            ->getForm();
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->factory = null;
        $this->tokenManager = null;
        $this->form = null;
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, null, $this->dispatcher, $this->factory, array('compound' => true));
    }

    protected function getForm($name = 'name')
    {
        return $this->getBuilder($name)->getForm();
    }

    protected function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }

    protected function getMockForm()
    {
        return $this->getMock('Symfony\Component\Form\Test\FormInterface');
    }

    // https://github.com/symfony/symfony/pull/5838
    public function testStringFormData()
    {
        $data = "XP4HUzmHPi";
        $event = new FormEvent($this->form, $data);

        $validation = new CsrfValidationListener('csrf', $this->tokenManager, 'unknown', 'Invalid.');
        $validation->preSubmit($event);

        // Validate accordingly
        $this->assertSame($data, $event->getData());
    }
}
PK,1[�L?��.�.SForm/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Csrf\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
use Symfony\Component\Security\Csrf\CsrfToken;

class FormTypeCsrfExtensionTest_ChildType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // The form needs a child in order to trigger CSRF protection by
        // default
        $builder->add('name', 'text');
    }

    public function getName()
    {
        return 'csrf_collection_test';
    }
}

class FormTypeCsrfExtensionTest extends TypeTestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $tokenManager;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $translator;

    protected function setUp()
    {
        $this->tokenManager = $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
        $this->translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');

        parent::setUp();
    }

    protected function tearDown()
    {
        $this->tokenManager = null;
        $this->translator = null;

        parent::tearDown();
    }

    protected function getExtensions()
    {
        return array_merge(parent::getExtensions(), array(
            new CsrfExtension($this->tokenManager, $this->translator),
        ));
    }

    public function testCsrfProtectionByDefaultIfRootAndCompound()
    {
        $view = $this->factory
            ->create('form', null, array(
                'csrf_field_name' => 'csrf',
                'compound' => true,
            ))
            ->createView();

        $this->assertTrue(isset($view['csrf']));
    }

    public function testNoCsrfProtectionByDefaultIfCompoundButNotRoot()
    {
        $view = $this->factory
            ->createNamedBuilder('root', 'form')
            ->add($this->factory
                ->createNamedBuilder('form', 'form', null, array(
                    'csrf_field_name' => 'csrf',
                    'compound' => true,
                ))
            )
            ->getForm()
            ->get('form')
            ->createView();

        $this->assertFalse(isset($view['csrf']));
    }

    public function testNoCsrfProtectionByDefaultIfRootButNotCompound()
    {
        $view = $this->factory
            ->create('form', null, array(
                'csrf_field_name' => 'csrf',
                'compound' => false,
            ))
            ->createView();

        $this->assertFalse(isset($view['csrf']));
    }

    public function testCsrfProtectionCanBeDisabled()
    {
        $view = $this->factory
            ->create('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_protection' => false,
                'compound' => true,
            ))
            ->createView();

        $this->assertFalse(isset($view['csrf']));
    }

    public function testGenerateCsrfToken()
    {
        $this->tokenManager->expects($this->once())
            ->method('getToken')
            ->with('TOKEN_ID')
            ->will($this->returnValue(new CsrfToken('TOKEN_ID', 'token')));

        $view = $this->factory
            ->create('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ))
            ->createView();

        $this->assertEquals('token', $view['csrf']->vars['value']);
    }

    public function testGenerateCsrfTokenUsesFormNameAsIntentionByDefault()
    {
        $this->tokenManager->expects($this->once())
            ->method('getToken')
            ->with('FORM_NAME')
            ->will($this->returnValue('token'));

        $view = $this->factory
            ->createNamed('FORM_NAME', 'form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'compound' => true,
            ))
            ->createView();

        $this->assertEquals('token', $view['csrf']->vars['value']);
    }

    public function testGenerateCsrfTokenUsesTypeClassAsIntentionIfEmptyFormName()
    {
        $this->tokenManager->expects($this->once())
            ->method('getToken')
            ->with('Symfony\Component\Form\Extension\Core\Type\FormType')
            ->will($this->returnValue('token'));

        $view = $this->factory
            ->createNamed('', 'form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'compound' => true,
            ))
            ->createView();

        $this->assertEquals('token', $view['csrf']->vars['value']);
    }

    public function provideBoolean()
    {
        return array(
            array(true),
            array(false),
        );
    }

    /**
     * @dataProvider provideBoolean
     */
    public function testValidateTokenOnSubmitIfRootAndCompound($valid)
    {
        $this->tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->with(new CsrfToken('TOKEN_ID', 'token'))
            ->will($this->returnValue($valid));

        $form = $this->factory
            ->createBuilder('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ))
            ->add('child', 'text')
            ->getForm();

        $form->submit(array(
            'child' => 'foobar',
            'csrf' => 'token',
        ));

        // Remove token from data
        $this->assertSame(array('child' => 'foobar'), $form->getData());

        // Validate accordingly
        $this->assertSame($valid, $form->isValid());
    }

    /**
     * @dataProvider provideBoolean
     */
    public function testValidateTokenOnSubmitIfRootAndCompoundUsesFormNameAsIntentionByDefault($valid)
    {
        $this->tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->with(new CsrfToken('FORM_NAME', 'token'))
            ->will($this->returnValue($valid));

        $form = $this->factory
            ->createNamedBuilder('FORM_NAME', 'form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'compound' => true,
            ))
            ->add('child', 'text')
            ->getForm();

        $form->submit(array(
            'child' => 'foobar',
            'csrf' => 'token',
        ));

        // Remove token from data
        $this->assertSame(array('child' => 'foobar'), $form->getData());

        // Validate accordingly
        $this->assertSame($valid, $form->isValid());
    }

    /**
     * @dataProvider provideBoolean
     */
    public function testValidateTokenOnSubmitIfRootAndCompoundUsesTypeClassAsIntentionIfEmptyFormName($valid)
    {
        $this->tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->with(new CsrfToken('Symfony\Component\Form\Extension\Core\Type\FormType', 'token'))
            ->will($this->returnValue($valid));

        $form = $this->factory
            ->createNamedBuilder('', 'form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'compound' => true,
            ))
            ->add('child', 'text')
            ->getForm();

        $form->submit(array(
            'child' => 'foobar',
            'csrf' => 'token',
        ));

        // Remove token from data
        $this->assertSame(array('child' => 'foobar'), $form->getData());

        // Validate accordingly
        $this->assertSame($valid, $form->isValid());
    }

    public function testFailIfRootAndCompoundAndTokenMissing()
    {
        $this->tokenManager->expects($this->never())
            ->method('isTokenValid');

        $form = $this->factory
            ->createBuilder('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ))
            ->add('child', 'text')
            ->getForm();

        $form->submit(array(
            'child' => 'foobar',
            // token is missing
        ));

        // Remove token from data
        $this->assertSame(array('child' => 'foobar'), $form->getData());

        // Validate accordingly
        $this->assertFalse($form->isValid());
    }

    public function testDontValidateTokenIfCompoundButNoRoot()
    {
        $this->tokenManager->expects($this->never())
            ->method('isTokenValid');

        $form = $this->factory
            ->createNamedBuilder('root', 'form')
            ->add($this->factory
                ->createNamedBuilder('form', 'form', null, array(
                    'csrf_field_name' => 'csrf',
                    'csrf_token_manager' => $this->tokenManager,
                    'csrf_token_id' => 'TOKEN_ID',
                    'compound' => true,
                ))
            )
            ->getForm()
            ->get('form');

        $form->submit(array(
            'child' => 'foobar',
            'csrf' => 'token',
        ));
    }

    public function testDontValidateTokenIfRootButNotCompound()
    {
        $this->tokenManager->expects($this->never())
            ->method('isTokenValid');

        $form = $this->factory
            ->create('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => false,
            ));

        $form->submit(array(
            'csrf' => 'token',
        ));
    }

    public function testNoCsrfProtectionOnPrototype()
    {
        $prototypeView = $this->factory
            ->create('collection', null, array(
                'type' => new FormTypeCsrfExtensionTest_ChildType(),
                'options' => array(
                    'csrf_field_name' => 'csrf',
                ),
                'prototype' => true,
                'allow_add' => true,
            ))
            ->createView()
            ->vars['prototype'];

        $this->assertFalse(isset($prototypeView['csrf']));
        $this->assertCount(1, $prototypeView);
    }

    public function testsTranslateCustomErrorMessage()
    {
        $this->tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->with(new CsrfToken('TOKEN_ID', 'token'))
            ->will($this->returnValue(false));

        $this->translator->expects($this->once())
             ->method('trans')
             ->with('Foobar')
             ->will($this->returnValue('[trans]Foobar[/trans]'));

        $form = $this->factory
            ->createBuilder('form', null, array(
                'csrf_field_name' => 'csrf',
                'csrf_token_manager' => $this->tokenManager,
                'csrf_message' => 'Foobar',
                'csrf_token_id' => 'TOKEN_ID',
                'compound' => true,
            ))
            ->getForm();

        $form->submit(array(
            'csrf' => 'token',
        ));

        $errors = $form->getErrors();

        $this->assertGreaterThan(0, count($errors));
        $this->assertEquals(new FormError('[trans]Foobar[/trans]'), $errors[0]);
    }
}
PK-1[��܏##RForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/Fixtures/randomhashnu�[���GIF87a�������,D;PK-1[��**\Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/FixRadioInputListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\EventListener\FixRadioInputListener;
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;

class FixRadioInputListenerTest extends \PHPUnit_Framework_TestCase
{
    private $choiceList;

    protected function setUp()
    {
        parent::setUp();

        $this->choiceList = new SimpleChoiceList(array('' => 'Empty', 0 => 'A', 1 => 'B'));
    }

    protected function tearDown()
    {
        parent::tearDown();

        $listener = null;
    }

    public function testFixRadio()
    {
        $data = '1';
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $listener = new FixRadioInputListener($this->choiceList, true);
        $listener->preSubmit($event);

        // Indices in SimpleChoiceList are zero-based generated integers
        $this->assertEquals(array(2 => '1'), $event->getData());
    }

    public function testFixZero()
    {
        $data = '0';
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $listener = new FixRadioInputListener($this->choiceList, true);
        $listener->preSubmit($event);

        // Indices in SimpleChoiceList are zero-based generated integers
        $this->assertEquals(array(1 => '0'), $event->getData());
    }

    public function testFixEmptyString()
    {
        $data = '';
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $listener = new FixRadioInputListener($this->choiceList, true);
        $listener->preSubmit($event);

        // Indices in SimpleChoiceList are zero-based generated integers
        $this->assertEquals(array(0 => ''), $event->getData());
    }

    public function testConvertEmptyStringToPlaceholderIfNotFound()
    {
        $list = new SimpleChoiceList(array(0 => 'A', 1 => 'B'));

        $data = '';
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $listener = new FixRadioInputListener($list, true);
        $listener->preSubmit($event);

        $this->assertEquals(array('placeholder' => ''), $event->getData());
    }

    public function testDontConvertEmptyStringToPlaceholderIfNoPlaceholderUsed()
    {
        $list = new SimpleChoiceList(array(0 => 'A', 1 => 'B'));

        $data = '';
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $listener = new FixRadioInputListener($list, false);
        $listener->preSubmit($event);

        $this->assertEquals(array(), $event->getData());
    }
}
PK-1[��!��$�$YForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\Extension\Core\EventListener\ResizeFormListener;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormEvent;

class ResizeFormListenerTest extends \PHPUnit_Framework_TestCase
{
    private $dispatcher;
    private $factory;
    private $form;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->form = $this->getBuilder()
            ->setCompound(true)
            ->setDataMapper($this->getDataMapper())
            ->getForm();
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->factory = null;
        $this->form = null;
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, null, $this->dispatcher, $this->factory);
    }

    protected function getForm($name = 'name')
    {
        return $this->getBuilder($name)->getForm();
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }

    protected function getMockForm()
    {
        return $this->getMock('Symfony\Component\Form\Test\FormInterface');
    }

    public function testPreSetDataResizesForm()
    {
        $this->form->add($this->getForm('0'));
        $this->form->add($this->getForm('1'));

        $this->factory->expects($this->at(0))
            ->method('createNamed')
            ->with(1, 'text', null, array('property_path' => '[1]', 'max_length' => 10, 'auto_initialize' => false))
            ->will($this->returnValue($this->getForm('1')));
        $this->factory->expects($this->at(1))
            ->method('createNamed')
            ->with(2, 'text', null, array('property_path' => '[2]', 'max_length' => 10, 'auto_initialize' => false))
            ->will($this->returnValue($this->getForm('2')));

        $data = array(1 => 'string', 2 => 'string');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array('max_length' => '10'), false, false);
        $listener->preSetData($event);

        $this->assertFalse($this->form->has('0'));
        $this->assertTrue($this->form->has('1'));
        $this->assertTrue($this->form->has('2'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testPreSetDataRequiresArrayOrTraversable()
    {
        $data = 'no array or traversable';
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->preSetData($event);
    }

    public function testPreSetDataDealsWithNullData()
    {
        $this->factory->expects($this->never())->method('createNamed');

        $data = null;
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->preSetData($event);
    }

    public function testPreSubmitResizesUpIfAllowAdd()
    {
        $this->form->add($this->getForm('0'));

        $this->factory->expects($this->once())
            ->method('createNamed')
            ->with(1, 'text', null, array('property_path' => '[1]', 'max_length' => 10, 'auto_initialize' => false))
            ->will($this->returnValue($this->getForm('1')));

        $data = array(0 => 'string', 1 => 'string');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array('max_length' => 10), true, false);
        $listener->preSubmit($event);

        $this->assertTrue($this->form->has('0'));
        $this->assertTrue($this->form->has('1'));
    }

    public function testPreSubmitResizesDownIfAllowDelete()
    {
        $this->form->add($this->getForm('0'));
        $this->form->add($this->getForm('1'));

        $data = array(0 => 'string');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->preSubmit($event);

        $this->assertTrue($this->form->has('0'));
        $this->assertFalse($this->form->has('1'));
    }

    // fix for https://github.com/symfony/symfony/pull/493
    public function testPreSubmitRemovesZeroKeys()
    {
        $this->form->add($this->getForm('0'));

        $data = array();
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->preSubmit($event);

        $this->assertFalse($this->form->has('0'));
    }

    public function testPreSubmitDoesNothingIfNotAllowAddNorAllowDelete()
    {
        $this->form->add($this->getForm('0'));
        $this->form->add($this->getForm('1'));

        $data = array(0 => 'string', 2 => 'string');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->preSubmit($event);

        $this->assertTrue($this->form->has('0'));
        $this->assertTrue($this->form->has('1'));
        $this->assertFalse($this->form->has('2'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testPreSubmitRequiresArrayOrTraversable()
    {
        $data = 'no array or traversable';
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->preSubmit($event);
    }

    public function testPreSubmitDealsWithNullData()
    {
        $this->form->add($this->getForm('1'));

        $data = null;
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->preSubmit($event);

        $this->assertFalse($this->form->has('1'));
    }

    // fixes https://github.com/symfony/symfony/pull/40
    public function testPreSubmitDealsWithEmptyData()
    {
        $this->form->add($this->getForm('1'));

        $data = '';
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->preSubmit($event);

        $this->assertFalse($this->form->has('1'));
    }

    public function testOnSubmitNormDataRemovesEntriesMissingInTheFormIfAllowDelete()
    {
        $this->form->add($this->getForm('1'));

        $data = array(0 => 'first', 1 => 'second', 2 => 'third');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->onSubmit($event);

        $this->assertEquals(array(1 => 'second'), $event->getData());
    }

    public function testOnSubmitNormDataDoesNothingIfNotAllowDelete()
    {
        $this->form->add($this->getForm('1'));

        $data = array(0 => 'first', 1 => 'second', 2 => 'third');
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->onSubmit($event);

        $this->assertEquals($data, $event->getData());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testOnSubmitNormDataRequiresArrayOrTraversable()
    {
        $data = 'no array or traversable';
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, false);
        $listener->onSubmit($event);
    }

    public function testOnSubmitNormDataDealsWithNullData()
    {
        $this->form->add($this->getForm('1'));

        $data = null;
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->onSubmit($event);

        $this->assertEquals(array(), $event->getData());
    }

    public function testOnSubmitDealsWithObjectBackedIteratorAggregate()
    {
        $this->form->add($this->getForm('1'));

        $data = new \ArrayObject(array(0 => 'first', 1 => 'second', 2 => 'third'));
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->onSubmit($event);

        $this->assertArrayNotHasKey(0, $event->getData());
        $this->assertArrayNotHasKey(2, $event->getData());
    }

    public function testOnSubmitDealsWithArrayBackedIteratorAggregate()
    {
        $this->form->add($this->getForm('1'));

        $data = new ArrayCollection(array(0 => 'first', 1 => 'second', 2 => 'third'));
        $event = new FormEvent($this->form, $data);
        $listener = new ResizeFormListener('text', array(), false, true);
        $listener->onSubmit($event);

        $this->assertArrayNotHasKey(0, $event->getData());
        $this->assertArrayNotHasKey(2, $event->getData());
    }
}
PK-1[fk5s3	3	SForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/TrimListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\EventListener\TrimListener;

class TrimListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testTrim()
    {
        $data = " Foo! ";
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new TrimListener();
        $filter->preSubmit($event);

        $this->assertEquals('Foo!', $event->getData());
    }

    public function testTrimSkipNonStrings()
    {
        $data = 1234;
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new TrimListener();
        $filter->preSubmit($event);

        $this->assertSame(1234, $event->getData());
    }

    /**
     * @dataProvider codePointProvider
     */
    public function testTrimUtf8($chars)
    {
        if (!function_exists('mb_check_encoding')) {
            $this->markTestSkipped('The "mb_check_encoding" function is not available');
        }

        $data = mb_convert_encoding(pack('H*', implode('', $chars)), 'UTF-8', 'UCS-2BE');
        $data = $data."ab\ncd".$data;

        $form  = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new TrimListener();
        $filter->preSubmit($event);

        $this->assertSame("ab\ncd", $event->getData(), 'TrimListener should trim character(s): '.implode(', ', $chars));
    }

    public function codePointProvider()
    {
        return array(
            'General category: Separator' => array(array('0020', '00A0', '1680', '180E', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '200A', '2028', '2029', '202F', '205F', '3000')),
            'General category: Other, control' => array(array('0009', '000A', '000B', '000C', '000D', '0085')),
            //'General category: Other, format. ZERO WIDTH SPACE' => array(array('200B')),
        );
    }
}
PK-1[B+�K��iForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormBuilder;

class MergeCollectionListenerArrayObjectTest extends MergeCollectionListenerTest
{
    protected function getData(array $data)
    {
        return new \ArrayObject($data);
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, '\ArrayObject', $this->dispatcher, $this->factory);
    }
}
PK-1[�@ڦoForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\Tests\Fixtures\CustomArrayObject;
use Symfony\Component\Form\FormBuilder;

class MergeCollectionListenerCustomArrayObjectTest extends MergeCollectionListenerTest
{
    protected function getData(array $data)
    {
        return new CustomArrayObject($data);
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, 'Symfony\Component\Form\Tests\Fixtures\CustomArrayObject', $this->dispatcher, $this->factory);
    }
}
PK-1[Э
���cForm/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormBuilder;

class MergeCollectionListenerArrayTest extends MergeCollectionListenerTest
{
    protected function getData(array $data)
    {
        return $data;
    }

    protected function getBuilder($name = 'name')
    {
        return new FormBuilder($name, null, $this->dispatcher, $this->factory);
    }
}
PK-1[��gg]Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/FixUrlProtocolListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\EventListener\FixUrlProtocolListener;

class FixUrlProtocolListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testFixHttpUrl()
    {
        $data = "www.symfony.com";
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new FixUrlProtocolListener('http');
        $filter->onSubmit($event);

        $this->assertEquals('http://www.symfony.com', $event->getData());
    }

    public function testSkipKnownUrl()
    {
        $data = "http://www.symfony.com";
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new FixUrlProtocolListener('http');
        $filter->onSubmit($event);

        $this->assertEquals('http://www.symfony.com', $event->getData());
    }

    public function testSkipOtherProtocol()
    {
        $data = "ftp://www.symfony.com";
        $form = $this->getMock('Symfony\Component\Form\Test\FormInterface');
        $event = new FormEvent($form, $data);

        $filter = new FixUrlProtocolListener('http');
        $filter->onSubmit($event);

        $this->assertEquals('ftp://www.symfony.com', $event->getData());
    }
}
PK-1[�O�&^Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\EventListener;

use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\EventListener\MergeCollectionListener;

abstract class MergeCollectionListenerTest extends \PHPUnit_Framework_TestCase
{
    protected $dispatcher;
    protected $factory;
    protected $form;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->form = $this->getForm('axes');
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->factory = null;
        $this->form = null;
    }

    abstract protected function getBuilder($name = 'name');

    protected function getForm($name = 'name', $propertyPath = null)
    {
        $propertyPath = $propertyPath ?: $name;

        return $this->getBuilder($name)->setAttribute('property_path', $propertyPath)->getForm();
    }

    protected function getMockForm()
    {
        return $this->getMock('Symfony\Component\Form\Test\FormInterface');
    }

    public function getBooleanMatrix1()
    {
        return array(
            array(true),
            array(false),
        );
    }

    public function getBooleanMatrix2()
    {
        return array(
            array(true, true),
            array(true, false),
            array(false, true),
            array(false, false),
        );
    }

    abstract protected function getData(array $data);

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testAddExtraEntriesIfAllowAdd($allowDelete)
    {
        $originalData = $this->getData(array(1 => 'second'));
        $newData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));

        $listener = new MergeCollectionListener(true, $allowDelete);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        // The original object was modified
        if (is_object($originalData)) {
            $this->assertSame($originalData, $event->getData());
        }

        // The original object matches the new object
        $this->assertEquals($newData, $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testAddExtraEntriesIfAllowAddDontOverwriteExistingIndices($allowDelete)
    {
        $originalData = $this->getData(array(1 => 'first'));
        $newData = $this->getData(array(0 => 'first', 1 => 'second'));

        $listener = new MergeCollectionListener(true, $allowDelete);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        // The original object was modified
        if (is_object($originalData)) {
            $this->assertSame($originalData, $event->getData());
        }

        // The original object matches the new object
        $this->assertEquals($this->getData(array(1 => 'first', 2 => 'second')), $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testDoNothingIfNotAllowAdd($allowDelete)
    {
        $originalDataArray = array(1 => 'second');
        $originalData = $this->getData($originalDataArray);
        $newData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));

        $listener = new MergeCollectionListener(false, $allowDelete);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        // We still have the original object
        if (is_object($originalData)) {
            $this->assertSame($originalData, $event->getData());
        }

        // Nothing was removed
        $this->assertEquals($this->getData($originalDataArray), $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testRemoveMissingEntriesIfAllowDelete($allowAdd)
    {
        $originalData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));
        $newData = $this->getData(array(1 => 'second'));

        $listener = new MergeCollectionListener($allowAdd, true);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        // The original object was modified
        if (is_object($originalData)) {
            $this->assertSame($originalData, $event->getData());
        }

        // The original object matches the new object
        $this->assertEquals($newData, $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testDoNothingIfNotAllowDelete($allowAdd)
    {
        $originalDataArray = array(0 => 'first', 1 => 'second', 2 => 'third');
        $originalData = $this->getData($originalDataArray);
        $newData = $this->getData(array(1 => 'second'));

        $listener = new MergeCollectionListener($allowAdd, false);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        // We still have the original object
        if (is_object($originalData)) {
            $this->assertSame($originalData, $event->getData());
        }

        // Nothing was removed
        $this->assertEquals($this->getData($originalDataArray), $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix2
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testRequireArrayOrTraversable($allowAdd, $allowDelete)
    {
        $newData = 'no array or traversable';
        $event = new FormEvent($this->form, $newData);
        $listener = new MergeCollectionListener($allowAdd, $allowDelete);
        $listener->onSubmit($event);
    }

    public function testDealWithNullData()
    {
        $originalData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));
        $newData = null;

        $listener = new MergeCollectionListener(false, false);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        $this->assertSame($originalData, $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testDealWithNullOriginalDataIfAllowAdd($allowDelete)
    {
        $originalData = null;
        $newData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));

        $listener = new MergeCollectionListener(true, $allowDelete);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        $this->assertSame($newData, $event->getData());
    }

    /**
     * @dataProvider getBooleanMatrix1
     */
    public function testDontDealWithNullOriginalDataIfNotAllowAdd($allowDelete)
    {
        $originalData = null;
        $newData = $this->getData(array(0 => 'first', 1 => 'second', 2 => 'third'));

        $listener = new MergeCollectionListener(false, $allowDelete);

        $this->form->setData($originalData);

        $event = new FormEvent($this->form, $newData);
        $listener->onSubmit($event);

        $this->assertNull($event->getData());
    }
}
PK-1[���� � TForm/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/ObjectChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

use Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class ObjectChoiceListTest_EntityWithToString
{
    private $property;

    public function __construct($property)
    {
        $this->property = $property;
    }

    public function __toString()
    {
        return $this->property;
    }
}

class ObjectChoiceListTest extends AbstractChoiceListTest
{
    private $obj1;

    private $obj2;

    private $obj3;

    private $obj4;

    protected function setUp()
    {
        $this->obj1 = (object) array('name' => 'A');
        $this->obj2 = (object) array('name' => 'B');
        $this->obj3 = (object) array('name' => 'C');
        $this->obj4 = (object) array('name' => 'D');

        parent::setUp();
    }

    public function testInitArray()
    {
        $this->list = new ObjectChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4),
            'name',
            array($this->obj2)
        );

        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3'), $this->list->getValues());
        $this->assertEquals(array(1 => new ChoiceView($this->obj2, '1', 'B')), $this->list->getPreferredViews());
        $this->assertEquals(array(0 => new ChoiceView($this->obj1, '0', 'A'), 2 => new ChoiceView($this->obj3, '2', 'C'), 3 => new ChoiceView($this->obj4, '3', 'D')), $this->list->getRemainingViews());
    }

    public function testInitNestedArray()
    {
        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3'), $this->list->getValues());
        $this->assertEquals(array(
            'Group 1' => array(1 => new ChoiceView($this->obj2, '1', 'B')),
            'Group 2' => array(2 => new ChoiceView($this->obj3, '2', 'C'))
        ), $this->list->getPreferredViews());
        $this->assertEquals(array(
            'Group 1' => array(0 => new ChoiceView($this->obj1, '0', 'A')),
            'Group 2' => array(3 => new ChoiceView($this->obj4, '3', 'D'))
        ), $this->list->getRemainingViews());
    }

    public function testInitArrayWithGroupPath()
    {
        $this->obj1 = (object) array('name' => 'A', 'category' => 'Group 1');
        $this->obj2 = (object) array('name' => 'B', 'category' => 'Group 1');
        $this->obj3 = (object) array('name' => 'C', 'category' => 'Group 2');
        $this->obj4 = (object) array('name' => 'D', 'category' => 'Group 2');

        // Objects with NULL groups are not grouped
        $obj5 = (object) array('name' => 'E', 'category' => null);

        // Objects without the group property are not grouped either
        // see https://github.com/symfony/symfony/commit/d9b7abb7c7a0f28e0ce970afc5e305dce5dccddf
        $obj6 = (object) array('name' => 'F');

        $this->list = new ObjectChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4, $obj5, $obj6),
            'name',
            array($this->obj2, $this->obj3),
            'category'
        );

        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4, $obj5, $obj6), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3', '4', '5'), $this->list->getValues());
        $this->assertEquals(array(
            'Group 1' => array(1 => new ChoiceView($this->obj2, '1', 'B')),
            'Group 2' => array(2 => new ChoiceView($this->obj3, '2', 'C'))
        ), $this->list->getPreferredViews());
        $this->assertEquals(array(
            'Group 1' => array(0 => new ChoiceView($this->obj1, '0', 'A')),
            'Group 2' => array(3 => new ChoiceView($this->obj4, '3', 'D')),
            4 => new ChoiceView($obj5, '4', 'E'),
            5 => new ChoiceView($obj6, '5', 'F'),
        ), $this->list->getRemainingViews());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInitArrayWithGroupPathThrowsExceptionIfNestedArray()
    {
        $this->obj1 = (object) array('name' => 'A', 'category' => 'Group 1');
        $this->obj2 = (object) array('name' => 'B', 'category' => 'Group 1');
        $this->obj3 = (object) array('name' => 'C', 'category' => 'Group 2');
        $this->obj4 = (object) array('name' => 'D', 'category' => 'Group 2');

        new ObjectChoiceList(
            array(
                'Group 1' => array($this->obj1, $this->obj2),
                'Group 2' => array($this->obj3, $this->obj4),
            ),
            'name',
            array($this->obj2, $this->obj3),
            'category'
        );
    }

    public function testInitArrayWithValuePath()
    {
        $this->obj1 = (object) array('name' => 'A', 'id' => 10);
        $this->obj2 = (object) array('name' => 'B', 'id' => 20);
        $this->obj3 = (object) array('name' => 'C', 'id' => 30);
        $this->obj4 = (object) array('name' => 'D', 'id' => 40);

        $this->list = new ObjectChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4),
            'name',
            array($this->obj2, $this->obj3),
            null,
            'id'
        );

        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('10', '20', '30', '40'), $this->list->getValues());
        $this->assertEquals(array(1 => new ChoiceView($this->obj2, '20', 'B'), 2 => new ChoiceView($this->obj3, '30', 'C')), $this->list->getPreferredViews());
        $this->assertEquals(array(0 => new ChoiceView($this->obj1, '10', 'A'), 3 => new ChoiceView($this->obj4, '40', 'D')), $this->list->getRemainingViews());
    }

    public function testInitArrayUsesToString()
    {
        $this->obj1 = new ObjectChoiceListTest_EntityWithToString('A');
        $this->obj2 = new ObjectChoiceListTest_EntityWithToString('B');
        $this->obj3 = new ObjectChoiceListTest_EntityWithToString('C');
        $this->obj4 = new ObjectChoiceListTest_EntityWithToString('D');

        $this->list = new ObjectChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4)
        );

        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3'), $this->list->getValues());
        $this->assertEquals(array(0 => new ChoiceView($this->obj1, '0', 'A'), 1 => new ChoiceView($this->obj2, '1', 'B'), 2 => new ChoiceView($this->obj3, '2', 'C'), 3 => new ChoiceView($this->obj4, '3', 'D')), $this->list->getRemainingViews());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\StringCastException
     */
    public function testInitArrayThrowsExceptionIfToStringNotFound()
    {
        $this->obj1 = new ObjectChoiceListTest_EntityWithToString('A');
        $this->obj2 = new ObjectChoiceListTest_EntityWithToString('B');
        $this->obj3 = (object) array('name' => 'C');
        $this->obj4 = new ObjectChoiceListTest_EntityWithToString('D');

        new ObjectChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4)
        );
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        return new ObjectChoiceList(
            array(
                'Group 1' => array($this->obj1, $this->obj2),
                'Group 2' => array($this->obj3, $this->obj4),
            ),
            'name',
            array($this->obj2, $this->obj3)
        );
    }

    protected function getChoices()
    {
        return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK-1[�.�p))NForm/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/ChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class ChoiceListTest extends AbstractChoiceListTest
{
    private $obj1;

    private $obj2;

    private $obj3;

    private $obj4;

    protected function setUp()
    {
        $this->obj1 = new \stdClass();
        $this->obj2 = new \stdClass();
        $this->obj3 = new \stdClass();
        $this->obj4 = new \stdClass();

        parent::setUp();
    }

    public function testInitArray()
    {
        $this->list = new ChoiceList(
            array($this->obj1, $this->obj2, $this->obj3, $this->obj4),
            array('A', 'B', 'C', 'D'),
            array($this->obj2)
        );

        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3'), $this->list->getValues());
        $this->assertEquals(array(1 => new ChoiceView($this->obj2, '1', 'B')), $this->list->getPreferredViews());
        $this->assertEquals(array(0 => new ChoiceView($this->obj1, '0', 'A'), 2 => new ChoiceView($this->obj3, '2', 'C'), 3 => new ChoiceView($this->obj4, '3', 'D')), $this->list->getRemainingViews());
    }

    /**
     * Necessary for interoperability with MongoDB cursors or ORM relations as
     * choices parameter. A choice itself that is an object implementing \Traversable
     * is not treated as hierarchical structure, but as-is.
     */
    public function testInitNestedTraversable()
    {
        $traversableChoice = new \ArrayIterator(array($this->obj3, $this->obj4));

        $this->list = new ChoiceList(
            new \ArrayIterator(array(
                'Group' => array($this->obj1, $this->obj2),
                'Not a Group' => $traversableChoice
            )),
            array(
                'Group' => array('A', 'B'),
                'Not a Group' => 'C',
            ),
            array($this->obj2)
        );

        $this->assertSame(array($this->obj1, $this->obj2, $traversableChoice), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2'), $this->list->getValues());
        $this->assertEquals(array(
            'Group' => array(1 => new ChoiceView($this->obj2, '1', 'B'))
        ), $this->list->getPreferredViews());
        $this->assertEquals(array(
            'Group' => array(0 => new ChoiceView($this->obj1, '0', 'A')),
            2 => new ChoiceView($traversableChoice, '2', 'C')
        ), $this->list->getRemainingViews());
    }

    public function testInitNestedArray()
    {
        $this->assertSame(array($this->obj1, $this->obj2, $this->obj3, $this->obj4), $this->list->getChoices());
        $this->assertSame(array('0', '1', '2', '3'), $this->list->getValues());
        $this->assertEquals(array(
            'Group 1' => array(1 => new ChoiceView($this->obj2, '1', 'B')),
            'Group 2' => array(2 => new ChoiceView($this->obj3, '2', 'C'))
        ), $this->list->getPreferredViews());
        $this->assertEquals(array(
            'Group 1' => array(0 => new ChoiceView($this->obj1, '0', 'A')),
            'Group 2' => array(3 => new ChoiceView($this->obj4, '3', 'D'))
        ), $this->list->getRemainingViews());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInitWithInsufficientLabels()
    {
        $this->list = new ChoiceList(
            array($this->obj1, $this->obj2),
            array('A')
        );
    }

    public function testInitWithLabelsContainingNull()
    {
        $this->list = new ChoiceList(
            array($this->obj1, $this->obj2),
            array('A', null)
        );

        $this->assertEquals(
            array(0 => new ChoiceView($this->obj1, '0', 'A'), 1 => new ChoiceView($this->obj2, '1', null)),
            $this->list->getRemainingViews()
        );
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        return new ChoiceList(
            array(
                'Group 1' => array($this->obj1, $this->obj2),
                'Group 2' => array($this->obj3, $this->obj4),
            ),
            array(
                'Group 1' => array('A', 'B'),
                'Group 2' => array('C', 'D'),
            ),
            array($this->obj2, $this->obj3)
        );
    }

    protected function getChoices()
    {
        return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK-1[�![���VForm/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/AbstractChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractChoiceListTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected $list;

    /**
     * @var array
     */
    protected $choices;

    /**
     * @var array
     */
    protected $values;

    /**
     * @var array
     */
    protected $indices;

    /**
     * @var array
     */
    protected $labels;

    /**
     * @var mixed
     */
    protected $choice1;

    /**
     * @var mixed
     */
    protected $choice2;

    /**
     * @var mixed
     */
    protected $choice3;

    /**
     * @var mixed
     */
    protected $choice4;

    /**
     * @var string
     */
    protected $value1;

    /**
     * @var string
     */
    protected $value2;

    /**
     * @var string
     */
    protected $value3;

    /**
     * @var string
     */
    protected $value4;

    /**
     * @var int|string
     */
    protected $index1;

    /**
     * @var int|string
     */
    protected $index2;

    /**
     * @var int|string
     */
    protected $index3;

    /**
     * @var int|string
     */
    protected $index4;

    /**
     * @var string
     */
    protected $label1;

    /**
     * @var string
     */
    protected $label2;

    /**
     * @var string
     */
    protected $label3;

    /**
     * @var string
     */
    protected $label4;

    protected function setUp()
    {
        parent::setUp();

        $this->list = $this->createChoiceList();

        $this->choices = $this->getChoices();
        $this->indices = $this->getIndices();
        $this->values = $this->getValues();
        $this->labels = $this->getLabels();

        // allow access to the individual entries without relying on their indices
        reset($this->choices);
        reset($this->indices);
        reset($this->values);
        reset($this->labels);

        for ($i = 1; $i <= 4; ++$i) {
            $this->{'choice'.$i} = current($this->choices);
            $this->{'index'.$i} = current($this->indices);
            $this->{'value'.$i} = current($this->values);
            $this->{'label'.$i} = current($this->labels);

            next($this->choices);
            next($this->indices);
            next($this->values);
            next($this->labels);
        }
    }

    public function testGetChoices()
    {
        $this->assertSame($this->choices, $this->list->getChoices());
    }

    public function testGetValues()
    {
        $this->assertSame($this->values, $this->list->getValues());
    }

    public function testGetIndicesForChoices()
    {
        $choices = array($this->choice1, $this->choice2);
        $this->assertSame(array($this->index1, $this->index2), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForChoicesPreservesKeys()
    {
        $choices = array(5 => $this->choice1, 8 => $this->choice2);
        $this->assertSame(array(5 => $this->index1, 8 => $this->index2), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForChoicesPreservesOrder()
    {
        $choices = array($this->choice2, $this->choice1);
        $this->assertSame(array($this->index2, $this->index1), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForChoicesIgnoresNonExistingChoices()
    {
        $choices = array($this->choice1, $this->choice2, 'foobar');
        $this->assertSame(array($this->index1, $this->index2), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForChoicesEmpty()
    {
        $this->assertSame(array(), $this->list->getIndicesForChoices(array()));
    }

    public function testGetIndicesForValues()
    {
        // values and indices are always the same
        $values = array($this->value1, $this->value2);
        $this->assertSame(array($this->index1, $this->index2), $this->list->getIndicesForValues($values));
    }

    public function testGetIndicesForValuesPreservesKeys()
    {
        // values and indices are always the same
        $values = array(5 => $this->value1, 8 => $this->value2);
        $this->assertSame(array(5 => $this->index1, 8 => $this->index2), $this->list->getIndicesForValues($values));
    }

    public function testGetIndicesForValuesPreservesOrder()
    {
        $values = array($this->value2, $this->value1);
        $this->assertSame(array($this->index2, $this->index1), $this->list->getIndicesForValues($values));
    }

    public function testGetIndicesForValuesIgnoresNonExistingValues()
    {
        $values = array($this->value1, $this->value2, 'foobar');
        $this->assertSame(array($this->index1, $this->index2), $this->list->getIndicesForValues($values));
    }

    public function testGetIndicesForValuesEmpty()
    {
        $this->assertSame(array(), $this->list->getIndicesForValues(array()));
    }

    public function testGetChoicesForValues()
    {
        $values = array($this->value1, $this->value2);
        $this->assertSame(array($this->choice1, $this->choice2), $this->list->getChoicesForValues($values));
    }

    public function testGetChoicesForValuesPreservesKeys()
    {
        $values = array(5 => $this->value1, 8 => $this->value2);
        $this->assertSame(array(5 => $this->choice1, 8 => $this->choice2), $this->list->getChoicesForValues($values));
    }

    public function testGetChoicesForValuesPreservesOrder()
    {
        $values = array($this->value2, $this->value1);
        $this->assertSame(array($this->choice2, $this->choice1), $this->list->getChoicesForValues($values));
    }

    public function testGetChoicesForValuesIgnoresNonExistingValues()
    {
        $values = array($this->value1, $this->value2, 'foobar');
        $this->assertSame(array($this->choice1, $this->choice2), $this->list->getChoicesForValues($values));
    }

    // https://github.com/symfony/symfony/issues/3446
    public function testGetChoicesForValuesEmpty()
    {
        $this->assertSame(array(), $this->list->getChoicesForValues(array()));
    }

    public function testGetValuesForChoices()
    {
        $choices = array($this->choice1, $this->choice2);
        $this->assertSame(array($this->value1, $this->value2), $this->list->getValuesForChoices($choices));
    }

    public function testGetValuesForChoicesPreservesKeys()
    {
        $choices = array(5 => $this->choice1, 8 => $this->choice2);
        $this->assertSame(array(5 => $this->value1, 8 => $this->value2), $this->list->getValuesForChoices($choices));
    }

    public function testGetValuesForChoicesPreservesOrder()
    {
        $choices = array($this->choice2, $this->choice1);
        $this->assertSame(array($this->value2, $this->value1), $this->list->getValuesForChoices($choices));
    }

    public function testGetValuesForChoicesIgnoresNonExistingChoices()
    {
        $choices = array($this->choice1, $this->choice2, 'foobar');
        $this->assertSame(array($this->value1, $this->value2), $this->list->getValuesForChoices($choices));
    }

    public function testGetValuesForChoicesEmpty()
    {
        $this->assertSame(array(), $this->list->getValuesForChoices(array()));
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    abstract protected function createChoiceList();

    abstract protected function getChoices();

    abstract protected function getLabels();

    abstract protected function getValues();

    abstract protected function getIndices();
}
PK-1[�gUI��RForm/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/LazyChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
use Symfony\Component\Form\Extension\Core\ChoiceList\LazyChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class LazyChoiceListTest extends \PHPUnit_Framework_TestCase
{
    private $list;

    protected function setUp()
    {
        parent::setUp();

        $this->list = new LazyChoiceListTest_Impl(new SimpleChoiceList(array(
            'a' => 'A',
            'b' => 'B',
            'c' => 'C',
        ), array('b')));
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->list = null;
    }

    public function testGetChoices()
    {
        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c'), $this->list->getChoices());
    }

    public function testGetValues()
    {
        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c'), $this->list->getValues());
    }

    public function testGetPreferredViews()
    {
        $this->assertEquals(array(1 => new ChoiceView('b', 'b', 'B')), $this->list->getPreferredViews());
    }

    public function testGetRemainingViews()
    {
        $this->assertEquals(array(0 => new ChoiceView('a', 'a', 'A'), 2 => new ChoiceView('c', 'c', 'C')), $this->list->getRemainingViews());
    }

    public function testGetIndicesForChoices()
    {
        $choices = array('b', 'c');
        $this->assertSame(array(1, 2), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForValues()
    {
        $values = array('b', 'c');
        $this->assertSame(array(1, 2), $this->list->getIndicesForValues($values));
    }

    public function testGetChoicesForValues()
    {
        $values = array('b', 'c');
        $this->assertSame(array('b', 'c'), $this->list->getChoicesForValues($values));
    }

    public function testGetValuesForChoices()
    {
        $choices = array('b', 'c');
        $this->assertSame(array('b', 'c'), $this->list->getValuesForChoices($choices));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     */
    public function testLoadChoiceListShouldReturnChoiceList()
    {
        $list = new LazyChoiceListTest_InvalidImpl();

        $list->getChoices();
    }
}

class LazyChoiceListTest_Impl extends LazyChoiceList
{
    private $choiceList;

    public function __construct($choiceList)
    {
        $this->choiceList = $choiceList;
    }

    protected function loadChoiceList()
    {
        return $this->choiceList;
    }
}

class LazyChoiceListTest_InvalidImpl extends LazyChoiceList
{
    protected function loadChoiceList()
    {
        return new \stdClass();
    }
}
PK-1[R��
�
TForm/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/SimpleChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class SimpleChoiceListTest extends AbstractChoiceListTest
{
    public function testInitArray()
    {
        $choices = array('a' => 'A', 'b' => 'B', 'c' => 'C');
        $this->list = new SimpleChoiceList($choices, array('b'));

        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c'), $this->list->getChoices());
        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c'), $this->list->getValues());
        $this->assertEquals(array(1 => new ChoiceView('b', 'b', 'B')), $this->list->getPreferredViews());
        $this->assertEquals(array(0 => new ChoiceView('a', 'a', 'A'), 2 => new ChoiceView('c', 'c', 'C')), $this->list->getRemainingViews());
    }

    public function testInitNestedArray()
    {
        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'), $this->list->getChoices());
        $this->assertSame(array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'), $this->list->getValues());
        $this->assertEquals(array(
            'Group 1' => array(1 => new ChoiceView('b', 'b', 'B')),
            'Group 2' => array(2 => new ChoiceView('c', 'c', 'C'))
        ), $this->list->getPreferredViews());
        $this->assertEquals(array(
            'Group 1' => array(0 => new ChoiceView('a', 'a', 'A')),
            'Group 2' => array(3 => new ChoiceView('d', 'd', 'D'))
        ), $this->list->getRemainingViews());
    }

    /**
     * @dataProvider dirtyValuesProvider
     */
    public function testGetValuesForChoicesDealsWithDirtyValues($choice, $value)
    {
        $choices = array(
            '0' => 'Zero',
            '1' => 'One',
            '' => 'Empty',
            '1.23' => 'Float',
            'foo' => 'Foo',
            'foo10' => 'Foo 10',
        );

        $this->list = new SimpleChoiceList($choices, array());

        $this->assertSame(array($value), $this->list->getValuesForChoices(array($choice)));
    }

    public function dirtyValuesProvider()
    {
        return array(
            array(0, '0'),
            array('0', '0'),
            array('1', '1'),
            array(false, '0'),
            array(true, '1'),
            array('', ''),
            array(null, ''),
            array('1.23', '1.23'),
            array('foo', 'foo'),
            array('foo10', 'foo10'),
        );
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        return new SimpleChoiceList(array(
            'Group 1' => array('a' => 'A', 'b' => 'B'),
            'Group 2' => array('c' => 'C', 'd' => 'D'),
        ), array('b', 'c'));
    }

    protected function getChoices()
    {
        return array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK-1[��x��[Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/SimpleNumericChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\ChoiceList;

use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;

class SimpleNumericChoiceListTest extends AbstractChoiceListTest
{
    public function testGetIndicesForChoicesDealsWithNumericChoices()
    {
        // Pass choices as strings although they are integers
        $choices = array('0', '1');
        $this->assertSame(array(0, 1), $this->list->getIndicesForChoices($choices));
    }

    public function testGetIndicesForValuesDealsWithNumericValues()
    {
        // Pass values as strings although they are integers
        $values = array('0', '1');
        $this->assertSame(array(0, 1), $this->list->getIndicesForValues($values));
    }

    public function testGetChoicesForValuesDealsWithNumericValues()
    {
        // Pass values as strings although they are integers
        $values = array('0', '1');
        $this->assertSame(array(0, 1), $this->list->getChoicesForValues($values));
    }

    public function testGetValuesForChoicesDealsWithNumericValues()
    {
        // Pass values as strings although they are integers
        $values = array('0', '1');

        $this->assertSame(array('0', '1'), $this->list->getValuesForChoices($values));
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        return new SimpleChoiceList(array(
            'Group 1' => array(0 => 'A', 1 => 'B'),
            'Group 2' => array(2 => 'C', 3 => 'D'),
        ), array(1, 2));
    }

    protected function getChoices()
    {
        return array(0 => 0, 1 => 1, 2 => 2, 3 => 3);
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK-1[?�R8�.�.VForm/Symfony/Component/Form/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataMapper;

use Symfony\Component\Form\FormConfigBuilder;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;

class PropertyPathMapperTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var PropertyPathMapper
     */
    private $mapper;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $propertyAccessor;

    protected function setUp()
    {
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->propertyAccessor = $this->getMock('Symfony\Component\PropertyAccess\PropertyAccessorInterface');
        $this->mapper = new PropertyPathMapper($this->propertyAccessor);
    }

    /**
     * @param $path
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getPropertyPath($path)
    {
        return $this->getMockBuilder('Symfony\Component\PropertyAccess\PropertyPath')
            ->setConstructorArgs(array($path))
            ->setMethods(array('getValue', 'setValue'))
            ->getMock();
    }

    /**
     * @param FormConfigInterface $config
     * @param Boolean $synchronized
     * @param Boolean $submitted
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getForm(FormConfigInterface $config, $synchronized = true, $submitted = true)
    {
        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
            ->setConstructorArgs(array($config))
            ->setMethods(array('isSynchronized', 'isSubmitted'))
            ->getMock();

        $form->expects($this->any())
            ->method('isSynchronized')
            ->will($this->returnValue($synchronized));

        $form->expects($this->any())
            ->method('isSubmitted')
            ->will($this->returnValue($submitted));

        return $form;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function getDataMapper()
    {
        return $this->getMock('Symfony\Component\Form\DataMapperInterface');
    }

    public function testMapDataToFormsPassesObjectRefIfByReference()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->once())
            ->method('getValue')
            ->with($car, $propertyPath)
            ->will($this->returnValue($engine));

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $form = $this->getForm($config);

        $this->mapper->mapDataToForms($car, array($form));

        // Can't use isIdentical() above because mocks always clone their
        // arguments which can't be disabled in PHPUnit 3.6
        $this->assertSame($engine, $form->getData());
    }

    public function testMapDataToFormsPassesObjectCloneIfNotByReference()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->once())
            ->method('getValue')
            ->with($car, $propertyPath)
            ->will($this->returnValue($engine));

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(false);
        $config->setPropertyPath($propertyPath);
        $form = $this->getForm($config);

        $this->mapper->mapDataToForms($car, array($form));

        $this->assertNotSame($engine, $form->getData());
        $this->assertEquals($engine, $form->getData());
    }

    public function testMapDataToFormsIgnoresEmptyPropertyPath()
    {
        $car = new \stdClass();

        $config = new FormConfigBuilder(null, '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $form = $this->getForm($config);

        $this->assertNull($form->getPropertyPath());

        $this->mapper->mapDataToForms($car, array($form));

        $this->assertNull($form->getData());
    }

    public function testMapDataToFormsIgnoresUnmapped()
    {
        $car = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('getValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setMapped(false);
        $config->setPropertyPath($propertyPath);
        $form = $this->getForm($config);

        $this->mapper->mapDataToForms($car, array($form));

        $this->assertNull($form->getData());
    }

    public function testMapDataToFormsSetsDefaultDataIfPassedDataIsNull()
    {
        $default = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('getValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($default);

        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
            ->setConstructorArgs(array($config))
            ->setMethods(array('setData'))
            ->getMock();

        $form->expects($this->once())
            ->method('setData')
            ->with($default);

        $this->mapper->mapDataToForms(null, array($form));
    }

    public function testMapDataToFormsSetsDefaultDataIfPassedDataIsEmptyArray()
    {
        $default = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('getValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($default);

        $form = $this->getMockBuilder('Symfony\Component\Form\Form')
            ->setConstructorArgs(array($config))
            ->setMethods(array('setData'))
            ->getMock();

        $form->expects($this->once())
            ->method('setData')
            ->with($default);

        $this->mapper->mapDataToForms(array(), array($form));
    }

    public function testMapFormsToDataWritesBackIfNotByReference()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->once())
            ->method('setValue')
            ->with($car, $propertyPath, $engine);

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(false);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataWritesBackIfByReferenceButNoReference()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->once())
            ->method('setValue')
            ->with($car, $propertyPath, $engine);

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataWritesBackIfByReferenceAndReference()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        // $car already contains the reference of $engine
        $this->propertyAccessor->expects($this->once())
            ->method('getValue')
            ->with($car, $propertyPath)
            ->will($this->returnValue($engine));

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataIgnoresUnmapped()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $config->setMapped(false);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataIgnoresUnsubmittedForms()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $form = $this->getForm($config, true, false);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataIgnoresEmptyData()
    {
        $car = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData(null);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataIgnoresUnsynchronized()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $form = $this->getForm($config, false);

        $this->mapper->mapFormsToData(array($form), $car);
    }

    public function testMapFormsToDataIgnoresDisabled()
    {
        $car = new \stdClass();
        $engine = new \stdClass();
        $propertyPath = $this->getPropertyPath('engine');

        $this->propertyAccessor->expects($this->never())
            ->method('setValue');

        $config = new FormConfigBuilder('name', '\stdClass', $this->dispatcher);
        $config->setByReference(true);
        $config->setPropertyPath($propertyPath);
        $config->setData($engine);
        $config->setDisabled(true);
        $form = $this->getForm($config);

        $this->mapper->mapFormsToData(array($form), $car);
    }
}
PK-1[���4��aForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
use Symfony\Component\Form\Extension\Core\DataTransformer\ChoiceToValueTransformer;

class ChoiceToValueTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected $transformer;

    protected function setUp()
    {
        $list = new SimpleChoiceList(array('' => 'A', 0 => 'B', 1 => 'C'));
        $this->transformer = new ChoiceToValueTransformer($list);
    }

    protected function tearDown()
    {
        $this->transformer = null;
    }

    public function transformProvider()
    {
        return array(
            // more extensive test set can be found in FormUtilTest
            array(0, '0'),
            array(false, '0'),
            array('', ''),
        );
    }

    /**
     * @dataProvider transformProvider
     */
    public function testTransform($in, $out)
    {
        $this->assertSame($out, $this->transformer->transform($in));
    }

    public function reverseTransformProvider()
    {
        return array(
            // values are expected to be valid choice keys already and stay
            // the same
            array('0', 0),
            array('', null),
            array(null, null),
        );
    }

    /**
     * @dataProvider reverseTransformProvider
     */
    public function testReverseTransform($in, $out)
    {
        $this->assertSame($out, $this->transformer->reverseTransform($in));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsScalar()
    {
        $this->transformer->reverseTransform(array());
    }
}
PK-1[�����lForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\PercentToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class PercentToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    public function testTransform()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->assertEquals('10', $transformer->transform(0.1));
        $this->assertEquals('15', $transformer->transform(0.15));
        $this->assertEquals('12', $transformer->transform(0.1234));
        $this->assertEquals('200', $transformer->transform(2));
    }

    public function testTransformEmpty()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->assertEquals('', $transformer->transform(null));
    }

    public function testTransformWithInteger()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, 'integer');

        $this->assertEquals('0', $transformer->transform(0.1));
        $this->assertEquals('1', $transformer->transform(1));
        $this->assertEquals('15', $transformer->transform(15));
        $this->assertEquals('16', $transformer->transform(15.9));
    }

    public function testTransformWithPrecision()
    {
        $transformer = new PercentToLocalizedStringTransformer(2);

        $this->assertEquals('12,34', $transformer->transform(0.1234));
    }

    public function testReverseTransform()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->assertEquals(0.1, $transformer->reverseTransform('10'));
        $this->assertEquals(0.15, $transformer->reverseTransform('15'));
        $this->assertEquals(0.12, $transformer->reverseTransform('12'));
        $this->assertEquals(2, $transformer->reverseTransform('200'));
    }

    public function testReverseTransformEmpty()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->assertNull($transformer->reverseTransform(''));
    }

    public function testReverseTransformWithInteger()
    {
        $transformer = new PercentToLocalizedStringTransformer(null, 'integer');

        $this->assertEquals(10, $transformer->reverseTransform('10'));
        $this->assertEquals(15, $transformer->reverseTransform('15'));
        $this->assertEquals(12, $transformer->reverseTransform('12'));
        $this->assertEquals(200, $transformer->reverseTransform('200'));
    }

    public function testReverseTransformWithPrecision()
    {
        $transformer = new PercentToLocalizedStringTransformer(2);

        $this->assertEquals(0.1234, $transformer->reverseTransform('12,34'));
    }

    public function testTransformExpectsNumeric()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->transform('foo');
    }

    public function testReverseTransformExpectsString()
    {
        $transformer = new PercentToLocalizedStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->reverseTransform(1);
    }
}
PK-1[Ws�**mForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class DateTimeToLocalizedStringTransformerTest extends DateTimeTestCase
{
    protected $dateTime;
    protected $dateTimeWithoutSeconds;

    protected function setUp()
    {
        parent::setUp();

        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');

        $this->dateTime = new \DateTime('2010-02-03 04:05:06 UTC');
        $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC');
    }

    protected function tearDown()
    {
        $this->dateTime = null;
        $this->dateTimeWithoutSeconds = null;
    }

    public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false)
    {
        if ($expected instanceof \DateTime && $actual instanceof \DateTime) {
            $expected = $expected->format('c');
            $actual = $actual->format('c');
        }

        parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
    }

    public function dataProvider()
    {
        return array(
            array(\IntlDateFormatter::SHORT, null, null, '03.02.10 04:05', '2010-02-03 04:05:00 UTC'),
            array(\IntlDateFormatter::MEDIUM, null, null, '03.02.2010 04:05', '2010-02-03 04:05:00 UTC'),
            array(\IntlDateFormatter::LONG, null, null, '03. Februar 2010 04:05', '2010-02-03 04:05:00 UTC'),
            array(\IntlDateFormatter::FULL, null, null, 'Mittwoch, 03. Februar 2010 04:05', '2010-02-03 04:05:00 UTC'),
            array(\IntlDateFormatter::SHORT, \IntlDateFormatter::NONE, null, '03.02.10', '2010-02-03 00:00:00 UTC'),
            array(\IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE, null, '03.02.2010', '2010-02-03 00:00:00 UTC'),
            array(\IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, '03. Februar 2010', '2010-02-03 00:00:00 UTC'),
            array(\IntlDateFormatter::FULL, \IntlDateFormatter::NONE, null, 'Mittwoch, 03. Februar 2010', '2010-02-03 00:00:00 UTC'),
            array(null, \IntlDateFormatter::SHORT, null, '03.02.2010 04:05', '2010-02-03 04:05:00 UTC'),
            array(null, \IntlDateFormatter::MEDIUM, null, '03.02.2010 04:05:06', '2010-02-03 04:05:06 UTC'),
            array(null, \IntlDateFormatter::LONG, null, '03.02.2010 04:05:06 GMT', '2010-02-03 04:05:06 UTC'),
            // see below for extra test case for time format FULL
            array(\IntlDateFormatter::NONE, \IntlDateFormatter::SHORT, null, '04:05', '1970-01-01 04:05:00 UTC'),
            array(\IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM, null, '04:05:06', '1970-01-01 04:05:06 UTC'),
            array(\IntlDateFormatter::NONE, \IntlDateFormatter::LONG, null, '04:05:06 GMT', '1970-01-01 04:05:06 UTC'),
            array(null, null, 'yyyy-MM-dd HH:mm:00', '2010-02-03 04:05:00', '2010-02-03 04:05:00 UTC'),
            array(null, null, 'yyyy-MM-dd HH:mm', '2010-02-03 04:05', '2010-02-03 04:05:00 UTC'),
            array(null, null, 'yyyy-MM-dd HH', '2010-02-03 04', '2010-02-03 04:00:00 UTC'),
            array(null, null, 'yyyy-MM-dd', '2010-02-03', '2010-02-03 00:00:00 UTC'),
            array(null, null, 'yyyy-MM', '2010-02', '2010-02-01 00:00:00 UTC'),
            array(null, null, 'yyyy', '2010', '2010-01-01 00:00:00 UTC'),
            array(null, null, 'dd-MM-yyyy', '03-02-2010', '2010-02-03 00:00:00 UTC'),
            array(null, null, 'HH:mm:ss', '04:05:06', '1970-01-01 04:05:06 UTC'),
            array(null, null, 'HH:mm:00', '04:05:00', '1970-01-01 04:05:00 UTC'),
            array(null, null, 'HH:mm', '04:05', '1970-01-01 04:05:00 UTC'),
            array(null, null, 'HH', '04', '1970-01-01 04:00:00 UTC'),
        );
    }

    /**
     * @dataProvider dataProvider
     */
    public function testTransform($dateFormat, $timeFormat, $pattern, $output, $input)
    {
        $transformer = new DateTimeToLocalizedStringTransformer(
            'UTC',
            'UTC',
            $dateFormat,
            $timeFormat,
            \IntlDateFormatter::GREGORIAN,
            $pattern
        );

        $input = new \DateTime($input);

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformFullTime()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, \IntlDateFormatter::FULL);

        $this->assertEquals('03.02.2010 04:05:06 GMT', $transformer->transform($this->dateTime));
    }

    public function testTransformToDifferentLocale()
    {
        \Locale::setDefault('en_US');

        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC');

        $this->assertEquals('Feb 3, 2010, 4:05 AM', $transformer->transform($this->dateTime));
    }

    public function testTransformEmpty()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();

        $this->assertSame('', $transformer->transform(null));
    }

    public function testTransformWithDifferentTimezones()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('America/New_York', 'Asia/Hong_Kong');

        $input = new \DateTime('2010-02-03 04:05:06 America/New_York');

        $dateTime = clone $input;
        $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertEquals($dateTime->format('d.m.Y H:i'), $transformer->transform($input));
    }

    public function testTransformWithDifferentPatterns()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, \IntlDateFormatter::GREGORIAN, 'MM*yyyy*dd HH|mm|ss');

        $this->assertEquals('02*2010*03 04|05|06', $transformer->transform($this->dateTime));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformRequiresValidDateTime()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();
        $transformer->transform('2010-01-01');
    }

    public function testTransformWrapsIntlErrors()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();

        // HOW TO REPRODUCE?

        //$this->setExpectedException('Symfony\Component\Form\Extension\Core\DataTransformer\Transdate_formationFailedException');

        //$transformer->transform(1.5);
    }

    /**
     * @dataProvider dataProvider
     */
    public function testReverseTransform($dateFormat, $timeFormat, $pattern, $input, $output)
    {
        $transformer = new DateTimeToLocalizedStringTransformer(
            'UTC',
            'UTC',
            $dateFormat,
            $timeFormat,
            \IntlDateFormatter::GREGORIAN,
            $pattern
        );

        $output = new \DateTime($output);

        $this->assertEquals($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformFullTime()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', null, \IntlDateFormatter::FULL);

        $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('03.02.2010 04:05:06 GMT+00:00'));
    }

    public function testReverseTransformFromDifferentLocale()
    {
        \Locale::setDefault('en_US');

        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC');

        $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('Feb 3, 2010, 04:05 AM'));
    }

    public function testReverseTransformWithDifferentTimezones()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('America/New_York', 'Asia/Hong_Kong');

        $dateTime = new \DateTime('2010-02-03 04:05:00 Asia/Hong_Kong');
        $dateTime->setTimezone(new \DateTimeZone('America/New_York'));

        $this->assertDateTimeEquals($dateTime, $transformer->reverseTransform('03.02.2010 04:05'));
    }

    public function testReverseTransformWithDifferentPatterns()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, \IntlDateFormatter::GREGORIAN, 'MM*yyyy*dd HH|mm|ss');

        $this->assertDateTimeEquals($this->dateTime, $transformer->reverseTransform('02*2010*03 04|05|06'));
    }

    public function testReverseTransformEmpty()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();

        $this->assertNull($transformer->reverseTransform(''));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformRequiresString()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();
        $transformer->reverseTransform(12345);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWrapsIntlErrors()
    {
        $transformer = new DateTimeToLocalizedStringTransformer();
        $transformer->reverseTransform('12345');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testValidateDateFormatOption()
    {
        new DateTimeToLocalizedStringTransformer(null, null, 'foobar');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testValidateTimeFormatOption()
    {
        new DateTimeToLocalizedStringTransformer(null, null, null, 'foobar');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNonExistingDate()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC', \IntlDateFormatter::SHORT);

        $this->assertDateTimeEquals($this->dateTimeWithoutSeconds, $transformer->reverseTransform('31.04.10 04:05'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformOutOfTimestampRange()
    {
        $transformer = new DateTimeToLocalizedStringTransformer('UTC', 'UTC');
        $transformer->reverseTransform('1789-07-14');
    }
}
PK-1[�Ub,,UForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

abstract class DateTimeTestCase extends \PHPUnit_Framework_TestCase
{
    public static function assertDateTimeEquals(\DateTime $expected, \DateTime $actual)
    {
        self::assertEquals($expected->format('c'), $actual->format('c'));
    }
}
PK-1[�}��!
!
gForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToTimestampTransformer;

class DateTimeToTimestampTransformerTest extends DateTimeTestCase
{
    public function testTransform()
    {
        $transformer = new DateTimeToTimestampTransformer('UTC', 'UTC');

        $input = new \DateTime('2010-02-03 04:05:06 UTC');
        $output = $input->format('U');

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformEmpty()
    {
        $transformer = new DateTimeToTimestampTransformer();

        $this->assertNull($transformer->transform(null));
    }

    public function testTransformWithDifferentTimezones()
    {
        $transformer = new DateTimeToTimestampTransformer('Asia/Hong_Kong', 'America/New_York');

        $input = new \DateTime('2010-02-03 04:05:06 America/New_York');
        $output = $input->format('U');
        $input->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformFromDifferentTimezone()
    {
        $transformer = new DateTimeToTimestampTransformer('Asia/Hong_Kong', 'UTC');

        $input = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong');

        $dateTime = clone $input;
        $dateTime->setTimezone(new \DateTimeZone('UTC'));
        $output = $dateTime->format('U');

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformExpectsDateTime()
    {
        $transformer = new DateTimeToTimestampTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->transform('1234');
    }

    public function testReverseTransform()
    {
        $reverseTransformer = new DateTimeToTimestampTransformer('UTC', 'UTC');

        $output = new \DateTime('2010-02-03 04:05:06 UTC');
        $input = $output->format('U');

        $this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
    }

    public function testReverseTransformEmpty()
    {
        $reverseTransformer = new DateTimeToTimestampTransformer();

        $this->assertNull($reverseTransformer->reverseTransform(null));
    }

    public function testReverseTransformWithDifferentTimezones()
    {
        $reverseTransformer = new DateTimeToTimestampTransformer('Asia/Hong_Kong', 'America/New_York');

        $output = new \DateTime('2010-02-03 04:05:06 America/New_York');
        $input = $output->format('U');
        $output->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
    }

    public function testReverseTransformExpectsValidTimestamp()
    {
        $reverseTransformer = new DateTimeToTimestampTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $reverseTransformer->reverseTransform('2010-2010-2010');
    }
}
PK-1[��=�C?C?cForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToArrayTransformer;

class DateTimeToArrayTransformerTest extends DateTimeTestCase
{
    public function testTransform()
    {
        $transformer = new DateTimeToArrayTransformer('UTC', 'UTC');

        $input = new \DateTime('2010-02-03 04:05:06 UTC');

        $output = array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        );

        $this->assertSame($output, $transformer->transform($input));
    }

    public function testTransformEmpty()
    {
        $transformer = new DateTimeToArrayTransformer();

        $output = array(
            'year' => '',
            'month' => '',
            'day' => '',
            'hour' => '',
            'minute' => '',
            'second' => '',
        );

        $this->assertSame($output, $transformer->transform(null));
    }

    public function testTransformEmptyWithFields()
    {
        $transformer = new DateTimeToArrayTransformer(null, null, array('year', 'minute', 'second'));

        $output = array(
            'year' => '',
            'minute' => '',
            'second' => '',
        );

        $this->assertSame($output, $transformer->transform(null));
    }

    public function testTransformWithFields()
    {
        $transformer = new DateTimeToArrayTransformer('UTC', 'UTC', array('year', 'month', 'minute', 'second'));

        $input = new \DateTime('2010-02-03 04:05:06 UTC');

        $output = array(
            'year' => '2010',
            'month' => '2',
            'minute' => '5',
            'second' => '6',
        );

        $this->assertSame($output, $transformer->transform($input));
    }

    public function testTransformWithPadding()
    {
        $transformer = new DateTimeToArrayTransformer('UTC', 'UTC', null, true);

        $input = new \DateTime('2010-02-03 04:05:06 UTC');

        $output = array(
            'year' => '2010',
            'month' => '02',
            'day' => '03',
            'hour' => '04',
            'minute' => '05',
            'second' => '06',
        );

        $this->assertSame($output, $transformer->transform($input));
    }

    public function testTransformDifferentTimezones()
    {
        $transformer = new DateTimeToArrayTransformer('America/New_York', 'Asia/Hong_Kong');

        $input = new \DateTime('2010-02-03 04:05:06 America/New_York');

        $dateTime = new \DateTime('2010-02-03 04:05:06 America/New_York');
        $dateTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));
        $output = array(
            'year' => (string) (int) $dateTime->format('Y'),
            'month' => (string) (int) $dateTime->format('m'),
            'day' => (string) (int) $dateTime->format('d'),
            'hour' => (string) (int) $dateTime->format('H'),
            'minute' => (string) (int) $dateTime->format('i'),
            'second' => (string) (int) $dateTime->format('s'),
        );

        $this->assertSame($output, $transformer->transform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformRequiresDateTime()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform('12345');
    }

    public function testReverseTransform()
    {
        $transformer = new DateTimeToArrayTransformer('UTC', 'UTC');

        $input = array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        );

        $output = new \DateTime('2010-02-03 04:05:06 UTC');

        $this->assertDateTimeEquals($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformWithSomeZero()
    {
        $transformer = new DateTimeToArrayTransformer('UTC', 'UTC');

        $input = array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '0',
            'second' => '0',
        );

        $output = new \DateTime('2010-02-03 04:00:00 UTC');

        $this->assertDateTimeEquals($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyEmpty()
    {
        $transformer = new DateTimeToArrayTransformer();

        $input = array(
            'year' => '',
            'month' => '',
            'day' => '',
            'hour' => '',
            'minute' => '',
            'second' => '',
        );

        $this->assertNull($transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyEmptySubsetOfFields()
    {
        $transformer = new DateTimeToArrayTransformer(null, null, array('year', 'month', 'day'));

        $input = array(
            'year' => '',
            'month' => '',
            'day' => '',
        );

        $this->assertNull($transformer->reverseTransform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptyYear()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptyMonth()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptyDay()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptyHour()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptyMinute()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyEmptySecond()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
        ));
    }

    public function testReverseTransformNull()
    {
        $transformer = new DateTimeToArrayTransformer();

        $this->assertNull($transformer->reverseTransform(null));
    }

    public function testReverseTransformDifferentTimezones()
    {
        $transformer = new DateTimeToArrayTransformer('America/New_York', 'Asia/Hong_Kong');

        $input = array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        );

        $output = new \DateTime('2010-02-03 04:05:06 Asia/Hong_Kong');
        $output->setTimezone(new \DateTimeZone('America/New_York'));

        $this->assertDateTimeEquals($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformToDifferentTimezone()
    {
        $transformer = new DateTimeToArrayTransformer('Asia/Hong_Kong', 'UTC');

        $input = array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        );

        $output = new \DateTime('2010-02-03 04:05:06 UTC');
        $output->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertDateTimeEquals($output, $transformer->reverseTransform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformRequiresArray()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform('12345');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeYear()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '-1',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeMonth()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '-1',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeDay()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '-1',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeHour()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '-1',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeMinute()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '-1',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNegativeSecond()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '-1',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithInvalidMonth()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '13',
            'day' => '3',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithInvalidDay()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '31',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithStringDay()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => 'bazinga',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithStringMonth()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => 'bazinga',
            'day' => '31',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithStringYear()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => 'bazinga',
            'month' => '2',
            'day' => '31',
            'hour' => '4',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithEmptyStringHour()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '31',
            'hour' => '',
            'minute' => '5',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithEmptyStringMinute()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '31',
            'hour' => '4',
            'minute' => '',
            'second' => '6',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithEmptyStringSecond()
    {
        $transformer = new DateTimeToArrayTransformer();
        $transformer->reverseTransform(array(
            'year' => '2010',
            'month' => '2',
            'day' => '31',
            'hour' => '4',
            'minute' => '5',
            'second' => '',
        ));
    }
}
PK-1[���`Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\ArrayToPartsTransformer;

class ArrayToPartsTransformerTest extends \PHPUnit_Framework_TestCase
{
    private $transformer;

    protected function setUp()
    {
        $this->transformer = new ArrayToPartsTransformer(array(
            'first' => array('a', 'b', 'c'),
            'second' => array('d', 'e', 'f'),
        ));
    }

    protected function tearDown()
    {
        $this->transformer = null;
    }

    public function testTransform()
    {
        $input = array(
            'a' => '1',
            'b' => '2',
            'c' => '3',
            'd' => '4',
            'e' => '5',
            'f' => '6',
        );

        $output = array(
            'first' => array(
                'a' => '1',
                'b' => '2',
                'c' => '3',
            ),
            'second' => array(
                'd' => '4',
                'e' => '5',
                'f' => '6',
            ),
        );

        $this->assertSame($output, $this->transformer->transform($input));
    }

    public function testTransformEmpty()
    {
        $output = array(
            'first' => null,
            'second' => null,
        );

        $this->assertSame($output, $this->transformer->transform(null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformRequiresArray()
    {
        $this->transformer->transform('12345');
    }

    public function testReverseTransform()
    {
        $input = array(
            'first' => array(
                'a' => '1',
                'b' => '2',
                'c' => '3',
            ),
            'second' => array(
                'd' => '4',
                'e' => '5',
                'f' => '6',
            ),
        );

        $output = array(
            'a' => '1',
            'b' => '2',
            'c' => '3',
            'd' => '4',
            'e' => '5',
            'f' => '6',
        );

        $this->assertSame($output, $this->transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyEmpty()
    {
        $input = array(
            'first' => '',
            'second' => '',
        );

        $this->assertNull($this->transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyNull()
    {
        $input = array(
            'first' => null,
            'second' => null,
        );

        $this->assertNull($this->transformer->reverseTransform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyNull()
    {
        $input = array(
            'first' => array(
                'a' => '1',
                'b' => '2',
                'c' => '3',
            ),
            'second' => null,
        );

        $this->transformer->reverseTransform($input);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformRequiresArray()
    {
        $this->transformer->reverseTransform('12345');
    }
}
PK-1[\R��]Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DataTransformerChain;

class DataTransformerChainTest extends \PHPUnit_Framework_TestCase
{
    public function testTransform()
    {
        $transformer1 = $this->getMock('Symfony\Component\Form\DataTransformerInterface');
        $transformer1->expects($this->once())
                                 ->method('transform')
                                 ->with($this->identicalTo('foo'))
                                 ->will($this->returnValue('bar'));
        $transformer2 = $this->getMock('Symfony\Component\Form\DataTransformerInterface');
        $transformer2->expects($this->once())
                                 ->method('transform')
                                 ->with($this->identicalTo('bar'))
                                 ->will($this->returnValue('baz'));

        $chain = new DataTransformerChain(array($transformer1, $transformer2));

        $this->assertEquals('baz', $chain->transform('foo'));
    }

    public function testReverseTransform()
    {
        $transformer2 = $this->getMock('Symfony\Component\Form\DataTransformerInterface');
        $transformer2->expects($this->once())
                                 ->method('reverseTransform')
                                 ->with($this->identicalTo('foo'))
                                 ->will($this->returnValue('bar'));
        $transformer1 = $this->getMock('Symfony\Component\Form\DataTransformerInterface');
        $transformer1->expects($this->once())
                                 ->method('reverseTransform')
                                 ->with($this->identicalTo('bar'))
                                 ->will($this->returnValue('baz'));

        $chain = new DataTransformerChain(array($transformer1, $transformer2));

        $this->assertEquals('baz', $chain->reverseTransform('foo'));
    }
}
PK-1[�6���cForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\BooleanToStringTransformer;

class BooleanToStringTransformerTest extends \PHPUnit_Framework_TestCase
{
    const TRUE_VALUE = '1';

    /**
     * @var BooleanToStringTransformer
     */
    protected $transformer;

    protected function setUp()
    {
        $this->transformer = new BooleanToStringTransformer(self::TRUE_VALUE);
    }

    protected function tearDown()
    {
        $this->transformer = null;
    }

    public function testTransform()
    {
        $this->assertEquals(self::TRUE_VALUE, $this->transformer->transform(true));
        $this->assertNull($this->transformer->transform(false));
    }

    // https://github.com/symfony/symfony/issues/8989
    public function testTransformAcceptsNull()
    {
        $this->assertNull($this->transformer->transform(null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformFailsIfString()
    {
        $this->transformer->transform('1');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformFailsIfInteger()
    {
        $this->transformer->reverseTransform(1);
    }

    public function testReverseTransform()
    {
        $this->assertTrue($this->transformer->reverseTransform(self::TRUE_VALUE));
        $this->assertTrue($this->transformer->reverseTransform('foobar'));
        $this->assertTrue($this->transformer->reverseTransform(''));
        $this->assertFalse($this->transformer->reverseTransform(null));
    }
}
PK-1[Y@zjjjForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\MoneyToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class MoneyToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    public function testTransform()
    {
        $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);

        $this->assertEquals('1,23', $transformer->transform(123));
    }

    public function testTransformExpectsNumeric()
    {
        $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->transform('abcd');
    }

    public function testTransformEmpty()
    {
        $transformer = new MoneyToLocalizedStringTransformer();

        $this->assertSame('', $transformer->transform(null));
    }

    public function testReverseTransform()
    {
        $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);

        $this->assertEquals(123, $transformer->reverseTransform('1,23'));
    }

    public function testReverseTransformExpectsString()
    {
        $transformer = new MoneyToLocalizedStringTransformer(null, null, null, 100);

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->reverseTransform(12345);
    }

    public function testReverseTransformEmpty()
    {
        $transformer = new MoneyToLocalizedStringTransformer();

        $this->assertNull($transformer->reverseTransform(''));
    }
}
PK-1[]e"��eForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToRfc3339Transformer;

class DateTimeToRfc3339TransformerTest extends DateTimeTestCase
{
    protected $dateTime;
    protected $dateTimeWithoutSeconds;

    protected function setUp()
    {
        parent::setUp();

        $this->dateTime = new \DateTime('2010-02-03 04:05:06 UTC');
        $this->dateTimeWithoutSeconds = new \DateTime('2010-02-03 04:05:00 UTC');
    }

    protected function tearDown()
    {
        $this->dateTime = null;
        $this->dateTimeWithoutSeconds = null;
    }

    public static function assertEquals($expected, $actual, $message = '', $delta = 0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE)
    {
        if ($expected instanceof \DateTime && $actual instanceof \DateTime) {
            $expected = $expected->format('c');
            $actual = $actual->format('c');
        }

        parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
    }

    public function allProvider()
    {
        return array(
            array('UTC', 'UTC', '2010-02-03 04:05:06 UTC', '2010-02-03T04:05:06Z'),
            array('UTC', 'UTC', null, ''),
            array('America/New_York', 'Asia/Hong_Kong', '2010-02-03 04:05:06 America/New_York', '2010-02-03T17:05:06+08:00'),
            array('America/New_York', 'Asia/Hong_Kong', null, ''),
            array('UTC', 'Asia/Hong_Kong', '2010-02-03 04:05:06 UTC', '2010-02-03T12:05:06+08:00'),
            array('America/New_York', 'UTC', '2010-02-03 04:05:06 America/New_York', '2010-02-03T09:05:06Z'),
        );
    }

    public function transformProvider()
    {
        return $this->allProvider();
    }

    public function reverseTransformProvider()
    {
        return array_merge($this->allProvider(), array(
            // format without seconds, as appears in some browsers
            array('UTC', 'UTC', '2010-02-03 04:05:00 UTC', '2010-02-03T04:05Z'),
            array('America/New_York', 'Asia/Hong_Kong', '2010-02-03 04:05:00 America/New_York', '2010-02-03T17:05+08:00'),
            array('Europe/Amsterdam', 'Europe/Amsterdam', '2013-08-21 10:30:00 Europe/Amsterdam', '2013-08-21T08:30:00Z')
        ));
    }

    /**
     * @dataProvider transformProvider
     */
    public function testTransform($fromTz, $toTz, $from, $to)
    {
        $transformer = new DateTimeToRfc3339Transformer($fromTz, $toTz);

        $this->assertSame($to, $transformer->transform(null !== $from ? new \DateTime($from) : null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformRequiresValidDateTime()
    {
        $transformer = new DateTimeToRfc3339Transformer();
        $transformer->transform('2010-01-01');
    }

    /**
     * @dataProvider reverseTransformProvider
     */
    public function testReverseTransform($toTz, $fromTz, $to, $from)
    {
        $transformer = new DateTimeToRfc3339Transformer($toTz, $fromTz);

        if (null !== $to) {
            $this->assertDateTimeEquals(new \DateTime($to), $transformer->reverseTransform($from));
        } else {
            $this->assertSame($to, $transformer->reverseTransform($from));
        }
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformRequiresString()
    {
        $transformer = new DateTimeToRfc3339Transformer();
        $transformer->reverseTransform(12345);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformWithNonExistingDate()
    {
        $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC');

        $transformer->reverseTransform('2010-04-31T04:05Z');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsValidDateString()
    {
        $transformer = new DateTimeToRfc3339Transformer('UTC', 'UTC');

        $transformer->reverseTransform('2010-2010-2010');
    }
}
PK-1[N�z.z.lForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\IntegerToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class IntegerToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    public function transformWithRoundingProvider()
    {
        return array(
            // towards positive infinity (1.6 -> 2, -1.6 -> -1)
            array(1234.5, '1235', IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array(1234.4, '1235', IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array(-1234.5, '-1234', IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array(-1234.4, '-1234', IntegerToLocalizedStringTransformer::ROUND_CEILING),
            // towards negative infinity (1.6 -> 1, -1.6 -> -2)
            array(1234.5, '1234', IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array(1234.4, '1234', IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array(-1234.5, '-1235', IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array(-1234.4, '-1235', IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            // away from zero (1.6 -> 2, -1.6 -> 2)
            array(1234.5, '1235', IntegerToLocalizedStringTransformer::ROUND_UP),
            array(1234.4, '1235', IntegerToLocalizedStringTransformer::ROUND_UP),
            array(-1234.5, '-1235', IntegerToLocalizedStringTransformer::ROUND_UP),
            array(-1234.4, '-1235', IntegerToLocalizedStringTransformer::ROUND_UP),
            // towards zero (1.6 -> 1, -1.6 -> -1)
            array(1234.5, '1234', IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array(1234.4, '1234', IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array(-1234.5, '-1234', IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array(-1234.4, '-1234', IntegerToLocalizedStringTransformer::ROUND_DOWN),
            // round halves (.5) to the next even number
            array(1234.6, '1235', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1234.5, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1234.4, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1233.5, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1232.5, '1232', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(-1234.6, '-1235', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(-1234.5, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(-1234.4, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(-1233.5, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(-1232.5, '-1232', IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            // round halves (.5) away from zero
            array(1234.6, '1235', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1234.5, '1235', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1234.4, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array(-1234.6, '-1235', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array(-1234.5, '-1235', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array(-1234.4, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            // round halves (.5) towards zero
            array(1234.6, '1235', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1234.5, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1234.4, '1234', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(-1234.6, '-1235', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(-1234.5, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(-1234.4, '-1234', IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
        );
    }

    /**
     * @dataProvider transformWithRoundingProvider
     */
    public function testTransformWithRounding($input, $output, $roundingMode)
    {
        $transformer = new IntegerToLocalizedStringTransformer(null, null, $roundingMode);

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testReverseTransform()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $this->assertEquals(1, $transformer->reverseTransform('1'));
        $this->assertEquals(1, $transformer->reverseTransform('1,5'));
        $this->assertEquals(1234, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(12345, $transformer->reverseTransform('12345,912'));
    }

    public function testReverseTransformEmpty()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $this->assertNull($transformer->reverseTransform(''));
    }

    public function testReverseTransformWithGrouping()
    {
        $transformer = new IntegerToLocalizedStringTransformer(null, true);

        $this->assertEquals(1234, $transformer->reverseTransform('1.234,5'));
        $this->assertEquals(12345, $transformer->reverseTransform('12.345,912'));
        $this->assertEquals(1234, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(12345, $transformer->reverseTransform('12345,912'));
    }

    public function reverseTransformWithRoundingProvider()
    {
        return array(
            // towards positive infinity (1.6 -> 2, -1.6 -> -1)
            array('1234,5', 1235, IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array('1234,4', 1235, IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array('-1234,5', -1234, IntegerToLocalizedStringTransformer::ROUND_CEILING),
            array('-1234,4', -1234, IntegerToLocalizedStringTransformer::ROUND_CEILING),
            // towards negative infinity (1.6 -> 1, -1.6 -> -2)
            array('1234,5', 1234, IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array('1234,4', 1234, IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array('-1234,5', -1235, IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            array('-1234,4', -1235, IntegerToLocalizedStringTransformer::ROUND_FLOOR),
            // away from zero (1.6 -> 2, -1.6 -> 2)
            array('1234,5', 1235, IntegerToLocalizedStringTransformer::ROUND_UP),
            array('1234,4', 1235, IntegerToLocalizedStringTransformer::ROUND_UP),
            array('-1234,5', -1235, IntegerToLocalizedStringTransformer::ROUND_UP),
            array('-1234,4', -1235, IntegerToLocalizedStringTransformer::ROUND_UP),
            // towards zero (1.6 -> 1, -1.6 -> -1)
            array('1234,5', 1234, IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array('1234,4', 1234, IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array('-1234,5', -1234, IntegerToLocalizedStringTransformer::ROUND_DOWN),
            array('-1234,4', -1234, IntegerToLocalizedStringTransformer::ROUND_DOWN),
            // round halves (.5) to the next even number
            array('1234,6', 1235, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('1234,5', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('1234,4', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('1233,5', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('1232,5', 1232, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('-1234,6', -1235, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('-1234,5', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('-1234,4', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('-1233,5', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array('-1232,5', -1232, IntegerToLocalizedStringTransformer::ROUND_HALF_EVEN),
            // round halves (.5) away from zero
            array('1234,6', 1235, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array('1234,5', 1235, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array('1234,4', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array('-1234,6', -1235, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array('-1234,5', -1235, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            array('-1234,4', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_UP),
            // round halves (.5) towards zero
            array('1234,6', 1235, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array('1234,5', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array('1234,4', 1234, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array('-1234,6', -1235, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array('-1234,5', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array('-1234,4', -1234, IntegerToLocalizedStringTransformer::ROUND_HALF_DOWN),
        );
    }

    /**
     * @dataProvider reverseTransformWithRoundingProvider
     */
    public function testReverseTransformWithRounding($input, $output, $roundingMode)
    {
        $transformer = new IntegerToLocalizedStringTransformer(null, null, $roundingMode);

        $this->assertEquals($output, $transformer->reverseTransform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsString()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform(1);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsValidNumber()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform('foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsNaN()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform('NaN');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsNaN2()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform('nan');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsInfinity()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform('∞');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsNegativeInfinity()
    {
        $transformer = new IntegerToLocalizedStringTransformer();

        $transformer->reverseTransform('-∞');
    }
}
PK-1[��`nonokForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\NumberToLocalizedStringTransformer;
use Symfony\Component\Intl\Util\IntlTestHelper;

class NumberToLocalizedStringTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        parent::setUp();

        // Since we test against "de_AT", we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    public function provideTransformations()
    {
        return array(
            array(null, '', 'de_AT'),
            array(1, '1', 'de_AT'),
            array(1.5, '1,5', 'de_AT'),
            array(1234.5, '1234,5', 'de_AT'),
            array(12345.912, '12345,912', 'de_AT'),
            array(1234.5, '1234,5', 'ru'),
            array(1234.5, '1234,5', 'fi'),
        );
    }

    /**
     * @dataProvider provideTransformations
     */
    public function testTransform($from, $to, $locale)
    {
        \Locale::setDefault($locale);

        $transformer = new NumberToLocalizedStringTransformer();

        $this->assertSame($to, $transformer->transform($from));
    }

    public function provideTransformationsWithGrouping()
    {
        return array(
            array(1234.5, '1.234,5', 'de_AT'),
            array(12345.912, '12.345,912', 'de_AT'),
            array(1234.5, '1 234,5', 'fr'),
            array(1234.5, '1 234,5', 'ru'),
            array(1234.5, '1 234,5', 'fi'),
        );
    }

    /**
     * @dataProvider provideTransformationsWithGrouping
     */
    public function testTransformWithGrouping($from, $to, $locale)
    {
        \Locale::setDefault($locale);

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $this->assertSame($to, $transformer->transform($from));
    }

    public function testTransformWithPrecision()
    {
        $transformer = new NumberToLocalizedStringTransformer(2);

        $this->assertEquals('1234,50', $transformer->transform(1234.5));
        $this->assertEquals('678,92', $transformer->transform(678.916));
    }

    public function transformWithRoundingProvider()
    {
        return array(
            // towards positive infinity (1.6 -> 2, -1.6 -> -1)
            array(0, 1234.5, '1235', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, 1234.4, '1235', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, -1234.5, '-1234', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, -1234.4, '-1234', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, 123.45, '123,5', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, 123.44, '123,5', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, -123.45, '-123,4', NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, -123.44, '-123,4', NumberToLocalizedStringTransformer::ROUND_CEILING),
            // towards negative infinity (1.6 -> 1, -1.6 -> -2)
            array(0, 1234.5, '1234', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, 1234.4, '1234', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, -1234.5, '-1235', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, -1234.4, '-1235', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, 123.45, '123,4', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, 123.44, '123,4', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, -123.45, '-123,5', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, -123.44, '-123,5', NumberToLocalizedStringTransformer::ROUND_FLOOR),
            // away from zero (1.6 -> 2, -1.6 -> 2)
            array(0, 1234.5, '1235', NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, 1234.4, '1235', NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, -1234.5, '-1235', NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, -1234.4, '-1235', NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, 123.45, '123,5', NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, 123.44, '123,5', NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, -123.45, '-123,5', NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, -123.44, '-123,5', NumberToLocalizedStringTransformer::ROUND_UP),
            // towards zero (1.6 -> 1, -1.6 -> -1)
            array(0, 1234.5, '1234', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, 1234.4, '1234', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, -1234.5, '-1234', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, -1234.4, '-1234', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, 123.45, '123,4', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, 123.44, '123,4', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, -123.45, '-123,4', NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, -123.44, '-123,4', NumberToLocalizedStringTransformer::ROUND_DOWN),
            // round halves (.5) to the next even number
            array(0, 1234.6, '1235', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, 1234.5, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, 1234.4, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, 1233.5, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, 1232.5, '1232', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, -1234.6, '-1235', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, -1234.5, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, -1234.4, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, -1233.5, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, -1232.5, '-1232', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, 123.46, '123,5', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, 123.45, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, 123.44, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, 123.35, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, 123.25, '123,2', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, -123.46, '-123,5', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, -123.45, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, -123.44, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, -123.35, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, -123.25, '-123,2', NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            // round halves (.5) away from zero
            array(0, 1234.6, '1235', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, 1234.5, '1235', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, 1234.4, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, -1234.6, '-1235', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, -1234.5, '-1235', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, -1234.4, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, 123.46, '123,5', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, 123.45, '123,5', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, 123.44, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, -123.46, '-123,5', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, -123.45, '-123,5', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, -123.44, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            // round halves (.5) towards zero
            array(0, 1234.6, '1235', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, 1234.5, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, 1234.4, '1234', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, -1234.6, '-1235', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, -1234.5, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, -1234.4, '-1234', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, 123.46, '123,5', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, 123.45, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, 123.44, '123,4', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, -123.46, '-123,5', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, -123.45, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, -123.44, '-123,4', NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
        );
    }

    /**
     * @dataProvider transformWithRoundingProvider
     */
    public function testTransformWithRounding($precision, $input, $output, $roundingMode)
    {
        $transformer = new NumberToLocalizedStringTransformer($precision, null, $roundingMode);

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformDoesNotRoundIfNoPrecision()
    {
        $transformer = new NumberToLocalizedStringTransformer(null, null, NumberToLocalizedStringTransformer::ROUND_DOWN);

        $this->assertEquals('1234,547', $transformer->transform(1234.547));
    }

    /**
     * @dataProvider provideTransformations
     */
    public function testReverseTransform($to, $from, $locale)
    {
        \Locale::setDefault($locale);

        $transformer = new NumberToLocalizedStringTransformer();

        $this->assertEquals($to, $transformer->reverseTransform($from));
    }

    /**
     * @dataProvider provideTransformationsWithGrouping
     */
    public function testReverseTransformWithGrouping($to, $from, $locale)
    {
        \Locale::setDefault($locale);

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $this->assertEquals($to, $transformer->reverseTransform($from));
    }

    // https://github.com/symfony/symfony/issues/7609
    public function testReverseTransformWithGroupingAndFixedSpaces()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('The "mbstring" extension is required for this test.');
        }

        \Locale::setDefault('ru');

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $this->assertEquals(1234.5, $transformer->reverseTransform("1\xc2\xa0234,5"));
    }

    public function testReverseTransformWithGroupingButWithoutGroupSeparator()
    {
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        // omit group separator
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(12345.912, $transformer->reverseTransform('12345,912'));
    }

    public function reverseTransformWithRoundingProvider()
    {
        return array(
            // towards positive infinity (1.6 -> 2, -1.6 -> -1)
            array(0, '1234,5', 1235, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, '1234,4', 1235, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, '-1234,5', -1234, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(0, '-1234,4', -1234, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, '123,45', 123.5, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, '123,44', 123.5, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, '-123,45', -123.4, NumberToLocalizedStringTransformer::ROUND_CEILING),
            array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_CEILING),
            // towards negative infinity (1.6 -> 1, -1.6 -> -2)
            array(0, '1234,5', 1234, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, '1234,4', 1234, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, '-1234,5', -1235, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(0, '-1234,4', -1235, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, '123,45', 123.4, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, '-123,45', -123.5, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            array(1, '-123,44', -123.5, NumberToLocalizedStringTransformer::ROUND_FLOOR),
            // away from zero (1.6 -> 2, -1.6 -> 2)
            array(0, '1234,5', 1235, NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, '1234,4', 1235, NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, '-1234,5', -1235, NumberToLocalizedStringTransformer::ROUND_UP),
            array(0, '-1234,4', -1235, NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, '123,45', 123.5, NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, '123,44', 123.5, NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, '-123,45', -123.5, NumberToLocalizedStringTransformer::ROUND_UP),
            array(1, '-123,44', -123.5, NumberToLocalizedStringTransformer::ROUND_UP),
            // towards zero (1.6 -> 1, -1.6 -> -1)
            array(0, '1234,5', 1234, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, '1234,4', 1234, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, '-1234,5', -1234, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(0, '-1234,4', -1234, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, '123,45', 123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, '-123,45', -123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
            array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_DOWN),
            // round halves (.5) to the next even number
            array(0, '1234,6', 1235, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '1234,5', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '1234,4', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '1233,5', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '1232,5', 1232, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '-1234,6', -1235, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '-1234,5', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '-1234,4', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '-1233,5', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(0, '-1232,5', -1232, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '123,46', 123.5, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '123,45', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '123,35', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '123,25', 123.2, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '-123,46', -123.5, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '-123,45', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '-123,35', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            array(1, '-123,25', -123.2, NumberToLocalizedStringTransformer::ROUND_HALF_EVEN),
            // round halves (.5) away from zero
            array(0, '1234,6', 1235, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, '1234,5', 1235, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, '1234,4', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, '-1234,6', -1235, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, '-1234,5', -1235, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(0, '-1234,4', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '123,46', 123.5, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '123,45', 123.5, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '-123,46', -123.5, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '-123,45', -123.5, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_UP),
            // round halves (.5) towards zero
            array(0, '1234,6', 1235, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, '1234,5', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, '1234,4', 1234, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, '-1234,6', -1235, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, '-1234,5', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(0, '-1234,4', -1234, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '123,46', 123.5, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '123,45', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '123,44', 123.4, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '-123,46', -123.5, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '-123,45', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
            array(1, '-123,44', -123.4, NumberToLocalizedStringTransformer::ROUND_HALF_DOWN),
        );
    }

    /**
     * @dataProvider reverseTransformWithRoundingProvider
     */
    public function testReverseTransformWithRounding($precision, $input, $output, $roundingMode)
    {
        $transformer = new NumberToLocalizedStringTransformer($precision, null, $roundingMode);

        $this->assertEquals($output, $transformer->reverseTransform($input));
    }

    public function testReverseTransformDoesNotRoundIfNoPrecision()
    {
        $transformer = new NumberToLocalizedStringTransformer(null, null, NumberToLocalizedStringTransformer::ROUND_DOWN);

        $this->assertEquals(1234.547, $transformer->reverseTransform('1234,547'));
    }

    public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsNotDot()
    {
        \Locale::setDefault('fr');
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        // completely valid format
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234,5'));
        // accept dots
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234.5'));
        // omit group separator
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDot()
    {
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform('1.234.5');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testDecimalSeparatorMayNotBeDotIfGroupingSeparatorIsDotWithNoGroupSep()
    {
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform('1234.5');
    }

    public function testDecimalSeparatorMayBeDotIfGroupingSeparatorIsDotButNoGroupingUsed()
    {
        \Locale::setDefault('fr');
        $transformer = new NumberToLocalizedStringTransformer();

        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsNotComma()
    {
        \Locale::setDefault('bg');
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        // completely valid format
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234.5'));
        // accept commas
        $this->assertEquals(1234.5, $transformer->reverseTransform('1 234,5'));
        // omit group separator
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsComma()
    {
        \Locale::setDefault('en');
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform('1,234,5');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testDecimalSeparatorMayNotBeCommaIfGroupingSeparatorIsCommaWithNoGroupSep()
    {
        \Locale::setDefault('en');
        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform('1234,5');
    }

    public function testDecimalSeparatorMayBeCommaIfGroupingSeparatorIsCommaButNoGroupingUsed()
    {
        \Locale::setDefault('en');
        $transformer = new NumberToLocalizedStringTransformer();

        $this->assertEquals(1234.5, $transformer->reverseTransform('1234,5'));
        $this->assertEquals(1234.5, $transformer->reverseTransform('1234.5'));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformExpectsNumeric()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->transform('foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsString()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform(1);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsValidNumber()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @link https://github.com/symfony/symfony/issues/3161
     */
    public function testReverseTransformDisallowsNaN()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('NaN');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsNaN2()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('nan');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsInfinity()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('∞');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsInfinity2()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('∞,123');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsNegativeInfinity()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('-∞');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDisallowsLeadingExtraCharacters()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('foo123');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @expectedExceptionMessage The number contains unrecognized characters: "foo3"
     */
    public function testReverseTransformDisallowsCenteredExtraCharacters()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('12foo3');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @expectedExceptionMessage The number contains unrecognized characters: "foo8"
     */
    public function testReverseTransformDisallowsCenteredExtraCharactersMultibyte()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('The "mbstring" extension is required for this test.');
        }

        \Locale::setDefault('ru');

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform("12\xc2\xa0345,67foo8");
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @expectedExceptionMessage The number contains unrecognized characters: "foo8"
     */
    public function testReverseTransformIgnoresTrailingSpacesInExceptionMessage()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('The "mbstring" extension is required for this test.');
        }

        \Locale::setDefault('ru');

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform("12\xc2\xa0345,67foo8  \xc2\xa0\t");
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @expectedExceptionMessage The number contains unrecognized characters: "foo"
     */
    public function testReverseTransformDisallowsTrailingExtraCharacters()
    {
        $transformer = new NumberToLocalizedStringTransformer();

        $transformer->reverseTransform('123foo');
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     * @expectedExceptionMessage The number contains unrecognized characters: "foo"
     */
    public function testReverseTransformDisallowsTrailingExtraCharactersMultibyte()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('The "mbstring" extension is required for this test.');
        }

        \Locale::setDefault('ru');

        $transformer = new NumberToLocalizedStringTransformer(null, true);

        $transformer->reverseTransform("12\xc2\xa0345,678foo");
    }
}
PK-1[�?+�<<eForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer;

class ValueToDuplicatesTransformerTest extends \PHPUnit_Framework_TestCase
{
    private $transformer;

    protected function setUp()
    {
        $this->transformer = new ValueToDuplicatesTransformer(array('a', 'b', 'c'));
    }

    protected function tearDown()
    {
        $this->transformer = null;
    }

    public function testTransform()
    {
        $output = array(
            'a' => 'Foo',
            'b' => 'Foo',
            'c' => 'Foo',
        );

        $this->assertSame($output, $this->transformer->transform('Foo'));
    }

    public function testTransformEmpty()
    {
        $output = array(
            'a' => null,
            'b' => null,
            'c' => null,
        );

        $this->assertSame($output, $this->transformer->transform(null));
    }

    public function testReverseTransform()
    {
        $input = array(
            'a' => 'Foo',
            'b' => 'Foo',
            'c' => 'Foo',
        );

        $this->assertSame('Foo', $this->transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyEmpty()
    {
        $input = array(
            'a' => '',
            'b' => '',
            'c' => '',
        );

        $this->assertNull($this->transformer->reverseTransform($input));
    }

    public function testReverseTransformCompletelyNull()
    {
        $input = array(
            'a' => null,
            'b' => null,
            'c' => null,
        );

        $this->assertNull($this->transformer->reverseTransform($input));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformPartiallyNull()
    {
        $input = array(
            'a' => 'Foo',
            'b' => 'Foo',
            'c' => null,
        );

        $this->transformer->reverseTransform($input);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformDifferences()
    {
        $input = array(
            'a' => 'Foo',
            'b' => 'Bar',
            'c' => 'Foo',
        );

        $this->transformer->reverseTransform($input);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformRequiresArray()
    {
        $this->transformer->reverseTransform('12345');
    }
}
PK-1[fJ��`Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

class BaseDateTimeTransformerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     * @expectedExceptionMessage this_timezone_does_not_exist
     */
    public function testConstructFailsIfInputTimezoneIsInvalid()
    {
        $this->getMock(
            'Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer',
            array(),
            array('this_timezone_does_not_exist')
        );
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidArgumentException
     * @expectedExceptionMessage that_timezone_does_not_exist
     */
    public function testConstructFailsIfOutputTimezoneIsInvalid()
    {
        $this->getMock(
            'Symfony\Component\Form\Extension\Core\DataTransformer\BaseDateTimeTransformer',
            array(),
            array(null, 'that_timezone_does_not_exist')
        );
    }
}
PK-1[�.bc))cForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;

use Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer;

class ChoicesToValuesTransformerTest extends \PHPUnit_Framework_TestCase
{
    protected $transformer;

    protected function setUp()
    {
        $list = new SimpleChoiceList(array(0 => 'A', 1 => 'B', 2 => 'C'));
        $this->transformer = new ChoicesToValuesTransformer($list);
    }

    protected function tearDown()
    {
        $this->transformer = null;
    }

    public function testTransform()
    {
        // Value strategy in SimpleChoiceList is to copy and convert to string
        $in = array(0, 1, 2);
        $out = array('0', '1', '2');

        $this->assertSame($out, $this->transformer->transform($in));
    }

    public function testTransformNull()
    {
        $this->assertSame(array(), $this->transformer->transform(null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformExpectsArray()
    {
        $this->transformer->transform('foobar');
    }

    public function testReverseTransform()
    {
        // values are expected to be valid choices and stay the same
        $in = array('0', '1', '2');
        $out = array(0, 1, 2);

        $this->assertSame($out, $this->transformer->reverseTransform($in));
    }

    public function testReverseTransformNull()
    {
        $this->assertSame(array(), $this->transformer->reverseTransform(null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testReverseTransformExpectsArray()
    {
        $this->transformer->reverseTransform('foobar');
    }
}
PK-1[JW����dForm/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\DataTransformer;

use Symfony\Component\Form\Extension\Core\DataTransformer\DateTimeToStringTransformer;

class DateTimeToStringTransformerTest extends DateTimeTestCase
{
    public function dataProvider()
    {
        $data = array(
            array('Y-m-d H:i:s', '2010-02-03 16:05:06', '2010-02-03 16:05:06 UTC'),
            array('Y-m-d H:i:00', '2010-02-03 16:05:00', '2010-02-03 16:05:00 UTC'),
            array('Y-m-d H:i', '2010-02-03 16:05', '2010-02-03 16:05:00 UTC'),
            array('Y-m-d H', '2010-02-03 16', '2010-02-03 16:00:00 UTC'),
            array('Y-m-d', '2010-02-03', '2010-02-03 00:00:00 UTC'),
            array('Y-m', '2010-12', '2010-12-01 00:00:00 UTC'),
            array('Y', '2010', '2010-01-01 00:00:00 UTC'),
            array('d-m-Y', '03-02-2010', '2010-02-03 00:00:00 UTC'),
            array('H:i:s', '16:05:06', '1970-01-01 16:05:06 UTC'),
            array('H:i:00', '16:05:00', '1970-01-01 16:05:00 UTC'),
            array('H:i', '16:05', '1970-01-01 16:05:00 UTC'),
            array('H', '16', '1970-01-01 16:00:00 UTC'),

            // different day representations
            array('Y-m-j', '2010-02-3', '2010-02-03 00:00:00 UTC'),
            array('z', '33', '1970-02-03 00:00:00 UTC'),

            // not bijective
            // this will not work as PHP will use actual date to replace missing info
            // and after change of date will lookup for closest Wednesday
            // i.e. value: 2010-02, PHP value: 2010-02-(today i.e. 20), parsed date: 2010-02-24
            //array('Y-m-D', '2010-02-Wed', '2010-02-03 00:00:00 UTC'),
            //array('Y-m-l', '2010-02-Wednesday', '2010-02-03 00:00:00 UTC'),

            // different month representations
            array('Y-n-d', '2010-2-03', '2010-02-03 00:00:00 UTC'),
            array('Y-M-d', '2010-Feb-03', '2010-02-03 00:00:00 UTC'),
            array('Y-F-d', '2010-February-03', '2010-02-03 00:00:00 UTC'),

            // different year representations
            array('y-m-d', '10-02-03', '2010-02-03 00:00:00 UTC'),

            // different time representations
            array('G:i:s', '16:05:06', '1970-01-01 16:05:06 UTC'),
            array('g:i:s a', '4:05:06 pm', '1970-01-01 16:05:06 UTC'),
            array('h:i:s a', '04:05:06 pm', '1970-01-01 16:05:06 UTC'),

            // seconds since Unix
            array('U', '1265213106', '2010-02-03 16:05:06 UTC'),
        );

        // This test will fail < 5.3.9 - see https://bugs.php.net/51994
        if (version_compare(phpversion(), '5.3.9', '>=')) {
            $data[] = array('Y-z', '2010-33', '2010-02-03 00:00:00 UTC');
        }

        return $data;
    }

    /**
     * @dataProvider dataProvider
     */
    public function testTransform($format, $output, $input)
    {
        $transformer = new DateTimeToStringTransformer('UTC', 'UTC', $format);

        $input = new \DateTime($input);

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformEmpty()
    {
        $transformer = new DateTimeToStringTransformer();

        $this->assertSame('', $transformer->transform(null));
    }

    public function testTransformWithDifferentTimezones()
    {
        $transformer = new DateTimeToStringTransformer('Asia/Hong_Kong', 'America/New_York', 'Y-m-d H:i:s');

        $input = new \DateTime('2010-02-03 12:05:06 America/New_York');
        $output = $input->format('Y-m-d H:i:s');
        $input->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertEquals($output, $transformer->transform($input));
    }

    public function testTransformExpectsDateTime()
    {
        $transformer = new DateTimeToStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $transformer->transform('1234');
    }

    /**
     * @dataProvider dataProvider
     */
    public function testReverseTransformUsingPipe($format, $input, $output)
    {
        if (version_compare(phpversion(), '5.3.7', '<')) {
            $this->markTestSkipped('Pipe usage requires PHP 5.3.7 or newer.');
        }

        $reverseTransformer = new DateTimeToStringTransformer('UTC', 'UTC', $format, true);

        $output = new \DateTime($output);

        $this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
    }

    /**
     * @dataProvider dataProvider
     */
    public function testReverseTransformWithoutUsingPipe($format, $input, $output)
    {
        $reverseTransformer = new DateTimeToStringTransformer('UTC', 'UTC', $format, false);

        $output = new \DateTime($output);

        $this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
    }

    public function testReverseTransformEmpty()
    {
        $reverseTransformer = new DateTimeToStringTransformer();

        $this->assertNull($reverseTransformer->reverseTransform(''));
    }

    public function testReverseTransformWithDifferentTimezones()
    {
        $reverseTransformer = new DateTimeToStringTransformer('America/New_York', 'Asia/Hong_Kong', 'Y-m-d H:i:s');

        $output = new \DateTime('2010-02-03 16:05:06 Asia/Hong_Kong');
        $input = $output->format('Y-m-d H:i:s');
        $output->setTimeZone(new \DateTimeZone('America/New_York'));

        $this->assertDateTimeEquals($output, $reverseTransformer->reverseTransform($input));
    }

    public function testReverseTransformExpectsString()
    {
        $reverseTransformer = new DateTimeToStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $reverseTransformer->reverseTransform(1234);
    }

    public function testReverseTransformExpectsValidDateString()
    {
        $reverseTransformer = new DateTimeToStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $reverseTransformer->reverseTransform('2010-2010-2010');
    }

    public function testReverseTransformWithNonExistingDate()
    {
        $reverseTransformer = new DateTimeToStringTransformer();

        $this->setExpectedException('Symfony\Component\Form\Exception\TransformationFailedException');

        $reverseTransformer->reverseTransform('2010-04-31');
    }
}
PK-1[��W@@JForm/Symfony/Component/Form/Tests/Extension/Core/Type/LanguageTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Intl\Util\IntlTestHelper;

class LanguageTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testCountriesAreSelectable()
    {
        $form = $this->factory->create('language');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        $this->assertContains(new ChoiceView('en', 'en', 'English'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('en_GB', 'en_GB', 'British English'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('en_US', 'en_US', 'U.S. English'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('fr', 'fr', 'French'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('my', 'my', 'Burmese'), $choices, '', false, false);
    }

    public function testMultipleLanguagesIsNotIncluded()
    {
        $form = $this->factory->create('language', 'language');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        $this->assertNotContains(new ChoiceView('mul', 'mul', 'Mehrsprachig'), $choices, '', false, false);
    }
}
PK.1[x���aaHForm/Symfony/Component/Form/Tests/Extension/Core/Type/LocaleTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Intl\Util\IntlTestHelper;

class LocaleTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testLocalesAreSelectable()
    {
        $form = $this->factory->create('locale');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        $this->assertContains(new ChoiceView('en', 'en', 'English'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('en_GB', 'en_GB', 'English (United Kingdom)'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('zh_Hant_MO', 'zh_Hant_MO', 'Chinese (Traditional, Macau SAR China)'), $choices, '', false, false);
    }
}
PK.1[�C���HForm/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ButtonTypeTest extends BaseTypeTest
{
    public function testCreateButtonInstances()
    {
        $this->assertInstanceOf('Symfony\Component\Form\Button', $this->factory->create('button'));
    }

    protected function getTestedType()
    {
        return 'button';
    }
}
PK.1[�'�\�\FForm/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;

class DateTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        parent::setUp();

        // we test against "de_AT", so we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_AT');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testInvalidWidgetOption()
    {
        $this->factory->create('date', null, array(
            'widget' => 'fake_widget',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testInvalidInputOption()
    {
        $this->factory->create('date', null, array(
            'input' => 'fake_input',
        ));
    }

    public function testSubmitFromSingleTextDateTimeWithDefaultFormat()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('2010-06-02');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('2010-06-02', $form->getViewData());
    }

    public function testSubmitFromSingleTextDateTime()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('2.6.2010');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextString()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'string',
        ));

        $form->submit('2.6.2010');

        $this->assertEquals('2010-06-02', $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextTimestamp()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'timestamp',
        ));

        $form->submit('2.6.2010');

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromSingleTextRaw()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
            'input' => 'array',
        ));

        $form->submit('2.6.2010');

        $output = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $this->assertEquals($output, $form->getData());
        $this->assertEquals('02.06.2010', $form->getViewData());
    }

    public function testSubmitFromText()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'text',
        ));

        $text = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $form->submit($text);

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromChoice()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $text = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $form->submit($text);

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromChoiceEmpty()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
            'required' => false,
        ));

        $text = array(
            'day' => '',
            'month' => '',
            'year' => '',
        );

        $form->submit($text);

        $this->assertNull($form->getData());
        $this->assertEquals($text, $form->getViewData());
    }

    public function testSubmitFromInputDateTimeDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $form->submit('06*2010*02');

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 UTC'), $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputStringDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'string',
        ));

        $form->submit('06*2010*02');

        $this->assertEquals('2010-06-02', $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputTimestampDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'timestamp',
        ));

        $form->submit('06*2010*02');

        $dateTime = new \DateTime('2010-06-02 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    public function testSubmitFromInputRawDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'format' => 'MM*yyyy*dd',
            'widget' => 'single_text',
            'input' => 'array',
        ));

        $form->submit('06*2010*02');

        $output = array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        );

        $this->assertEquals($output, $form->getData());
        $this->assertEquals('06*2010*02', $form->getViewData());
    }

    /**
     * @dataProvider provideDateFormats
     */
    public function testDatePatternWithFormatOption($format, $pattern)
    {
        $form = $this->factory->create('date', null, array(
            'format' => $format,
        ));

        $view = $form->createView();

        $this->assertEquals($pattern, $view->vars['date_pattern']);
    }

    public function provideDateFormats()
    {
        return array(
            array('dMy', '{{ day }}{{ month }}{{ year }}'),
            array('d-M-yyyy', '{{ day }}-{{ month }}-{{ year }}'),
            array('M d y', '{{ month }} {{ day }} {{ year }}'),
        );
    }

    /**
     * This test is to check that the strings '0', '1', '2', '3' are not accepted
     * as valid IntlDateFormatter constants for FULL, LONG, MEDIUM or SHORT respectively.
     *
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsNoPattern()
    {
        $this->factory->create('date', null, array(
            'format' => '0',
            'widget' => 'single_text',
            'input' => 'string',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatDoesNotContainYearMonthAndDay()
    {
        $this->factory->create('date', null, array(
            'months' => array(6, 7),
            'format' => 'yy',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsNoConstant()
    {
        $this->factory->create('date', null, array(
            'format' => 105,
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testThrowExceptionIfFormatIsInvalid()
    {
        $this->factory->create('date', null, array(
            'format' => array(),
        ));
    }

    public function testSetDataWithDifferentTimezones()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $form->setData('2010-06-02');

        $this->assertEquals('01.06.2010', $form->getViewData());
    }

    public function testSetDataWithDifferentTimezonesDateTime()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::MEDIUM,
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'input' => 'datetime',
            'widget' => 'single_text',
        ));

        $dateTime = new \DateTime('2010-06-02 America/New_York');

        $form->setData($dateTime);

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals('01.06.2010', $form->getViewData());
    }

    public function testYearsOption()
    {
        $form = $this->factory->create('date', null, array(
            'years' => array(2010, 2011),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('2010', '2010', '2010'),
            new ChoiceView('2011', '2011', '2011'),
        ), $view['year']->vars['choices']);
    }

    public function testMonthsOption()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionShortFormat()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jän'),
            new ChoiceView('4', '4', 'Apr.')
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionLongFormat()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jänner'),
            new ChoiceView('4', '4', 'April'),
        ), $view['month']->vars['choices']);
    }

    public function testMonthsOptionLongFormatWithDifferentTimezone()
    {
        $form = $this->factory->create('date', null, array(
            'months' => array(1, 4),
            'format' => 'dd.MMMM.yy',
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('1', '1', 'Jänner'),
            new ChoiceView('4', '4', 'April'),
        ), $view['month']->vars['choices']);
    }

    public function testIsDayWithinRangeReturnsTrueIfWithin()
    {
        $form = $this->factory->create('date', null, array(
            'days' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['day']->vars['choices']);
    }

    public function testIsPartiallyFilledReturnsFalseIfSingleText()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'single_text',
        ));

        $form->submit('7.6.2010');

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfChoiceAndCompletelyEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '',
            'month' => '',
            'year' => '',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfChoiceAndCompletelyFilled()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '2',
            'month' => '6',
            'year' => '2010',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsTrueIfChoiceAndDayEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('date', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'widget' => 'choice',
        ));

        $form->submit(array(
            'day' => '',
            'month' => '6',
            'year' => '2010',
        ));

        $this->assertTrue($form->isPartiallyFilled());
    }

    public function testPassDatePatternToView()
    {
        $form = $this->factory->create('date');
        $view = $form->createView();

        $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentFormat()
    {
        $form = $this->factory->create('date', null, array(
            'format' => \IntlDateFormatter::LONG,
        ));

        $view = $form->createView();

        $this->assertSame('{{ day }}{{ month }}{{ year }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentPattern()
    {
        $form = $this->factory->create('date', null, array(
            'format' => 'MMyyyydd'
        ));

        $view = $form->createView();

        $this->assertSame('{{ month }}{{ year }}{{ day }}', $view->vars['date_pattern']);
    }

    public function testPassDatePatternToViewDifferentPatternWithSeparators()
    {
        $form = $this->factory->create('date', null, array(
            'format' => 'MM*yyyy*dd'
        ));

        $view = $form->createView();

        $this->assertSame('{{ month }}*{{ year }}*{{ day }}', $view->vars['date_pattern']);
    }

    public function testDontPassDatePatternIfText()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));
        $view = $form->createView();

        $this->assertFalse(isset($view->vars['date_pattern']));
    }

    public function testPassWidgetToView()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));
        $view = $form->createView();

        $this->assertSame('single_text', $view->vars['widget']);
    }

    // Bug fix
    public function testInitializeWithDateTime()
    {
        // Throws an exception if "data_class" option is not explicitly set
        // to null in the type
        $this->factory->create('date', new \DateTime());
    }

    public function testSingleTextWidgetShouldUseTheRightInputType()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertEquals('date', $view->vars['type']);
    }

    public function testPassDefaultEmptyValueToViewIfNotRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => false,
        ));

        $view = $form->createView();
        $this->assertSame('', $view['year']->vars['empty_value']);
        $this->assertSame('', $view['month']->vars['empty_value']);
        $this->assertSame('', $view['day']->vars['empty_value']);
    }

    public function testPassNoEmptyValueToViewIfRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => true,
        ));

        $view = $form->createView();
        $this->assertNull($view['year']->vars['empty_value']);
        $this->assertNull($view['month']->vars['empty_value']);
        $this->assertNull($view['day']->vars['empty_value']);
    }

    public function testPassEmptyValueAsString()
    {
        $form = $this->factory->create('date', null, array(
            'empty_value' => 'Empty',
        ));

        $view = $form->createView();
        $this->assertSame('Empty', $view['year']->vars['empty_value']);
        $this->assertSame('Empty', $view['month']->vars['empty_value']);
        $this->assertSame('Empty', $view['day']->vars['empty_value']);
    }

    public function testPassEmptyValueAsArray()
    {
        $form = $this->factory->create('date', null, array(
            'empty_value' => array(
                'year' => 'Empty year',
                'month' => 'Empty month',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['empty_value']);
        $this->assertSame('Empty month', $view['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['day']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddEmptyIfNotRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => false,
            'empty_value' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['empty_value']);
        $this->assertSame('', $view['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['day']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddNullIfRequired()
    {
        $form = $this->factory->create('date', null, array(
            'required' => true,
            'empty_value' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
            ),
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['year']->vars['empty_value']);
        $this->assertNull($view['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['day']->vars['empty_value']);
    }

    public function testPassHtml5TypeIfSingleTextAndHtml5Format()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertSame('date', $view->vars['type']);
    }

    public function testDontPassHtml5TypeIfNotHtml5Format()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'single_text',
            'format' => \IntlDateFormatter::MEDIUM,
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function testDontPassHtml5TypeIfNotSingleText()
    {
        $form = $this->factory->create('date', null, array(
            'widget' => 'text',
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function provideCompoundWidgets()
    {
        return array(
            array('text'),
            array('choice'),
        );
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testYearErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['year']->addError($error);

        $this->assertSame(array(), $form['year']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testMonthErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['month']->addError($error);

        $this->assertSame(array(), $form['month']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testDayErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('date', null, array(
            'widget' => $widget,
        ));
        $form['day']->addError($error);

        $this->assertSame(array(), $form['day']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    public function testYearsFor32BitsMachines()
    {
        if (4 !== PHP_INT_SIZE) {
            $this->markTestSkipped(
                'PHP must be compiled in 32 bit mode to run this test');
        }

        $form = $this->factory->create('date', null, array(
            'years' => range(1900, 2040),
        ));

        $view = $form->createView();

        $listChoices = array();
        foreach (range(1902, 2037) as $y) {
            $listChoices[] = new ChoiceView($y, $y, $y);
        }

        $this->assertEquals($listChoices, $view['year']->vars['choices']);
    }
}
PK.1[vzw�LLLForm/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Form;

class CollectionTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    public function testContainsNoChildByDefault()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
        ));

        $this->assertCount(0, $form);
    }

    public function testSetDataAdjustsSize()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
            'options' => array(
                'max_length' => 20,
            ),
        ));
        $form->setData(array('foo@foo.com', 'foo@bar.com'));

        $this->assertInstanceOf('Symfony\Component\Form\Form', $form[0]);
        $this->assertInstanceOf('Symfony\Component\Form\Form', $form[1]);
        $this->assertCount(2, $form);
        $this->assertEquals('foo@foo.com', $form[0]->getData());
        $this->assertEquals('foo@bar.com', $form[1]->getData());
        $this->assertEquals(20, $form[0]->getConfig()->getOption('max_length'));
        $this->assertEquals(20, $form[1]->getConfig()->getOption('max_length'));

        $form->setData(array('foo@baz.com'));
        $this->assertInstanceOf('Symfony\Component\Form\Form', $form[0]);
        $this->assertFalse(isset($form[1]));
        $this->assertCount(1, $form);
        $this->assertEquals('foo@baz.com', $form[0]->getData());
        $this->assertEquals(20, $form[0]->getConfig()->getOption('max_length'));
    }

    public function testThrowsExceptionIfObjectIsNotTraversable()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
        ));
        $this->setExpectedException('Symfony\Component\Form\Exception\UnexpectedTypeException');
        $form->setData(new \stdClass());
    }

    public function testNotResizedIfSubmittedWithMissingData()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
        ));
        $form->setData(array('foo@foo.com', 'bar@bar.com'));
        $form->submit(array('foo@bar.com'));

        $this->assertTrue($form->has('0'));
        $this->assertTrue($form->has('1'));
        $this->assertEquals('foo@bar.com', $form[0]->getData());
        $this->assertEquals('', $form[1]->getData());
    }

    public function testResizedDownIfSubmittedWithMissingDataAndAllowDelete()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
            'allow_delete' => true,
        ));
        $form->setData(array('foo@foo.com', 'bar@bar.com'));
        $form->submit(array('foo@foo.com'));

        $this->assertTrue($form->has('0'));
        $this->assertFalse($form->has('1'));
        $this->assertEquals('foo@foo.com', $form[0]->getData());
        $this->assertEquals(array('foo@foo.com'), $form->getData());
    }

    public function testNotResizedIfSubmittedWithExtraData()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
        ));
        $form->setData(array('foo@bar.com'));
        $form->submit(array('foo@foo.com', 'bar@bar.com'));

        $this->assertTrue($form->has('0'));
        $this->assertFalse($form->has('1'));
        $this->assertEquals('foo@foo.com', $form[0]->getData());
    }

    public function testResizedUpIfSubmittedWithExtraDataAndAllowAdd()
    {
        $form = $this->factory->create('collection', null, array(
            'type' => 'text',
            'allow_add' => true,
        ));
        $form->setData(array('foo@bar.com'));
        $form->submit(array('foo@bar.com', 'bar@bar.com'));

        $this->assertTrue($form->has('0'));
        $this->assertTrue($form->has('1'));
        $this->assertEquals('foo@bar.com', $form[0]->getData());
        $this->assertEquals('bar@bar.com', $form[1]->getData());
        $this->assertEquals(array('foo@bar.com', 'bar@bar.com'), $form->getData());
    }

    public function testAllowAddButNoPrototype()
    {
        $form = $this->factory->create('collection', null, array(
            'type'      => 'form',
            'allow_add' => true,
            'prototype' => false,
        ));

        $this->assertFalse($form->has('__name__'));
    }

    public function testPrototypeMultipartPropagation()
    {
        $form = $this->factory
            ->create('collection', null, array(
                'type'      => 'file',
                'allow_add' => true,
                'prototype' => true,
            ))
        ;

        $this->assertTrue($form->createView()->vars['multipart']);
    }

    public function testGetDataDoesNotContainsPrototypeNameBeforeDataAreSet()
    {
        $form = $this->factory->create('collection', array(), array(
            'type'      => 'file',
            'prototype' => true,
            'allow_add' => true,
        ));

        $data = $form->getData();
        $this->assertFalse(isset($data['__name__']));
    }

    public function testGetDataDoesNotContainsPrototypeNameAfterDataAreSet()
    {
        $form = $this->factory->create('collection', array(), array(
            'type'      => 'file',
            'allow_add' => true,
            'prototype' => true,
        ));

        $form->setData(array('foobar.png'));
        $data = $form->getData();
        $this->assertFalse(isset($data['__name__']));
    }

    public function testPrototypeNameOption()
    {
        $form = $this->factory->create('collection', null, array(
            'type'      => 'form',
            'prototype' => true,
            'allow_add' => true,
        ));

        $this->assertSame('__name__', $form->getConfig()->getAttribute('prototype')->getName(), '__name__ is the default');

        $form = $this->factory->create('collection', null, array(
            'type'           => 'form',
            'prototype'      => true,
            'allow_add'      => true,
            'prototype_name' => '__test__',
        ));

        $this->assertSame('__test__', $form->getConfig()->getAttribute('prototype')->getName());
    }

    public function testPrototypeDefaultLabel()
    {
        $form = $this->factory->create('collection', array(), array(
            'type'      => 'file',
            'allow_add' => true,
            'prototype' => true,
            'prototype_name' => '__test__',
        ));

        $this->assertSame('__test__label__', $form->createView()->vars['prototype']->vars['label']);
    }
}
PK.1[�(��__JForm/Symfony/Component/Form/Tests/Extension/Core/Type/PasswordTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

class PasswordTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    public function testEmptyIfNotSubmitted()
    {
        $form = $this->factory->create('password');
        $form->setData('pAs5w0rd');
        $view = $form->createView();

        $this->assertSame('', $view->vars['value']);
    }

    public function testEmptyIfSubmitted()
    {
        $form = $this->factory->create('password');
        $form->submit('pAs5w0rd');
        $view = $form->createView();

        $this->assertSame('', $view->vars['value']);
    }

    public function testNotEmptyIfSubmittedAndNotAlwaysEmpty()
    {
        $form = $this->factory->create('password', null, array('always_empty' => false));
        $form->submit('pAs5w0rd');
        $view = $form->createView();

        $this->assertSame('pAs5w0rd', $view->vars['value']);
    }

    public function testNotTrimmed()
    {
        $form = $this->factory->create('password', null);
        $form->submit(' pAs5w0rd ');
        $data = $form->getData();

        $this->assertSame(' pAs5w0rd ', $data);
    }
}
PK.1[x�=�t=t=JForm/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;

class DateTimeTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testSubmitDateTime()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
            'input' => 'datetime',
        ));

        $form->submit(array(
            'date' => array(
                'day' => '2',
                'month' => '6',
                'year' => '2010',
            ),
            'time' => array(
                'hour' => '3',
                'minute' => '4',
            ),
        ));

        $dateTime = new \DateTime('2010-06-02 03:04:00 UTC');

        $this->assertDateTimeEquals($dateTime, $form->getData());
    }

    public function testSubmitString()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
        ));

        $form->submit(array(
            'date' => array(
                'day' => '2',
                'month' => '6',
                'year' => '2010',
            ),
            'time' => array(
                'hour' => '3',
                'minute' => '4',
            ),
        ));

        $this->assertEquals('2010-06-02 03:04:00', $form->getData());
    }

    public function testSubmitTimestamp()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'timestamp',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
        ));

        $form->submit(array(
            'date' => array(
                'day' => '2',
                'month' => '6',
                'year' => '2010',
            ),
            'time' => array(
                'hour' => '3',
                'minute' => '4',
            ),
        ));

        $dateTime = new \DateTime('2010-06-02 03:04:00 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
    }

    public function testSubmitWithoutMinutes()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
            'input' => 'datetime',
            'with_minutes' => false,
        ));

        $form->setData(new \DateTime('2010-06-02 03:04:05 UTC'));

        $input = array(
            'date' => array(
                'day' => '2',
                'month' => '6',
                'year' => '2010',
            ),
            'time' => array(
                'hour' => '3',
            ),
        );

        $form->submit($input);

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 03:00:00 UTC'), $form->getData());
    }

    public function testSubmitWithSeconds()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
            'input' => 'datetime',
            'with_seconds' => true,
        ));

        $form->setData(new \DateTime('2010-06-02 03:04:05 UTC'));

        $input = array(
            'date' => array(
                'day' => '2',
                'month' => '6',
                'year' => '2010',
            ),
            'time' => array(
                'hour' => '3',
                'minute' => '4',
                'second' => '5',
            ),
        );

        $form->submit($input);

        $this->assertDateTimeEquals(new \DateTime('2010-06-02 03:04:05 UTC'), $form->getData());
    }

    public function testSubmitDifferentTimezones()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'date_widget' => 'choice',
            'time_widget' => 'choice',
            'input' => 'string',
            'with_seconds' => true,
        ));

        $dateTime = new \DateTime('2010-06-02 03:04:05 Pacific/Tahiti');

        $form->submit(array(
            'date' => array(
                'day' => (int) $dateTime->format('d'),
                'month' => (int) $dateTime->format('m'),
                'year' => (int) $dateTime->format('Y'),
            ),
            'time' => array(
                'hour' => (int) $dateTime->format('H'),
                'minute' => (int) $dateTime->format('i'),
                'second' => (int) $dateTime->format('s'),
            ),
        ));

        $dateTime->setTimezone(new \DateTimeZone('America/New_York'));

        $this->assertEquals($dateTime->format('Y-m-d H:i:s'), $form->getData());
    }

    public function testSubmitDifferentTimezonesDateTime()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Pacific/Tahiti',
            'widget' => 'single_text',
            'input' => 'datetime',
        ));

        $outputTime = new \DateTime('2010-06-02 03:04:00 Pacific/Tahiti');

        $form->submit('2010-06-02T03:04:00-10:00');

        $outputTime->setTimezone(new \DateTimeZone('America/New_York'));

        $this->assertDateTimeEquals($outputTime, $form->getData());
        $this->assertEquals('2010-06-02T03:04:00-10:00', $form->getViewData());
    }

    public function testSubmitStringSingleText()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $form->submit('2010-06-02T03:04:00Z');

        $this->assertEquals('2010-06-02 03:04:00', $form->getData());
        $this->assertEquals('2010-06-02T03:04:00Z', $form->getViewData());
    }

    public function testSubmitStringSingleTextWithSeconds()
    {
        $form = $this->factory->create('datetime', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
            'widget' => 'single_text',
            'with_seconds' => true,
        ));

        $form->submit('2010-06-02T03:04:05Z');

        $this->assertEquals('2010-06-02 03:04:05', $form->getData());
        $this->assertEquals('2010-06-02T03:04:05Z', $form->getViewData());
    }

    public function testSubmitDifferentPattern()
    {
        $form = $this->factory->create('datetime', null, array(
            'date_format' => 'MM*yyyy*dd',
            'date_widget' => 'single_text',
            'time_widget' => 'single_text',
            'input' => 'datetime',
        ));

        $dateTime = new \DateTime('2010-06-02 03:04');

        $form->submit(array(
            'date' => '06*2010*02',
            'time' => '03:04',
        ));

        $this->assertDateTimeEquals($dateTime, $form->getData());
    }

    // Bug fix
    public function testInitializeWithDateTime()
    {
        // Throws an exception if "data_class" option is not explicitly set
        // to null in the type
        $this->factory->create('datetime', new \DateTime());
    }

    public function testSingleTextWidgetShouldUseTheRightInputType()
    {
        $form = $this->factory->create('datetime', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertEquals('datetime', $view->vars['type']);
    }

    public function testPassDefaultEmptyValueToViewIfNotRequired()
    {
        $form = $this->factory->create('datetime', null, array(
            'required' => false,
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('', $view['date']['year']->vars['empty_value']);
        $this->assertSame('', $view['date']['month']->vars['empty_value']);
        $this->assertSame('', $view['date']['day']->vars['empty_value']);
        $this->assertSame('', $view['time']['hour']->vars['empty_value']);
        $this->assertSame('', $view['time']['minute']->vars['empty_value']);
        $this->assertSame('', $view['time']['second']->vars['empty_value']);
    }

    public function testPassNoEmptyValueToViewIfRequired()
    {
        $form = $this->factory->create('datetime', null, array(
            'required' => true,
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertNull($view['date']['year']->vars['empty_value']);
        $this->assertNull($view['date']['month']->vars['empty_value']);
        $this->assertNull($view['date']['day']->vars['empty_value']);
        $this->assertNull($view['time']['hour']->vars['empty_value']);
        $this->assertNull($view['time']['minute']->vars['empty_value']);
        $this->assertNull($view['time']['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsString()
    {
        $form = $this->factory->create('datetime', null, array(
            'empty_value' => 'Empty',
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty', $view['date']['year']->vars['empty_value']);
        $this->assertSame('Empty', $view['date']['month']->vars['empty_value']);
        $this->assertSame('Empty', $view['date']['day']->vars['empty_value']);
        $this->assertSame('Empty', $view['time']['hour']->vars['empty_value']);
        $this->assertSame('Empty', $view['time']['minute']->vars['empty_value']);
        $this->assertSame('Empty', $view['time']['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsArray()
    {
        $form = $this->factory->create('datetime', null, array(
            'empty_value' => array(
                'year' => 'Empty year',
                'month' => 'Empty month',
                'day' => 'Empty day',
                'hour' => 'Empty hour',
                'minute' => 'Empty minute',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['date']['year']->vars['empty_value']);
        $this->assertSame('Empty month', $view['date']['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['date']['day']->vars['empty_value']);
        $this->assertSame('Empty hour', $view['time']['hour']->vars['empty_value']);
        $this->assertSame('Empty minute', $view['time']['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['time']['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddEmptyIfNotRequired()
    {
        $form = $this->factory->create('datetime', null, array(
            'required' => false,
            'empty_value' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
                'hour' => 'Empty hour',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['date']['year']->vars['empty_value']);
        $this->assertSame('', $view['date']['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['date']['day']->vars['empty_value']);
        $this->assertSame('Empty hour', $view['time']['hour']->vars['empty_value']);
        $this->assertSame('', $view['time']['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['time']['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddNullIfRequired()
    {
        $form = $this->factory->create('datetime', null, array(
            'required' => true,
            'empty_value' => array(
                'year' => 'Empty year',
                'day' => 'Empty day',
                'hour' => 'Empty hour',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty year', $view['date']['year']->vars['empty_value']);
        $this->assertNull($view['date']['month']->vars['empty_value']);
        $this->assertSame('Empty day', $view['date']['day']->vars['empty_value']);
        $this->assertSame('Empty hour', $view['time']['hour']->vars['empty_value']);
        $this->assertNull($view['time']['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['time']['second']->vars['empty_value']);
    }

    public function testPassHtml5TypeIfSingleTextAndHtml5Format()
    {
        $form = $this->factory->create('datetime', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertSame('datetime', $view->vars['type']);
    }

    public function testDontPassHtml5TypeIfNotHtml5Format()
    {
        $form = $this->factory->create('datetime', null, array(
            'widget' => 'single_text',
            'format' => 'yyyy-MM-dd HH:mm',
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function testDontPassHtml5TypeIfNotSingleText()
    {
        $form = $this->factory->create('datetime', null, array(
            'widget' => 'text',
        ));

        $view = $form->createView();
        $this->assertFalse(isset($view->vars['type']));
    }

    public function testDateTypeChoiceErrorsBubbleUp()
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('datetime', null);

        $form['date']->addError($error);

        $this->assertSame(array(), $form['date']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    public function testDateTypeSingleTextErrorsBubbleUp()
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('datetime', null, array(
            'date_widget' => 'single_text'
        ));

        $form['date']->addError($error);

        $this->assertSame(array(), $form['date']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    public function testTimeTypeChoiceErrorsBubbleUp()
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('datetime', null);

        $form['time']->addError($error);

        $this->assertSame(array(), $form['time']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    public function testTimeTypeSingleTextErrorsBubbleUp()
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('datetime', null, array(
            'time_widget' => 'single_text'
        ));

        $form['time']->addError($error);

        $this->assertSame(array(), $form['time']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

}
PK.1[P�!���EForm/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

class UrlTypeTest extends TypeTestCase
{
    public function testSubmitAddsDefaultProtocolIfNoneIsIncluded()
    {
        $form = $this->factory->create('url', 'name');

        $form->submit('www.domain.com');

        $this->assertSame('http://www.domain.com', $form->getData());
        $this->assertSame('http://www.domain.com', $form->getViewData());
    }

    public function testSubmitAddsNoDefaultProtocolIfAlreadyIncluded()
    {
        $form = $this->factory->create('url', null, array(
            'default_protocol' => 'http',
        ));

        $form->submit('ftp://www.domain.com');

        $this->assertSame('ftp://www.domain.com', $form->getData());
        $this->assertSame('ftp://www.domain.com', $form->getViewData());
    }

    public function testSubmitAddsNoDefaultProtocolIfEmpty()
    {
        $form = $this->factory->create('url', null, array(
            'default_protocol' => 'http',
        ));

        $form->submit('');

        $this->assertNull($form->getData());
        $this->assertSame('', $form->getViewData());
    }

    public function testSubmitAddsNoDefaultProtocolIfSetToNull()
    {
        $form = $this->factory->create('url', null, array(
            'default_protocol' => null,
        ));

        $form->submit('www.domain.com');

        $this->assertSame('www.domain.com', $form->getData());
        $this->assertSame('www.domain.com', $form->getViewData());
    }
}
PK.1[X�:::FForm/Symfony/Component/Form/Tests/Extension/Core/Type/TypeTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Test\TypeTestCase as BaseTypeTestCase;

/**
 * @deprecated Deprecated since version 2.3, to be removed in 3.0. Use Symfony\Component\Form\Test\TypeTestCase instead.
 */
abstract class TypeTestCase extends BaseTypeTestCase
{
}
PK.1[����IForm/Symfony/Component/Form/Tests/Extension/Core/Type/CountryTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Intl\Util\IntlTestHelper;

class CountryTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testCountriesAreSelectable()
    {
        $form = $this->factory->create('country');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        // Don't check objects for identity
        $this->assertContains(new ChoiceView('DE', 'DE', 'Germany'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('GB', 'GB', 'United Kingdom'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('US', 'US', 'United States'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('FR', 'FR', 'France'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('MY', 'MY', 'Malaysia'), $choices, '', false, false);
    }

    public function testUnknownCountryIsNotIncluded()
    {
        $form = $this->factory->create('country', 'country');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        foreach ($choices as $choice) {
            if ('ZZ' === $choice->value) {
                $this->fail('Should not contain choice "ZZ"');
            }
        }
    }
}
PK.1[�_*G��SForm/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypePerformanceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Test\FormPerformanceTestCase;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ChoiceTypePerformanceTest extends FormPerformanceTestCase
{
    /**
     * This test case is realistic in collection forms where each
     * row contains the same choice field.
     *
     * @group benchmark
     */
    public function testSameChoiceFieldCreatedMultipleTimes()
    {
        $this->setMaxRunningTime(1);
        $choices = range(1, 300);

        for ($i = 0; $i < 100; ++$i) {
            $this->factory->create('choice', rand(1, 400), array(
                'choices' => $choices,
            ));
        }
    }
}
PK.1[�{MK��FForm/Symfony/Component/Form/Tests/Extension/Core/Type/BaseTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class BaseTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    public function testPassDisabledAsOption()
    {
        $form = $this->factory->create($this->getTestedType(), null, array('disabled' => true));

        $this->assertTrue($form->isDisabled());
    }

    public function testPassIdAndNameToView()
    {
        $view = $this->factory->createNamed('name', $this->getTestedType())
            ->createView();

        $this->assertEquals('name', $view->vars['id']);
        $this->assertEquals('name', $view->vars['name']);
        $this->assertEquals('name', $view->vars['full_name']);
    }

    public function testStripLeadingUnderscoresAndDigitsFromId()
    {
        $view = $this->factory->createNamed('_09name', $this->getTestedType())
            ->createView();

        $this->assertEquals('name', $view->vars['id']);
        $this->assertEquals('_09name', $view->vars['name']);
        $this->assertEquals('_09name', $view->vars['full_name']);
    }

    public function testPassIdAndNameToViewWithParent()
    {
        $view = $this->factory->createNamedBuilder('parent', 'form')
            ->add('child', $this->getTestedType())
            ->getForm()
            ->createView();

        $this->assertEquals('parent_child', $view['child']->vars['id']);
        $this->assertEquals('child', $view['child']->vars['name']);
        $this->assertEquals('parent[child]', $view['child']->vars['full_name']);
    }

    public function testPassIdAndNameToViewWithGrandParent()
    {
        $builder = $this->factory->createNamedBuilder('parent', 'form')
            ->add('child', 'form');
        $builder->get('child')->add('grand_child', $this->getTestedType());
        $view = $builder->getForm()->createView();

        $this->assertEquals('parent_child_grand_child', $view['child']['grand_child']->vars['id']);
        $this->assertEquals('grand_child', $view['child']['grand_child']->vars['name']);
        $this->assertEquals('parent[child][grand_child]', $view['child']['grand_child']->vars['full_name']);
    }

    public function testPassTranslationDomainToView()
    {
        $form = $this->factory->create($this->getTestedType(), null, array(
            'translation_domain' => 'domain',
        ));
        $view = $form->createView();

        $this->assertSame('domain', $view->vars['translation_domain']);
    }

    public function testInheritTranslationDomainFromParent()
    {
        $view = $this->factory
            ->createNamedBuilder('parent', 'form', null, array(
                'translation_domain' => 'domain',
            ))
            ->add('child', $this->getTestedType())
            ->getForm()
            ->createView();

        $this->assertEquals('domain', $view['child']->vars['translation_domain']);
    }

    public function testPreferOwnTranslationDomain()
    {
        $view = $this->factory
            ->createNamedBuilder('parent', 'form', null, array(
                'translation_domain' => 'parent_domain',
            ))
            ->add('child', $this->getTestedType(), array(
                'translation_domain' => 'domain',
            ))
            ->getForm()
            ->createView();

        $this->assertEquals('domain', $view['child']->vars['translation_domain']);
    }

    public function testDefaultTranslationDomain()
    {
        $view = $this->factory->createNamedBuilder('parent', 'form')
            ->add('child', $this->getTestedType())
            ->getForm()
            ->createView();

        $this->assertEquals('messages', $view['child']->vars['translation_domain']);
    }

    public function testPassLabelToView()
    {
        $form = $this->factory->createNamed('__test___field', $this->getTestedType(), null, array('label' => 'My label'));
        $view = $form->createView();

        $this->assertSame('My label', $view->vars['label']);
    }

    public function testPassMultipartFalseToView()
    {
        $form = $this->factory->create($this->getTestedType());
        $view = $form->createView();

        $this->assertFalse($view->vars['multipart']);
    }

    abstract protected function getTestedType();
}
PK.1[ސ/���JForm/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class TimezoneTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    public function testTimezonesAreSelectable()
    {
        $form = $this->factory->create('timezone');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        $this->assertArrayHasKey('Africa', $choices);
        $this->assertContains(new ChoiceView('Africa/Kinshasa', 'Africa/Kinshasa', 'Kinshasa'), $choices['Africa'], '', false, false);

        $this->assertArrayHasKey('America', $choices);
        $this->assertContains(new ChoiceView('America/New_York', 'America/New_York', 'New York'), $choices['America'], '', false, false);
    }
}
PK.1[dwҢSJSJFForm/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\FormError;
use Symfony\Component\Intl\Util\IntlTestHelper;

class TimeTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testSubmitDateTime()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'datetime',
        ));

        $input = array(
            'hour' => '3',
            'minute' => '4',
        );

        $form->submit($input);

        $dateTime = new \DateTime('1970-01-01 03:04:00 UTC');

        $this->assertEquals($dateTime, $form->getData());
        $this->assertEquals($input, $form->getViewData());
    }

    public function testSubmitString()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
        ));

        $input = array(
            'hour' => '3',
            'minute' => '4',
        );

        $form->submit($input);

        $this->assertEquals('03:04:00', $form->getData());
        $this->assertEquals($input, $form->getViewData());
    }

    public function testSubmitTimestamp()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'timestamp',
        ));

        $input = array(
            'hour' => '3',
            'minute' => '4',
        );

        $form->submit($input);

        $dateTime = new \DateTime('1970-01-01 03:04:00 UTC');

        $this->assertEquals($dateTime->format('U'), $form->getData());
        $this->assertEquals($input, $form->getViewData());
    }

    public function testSubmitArray()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'array',
        ));

        $input = array(
            'hour' => '3',
            'minute' => '4',
        );

        $form->submit($input);

        $this->assertEquals($input, $form->getData());
        $this->assertEquals($input, $form->getViewData());
    }

    public function testSubmitDatetimeSingleText()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'datetime',
            'widget' => 'single_text',
        ));

        $form->submit('03:04');

        $this->assertEquals(new \DateTime('1970-01-01 03:04:00 UTC'), $form->getData());
        $this->assertEquals('03:04', $form->getViewData());
    }

    public function testSubmitDatetimeSingleTextWithoutMinutes()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'datetime',
            'widget' => 'single_text',
            'with_minutes' => false,
        ));

        $form->submit('03');

        $this->assertEquals(new \DateTime('1970-01-01 03:00:00 UTC'), $form->getData());
        $this->assertEquals('03', $form->getViewData());
    }

    public function testSubmitArraySingleText()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'array',
            'widget' => 'single_text',
        ));

        $data = array(
            'hour' => '3',
            'minute' => '4',
        );

        $form->submit('03:04');

        $this->assertEquals($data, $form->getData());
        $this->assertEquals('03:04', $form->getViewData());
    }

    public function testSubmitArraySingleTextWithoutMinutes()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'array',
            'widget' => 'single_text',
            'with_minutes' => false,
        ));

        $data = array(
            'hour' => '3',
        );

        $form->submit('03');

        $this->assertEquals($data, $form->getData());
        $this->assertEquals('03', $form->getViewData());
    }

    public function testSubmitArraySingleTextWithSeconds()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'array',
            'widget' => 'single_text',
            'with_seconds' => true,
        ));

        $data = array(
            'hour' => '3',
            'minute' => '4',
            'second' => '5',
        );

        $form->submit('03:04:05');

        $this->assertEquals($data, $form->getData());
        $this->assertEquals('03:04:05', $form->getViewData());
    }

    public function testSubmitStringSingleText()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
            'widget' => 'single_text',
        ));

        $form->submit('03:04');

        $this->assertEquals('03:04:00', $form->getData());
        $this->assertEquals('03:04', $form->getViewData());
    }

    public function testSubmitStringSingleTextWithoutMinutes()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'string',
            'widget' => 'single_text',
            'with_minutes' => false,
        ));

        $form->submit('03');

        $this->assertEquals('03:00:00', $form->getData());
        $this->assertEquals('03', $form->getViewData());
    }

    public function testSetDataWithoutMinutes()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'datetime',
            'with_minutes' => false,
        ));

        $form->setData(new \DateTime('03:04:05 UTC'));

        $this->assertEquals(array('hour' => 3), $form->getViewData());
    }

    public function testSetDataWithSeconds()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'UTC',
            'view_timezone' => 'UTC',
            'input' => 'datetime',
            'with_seconds' => true,
        ));

        $form->setData(new \DateTime('03:04:05 UTC'));

        $this->assertEquals(array('hour' => 3, 'minute' => 4, 'second' => 5), $form->getViewData());
    }

    public function testSetDataDifferentTimezones()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Asia/Hong_Kong',
            'input' => 'string',
            'with_seconds' => true,
        ));

        $dateTime = new \DateTime('2013-01-01 12:04:05');
        $dateTime->setTimezone(new \DateTimeZone('America/New_York'));

        $form->setData($dateTime->format('H:i:s'));

        $outputTime = clone $dateTime;
        $outputTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $displayedData = array(
            'hour' => (int) $outputTime->format('H'),
            'minute' => (int) $outputTime->format('i'),
            'second' => (int) $outputTime->format('s')
        );

        $this->assertEquals($displayedData, $form->getViewData());
    }

    public function testSetDataDifferentTimezonesDateTime()
    {
        $form = $this->factory->create('time', null, array(
            'model_timezone' => 'America/New_York',
            'view_timezone' => 'Asia/Hong_Kong',
            'input' => 'datetime',
            'with_seconds' => true,
        ));

        $dateTime = new \DateTime('12:04:05');
        $dateTime->setTimezone(new \DateTimeZone('America/New_York'));

        $form->setData($dateTime);

        $outputTime = clone $dateTime;
        $outputTime->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $displayedData = array(
            'hour' => (int) $outputTime->format('H'),
            'minute' => (int) $outputTime->format('i'),
            'second' => (int) $outputTime->format('s')
        );

        $this->assertDateTimeEquals($dateTime, $form->getData());
        $this->assertEquals($displayedData, $form->getViewData());
    }

    public function testHoursOption()
    {
        $form = $this->factory->create('time', null, array(
            'hours' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['hour']->vars['choices']);
    }

    public function testIsMinuteWithinRangeReturnsTrueIfWithin()
    {
        $form = $this->factory->create('time', null, array(
            'minutes' => array(6, 7),
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['minute']->vars['choices']);
    }

    public function testIsSecondWithinRangeReturnsTrueIfWithin()
    {
        $form = $this->factory->create('time', null, array(
            'seconds' => array(6, 7),
            'with_seconds' => true,
        ));

        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('6', '6', '06'),
            new ChoiceView('7', '7', '07'),
        ), $view['second']->vars['choices']);
    }

    public function testIsPartiallyFilledReturnsFalseIfCompletelyEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
        ));

        $form->submit(array(
            'hour' => '',
            'minute' => '',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfCompletelyEmptyWithSeconds()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
            'with_seconds' => true,
        ));

        $form->submit(array(
            'hour' => '',
            'minute' => '',
            'second' => '',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfCompletelyFilled()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
        ));

        $form->submit(array(
            'hour' => '0',
            'minute' => '0',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsFalseIfCompletelyFilledWithSeconds()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
            'with_seconds' => true,
        ));

        $form->submit(array(
            'hour' => '0',
            'minute' => '0',
            'second' => '0',
        ));

        $this->assertFalse($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsTrueIfChoiceAndHourEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
            'with_seconds' => true,
        ));

        $form->submit(array(
            'hour' => '',
            'minute' => '0',
            'second' => '0',
        ));

        $this->assertTrue($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsTrueIfChoiceAndMinuteEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
            'with_seconds' => true,
        ));

        $form->submit(array(
            'hour' => '0',
            'minute' => '',
            'second' => '0',
        ));

        $this->assertTrue($form->isPartiallyFilled());
    }

    public function testIsPartiallyFilledReturnsTrueIfChoiceAndSecondsEmpty()
    {
        $this->markTestIncomplete('Needs to be reimplemented using validators');

        $form = $this->factory->create('time', null, array(
            'widget' => 'choice',
            'with_seconds' => true,
        ));

        $form->submit(array(
            'hour' => '0',
            'minute' => '0',
            'second' => '',
        ));

        $this->assertTrue($form->isPartiallyFilled());
    }

    // Bug fix
    public function testInitializeWithDateTime()
    {
        // Throws an exception if "data_class" option is not explicitly set
        // to null in the type
        $this->factory->create('time', new \DateTime());
    }

    public function testSingleTextWidgetShouldUseTheRightInputType()
    {
        $form = $this->factory->create('time', null, array(
            'widget' => 'single_text',
        ));

        $view = $form->createView();
        $this->assertEquals('time', $view->vars['type']);
    }

    public function testPassDefaultEmptyValueToViewIfNotRequired()
    {
        $form = $this->factory->create('time', null, array(
            'required' => false,
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('', $view['hour']->vars['empty_value']);
        $this->assertSame('', $view['minute']->vars['empty_value']);
        $this->assertSame('', $view['second']->vars['empty_value']);
    }

    public function testPassNoEmptyValueToViewIfRequired()
    {
        $form = $this->factory->create('time', null, array(
            'required' => true,
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertNull($view['hour']->vars['empty_value']);
        $this->assertNull($view['minute']->vars['empty_value']);
        $this->assertNull($view['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsString()
    {
        $form = $this->factory->create('time', null, array(
            'empty_value' => 'Empty',
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty', $view['hour']->vars['empty_value']);
        $this->assertSame('Empty', $view['minute']->vars['empty_value']);
        $this->assertSame('Empty', $view['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsArray()
    {
        $form = $this->factory->create('time', null, array(
            'empty_value' => array(
                'hour' => 'Empty hour',
                'minute' => 'Empty minute',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty hour', $view['hour']->vars['empty_value']);
        $this->assertSame('Empty minute', $view['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddEmptyIfNotRequired()
    {
        $form = $this->factory->create('time', null, array(
            'required' => false,
            'empty_value' => array(
                'hour' => 'Empty hour',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty hour', $view['hour']->vars['empty_value']);
        $this->assertSame('', $view['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['second']->vars['empty_value']);
    }

    public function testPassEmptyValueAsPartialArrayAddNullIfRequired()
    {
        $form = $this->factory->create('time', null, array(
            'required' => true,
            'empty_value' => array(
                'hour' => 'Empty hour',
                'second' => 'Empty second',
            ),
            'with_seconds' => true,
        ));

        $view = $form->createView();
        $this->assertSame('Empty hour', $view['hour']->vars['empty_value']);
        $this->assertNull($view['minute']->vars['empty_value']);
        $this->assertSame('Empty second', $view['second']->vars['empty_value']);
    }

    public function provideCompoundWidgets()
    {
        return array(
            array('text'),
            array('choice'),
        );
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testHourErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('time', null, array(
            'widget' => $widget,
        ));
        $form['hour']->addError($error);

        $this->assertSame(array(), $form['hour']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testMinuteErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('time', null, array(
            'widget' => $widget,
        ));
        $form['minute']->addError($error);

        $this->assertSame(array(), $form['minute']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    /**
     * @dataProvider provideCompoundWidgets
     */
    public function testSecondErrorsBubbleUp($widget)
    {
        $error = new FormError('Invalid!');
        $form = $this->factory->create('time', null, array(
            'widget' => $widget,
            'with_seconds' => true,
        ));
        $form['second']->addError($error);

        $this->assertSame(array(), $form['second']->getErrors());
        $this->assertSame(array($error), $form->getErrors());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\InvalidConfigurationException
     */
    public function testInitializeWithSecondsAndWithoutMinutes()
    {
        $this->factory->create('time', null, array(
            'with_minutes' => false,
            'with_seconds' => true,
        ));
    }
}
PK.1[/����GForm/Symfony/Component/Form/Tests/Extension/Core/Type/MoneyTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Intl\Util\IntlTestHelper;

class MoneyTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        // we test against different locales, so we need the full
        // implementation
        IntlTestHelper::requireFullIntl($this);

        parent::setUp();
    }

    public function testPassMoneyPatternToView()
    {
        \Locale::setDefault('de_DE');

        $form = $this->factory->create('money');
        $view = $form->createView();

        $this->assertSame('{{ widget }} €', $view->vars['money_pattern']);
    }

    public function testMoneyPatternWorksForYen()
    {
        \Locale::setDefault('en_US');

        $form = $this->factory->create('money', null, array('currency' => 'JPY'));
        $view = $form->createView();
        $this->assertTrue((Boolean) strstr($view->vars['money_pattern'], '¥'));
    }

    // https://github.com/symfony/symfony/issues/5458
    public function testPassDifferentPatternsForDifferentCurrencies()
    {
        \Locale::setDefault('de_DE');

        $form1 = $this->factory->create('money', null, array('currency' => 'GBP'));
        $form2 = $this->factory->create('money', null, array('currency' => 'EUR'));
        $view1 = $form1->createView();
        $view2 = $form2->createView();

        $this->assertSame('{{ widget }} £', $view1->vars['money_pattern']);
        $this->assertSame('{{ widget }} €', $view2->vars['money_pattern']);
    }
}
PK.1[���J��HForm/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Intl\Util\IntlTestHelper;

class NumberTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        parent::setUp();

        // we test against "de_DE", so we need the full implementation
        IntlTestHelper::requireFullIntl($this);

        \Locale::setDefault('de_DE');
    }

    public function testDefaultFormatting()
    {
        $form = $this->factory->create('number');
        $form->setData('12345.67890');
        $view = $form->createView();

        $this->assertSame('12345,679', $view->vars['value']);
    }

    public function testDefaultFormattingWithGrouping()
    {
        $form = $this->factory->create('number', null, array('grouping' => true));
        $form->setData('12345.67890');
        $view = $form->createView();

        $this->assertSame('12.345,679', $view->vars['value']);
    }

    public function testDefaultFormattingWithPrecision()
    {
        $form = $this->factory->create('number', null, array('precision' => 2));
        $form->setData('12345.67890');
        $view = $form->createView();

        $this->assertSame('12345,68', $view->vars['value']);
    }

    public function testDefaultFormattingWithRounding()
    {
        $form = $this->factory->create('number', null, array('precision' => 0, 'rounding_mode' => \NumberFormatter::ROUND_UP));
        $form->setData('12345.54321');
        $view = $form->createView();

        $this->assertSame('12346', $view->vars['value']);
    }
}
PK.1[�}�C%%HForm/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class SubmitTypeTest extends TypeTestCase
{
    public function testCreateSubmitButtonInstances()
    {
        $this->assertInstanceOf('Symfony\Component\Form\SubmitButton', $this->factory->create('submit'));
    }

    public function testNotClickedByDefault()
    {
        $button = $this->factory->create('submit');

        $this->assertFalse($button->isClicked());
    }

    public function testNotClickedIfSubmittedWithNull()
    {
        $button = $this->factory->create('submit');
        $button->submit(null);

        $this->assertFalse($button->isClicked());
    }

    public function testClickedIfSubmittedWithEmptyString()
    {
        $button = $this->factory->create('submit');
        $button->submit('');

        $this->assertTrue($button->isClicked());
    }

    public function testClickedIfSubmittedWithUnemptyString()
    {
        $button = $this->factory->create('submit');
        $button->submit('foo');

        $this->assertTrue($button->isClicked());
    }

    public function testSubmitCanBeAddedToForm()
    {
        $form = $this->factory
            ->createBuilder('form')
            ->getForm();

        $this->assertSame($form, $form->add('send', 'submit'));
    }
}
PK.1[�!]i00JForm/Symfony/Component/Form/Tests/Extension/Core/Type/CurrencyTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Intl\Util\IntlTestHelper;

class CurrencyTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testCurrenciesAreSelectable()
    {
        $form = $this->factory->create('currency');
        $view = $form->createView();
        $choices = $view->vars['choices'];

        $this->assertContains(new ChoiceView('EUR', 'EUR', 'Euro'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('USD', 'USD', 'US Dollar'), $choices, '', false, false);
        $this->assertContains(new ChoiceView('SIT', 'SIT', 'Slovenian Tolar'), $choices, '', false, false);
    }

}
PK.1[�IJ��JForm/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\CallbackTransformer;

class CheckboxTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    public function testDataIsFalseByDefault()
    {
        $form = $this->factory->create('checkbox');

        $this->assertFalse($form->getData());
        $this->assertFalse($form->getNormData());
        $this->assertNull($form->getViewData());
    }

    public function testPassValueToView()
    {
        $form = $this->factory->create('checkbox', null, array('value' => 'foobar'));
        $view = $form->createView();

        $this->assertEquals('foobar', $view->vars['value']);
    }

    public function testCheckedIfDataTrue()
    {
        $form = $this->factory->create('checkbox');
        $form->setData(true);
        $view = $form->createView();

        $this->assertTrue($view->vars['checked']);
    }

    public function testCheckedIfDataTrueWithEmptyValue()
    {
        $form = $this->factory->create('checkbox', null, array('value' => ''));
        $form->setData(true);
        $view = $form->createView();

        $this->assertTrue($view->vars['checked']);
    }

    public function testNotCheckedIfDataFalse()
    {
        $form = $this->factory->create('checkbox');
        $form->setData(false);
        $view = $form->createView();

        $this->assertFalse($view->vars['checked']);
    }

    public function testSubmitWithValueChecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => 'foobar',
        ));
        $form->submit('foobar');

        $this->assertTrue($form->getData());
        $this->assertEquals('foobar', $form->getViewData());
    }

    public function testSubmitWithRandomValueChecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => 'foobar',
        ));
        $form->submit('krixikraxi');

        $this->assertTrue($form->getData());
        $this->assertEquals('foobar', $form->getViewData());
    }

    public function testSubmitWithValueUnchecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => 'foobar',
        ));
        $form->submit(null);

        $this->assertFalse($form->getData());
        $this->assertNull($form->getViewData());
    }

    public function testSubmitWithEmptyValueChecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => '',
        ));
        $form->submit('');

        $this->assertTrue($form->getData());
        $this->assertSame('', $form->getViewData());
    }

    public function testSubmitWithEmptyValueUnchecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => '',
        ));
        $form->submit(null);

        $this->assertFalse($form->getData());
        $this->assertNull($form->getViewData());
    }

    public function testSubmitWithEmptyValueAndFalseUnchecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => '',
        ));
        $form->submit(false);

        $this->assertFalse($form->getData());
        $this->assertNull($form->getViewData());
    }

    public function testSubmitWithEmptyValueAndTrueChecked()
    {
        $form = $this->factory->create('checkbox', null, array(
            'value' => '',
        ));
        $form->submit(true);

        $this->assertTrue($form->getData());
        $this->assertSame('', $form->getViewData());
    }

    /**
     * @dataProvider provideCustomModelTransformerData
     */
    public function testCustomModelTransformer($data, $checked)
    {
        // present a binary status field as a checkbox
        $transformer = new CallbackTransformer(
            function ($value) {
                return 'checked' == $value;
            },
            function ($value) {
                return $value ? 'checked' : 'unchecked';
            }
        );

        $form = $this->factory->createBuilder('checkbox')
            ->addModelTransformer($transformer)
            ->getForm();

        $form->setData($data);
        $view = $form->createView();

        $this->assertSame($data, $form->getData());
        $this->assertSame($checked, $form->getNormData());
        $this->assertEquals($checked, $view->vars['checked']);
    }

    public function provideCustomModelTransformerData()
    {
        return array(
            array('checked', true),
            array('unchecked', false),
        );
    }
}
PK/1[�ñI��JForm/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

class RepeatedTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    protected $form;

    protected function setUp()
    {
        parent::setUp();

        $this->form = $this->factory->create('repeated', null, array(
            'type' => 'text',
        ));
        $this->form->setData(null);
    }

    public function testSetData()
    {
        $this->form->setData('foobar');

        $this->assertEquals('foobar', $this->form['first']->getData());
        $this->assertEquals('foobar', $this->form['second']->getData());
    }

    public function testSetOptions()
    {
        $form = $this->factory->create('repeated', null, array(
            'type'    => 'text',
            'options' => array('label' => 'Global'),
        ));

        $this->assertEquals('Global', $form['first']->getConfig()->getOption('label'));
        $this->assertEquals('Global', $form['second']->getConfig()->getOption('label'));
        $this->assertTrue($form['first']->isRequired());
        $this->assertTrue($form['second']->isRequired());
    }

    public function testSetOptionsPerChild()
    {
        $form = $this->factory->create('repeated', null, array(
            // the global required value cannot be overridden
            'type'           => 'text',
            'first_options'  => array('label' => 'Test', 'required' => false),
            'second_options' => array('label' => 'Test2')
        ));

        $this->assertEquals('Test', $form['first']->getConfig()->getOption('label'));
        $this->assertEquals('Test2', $form['second']->getConfig()->getOption('label'));
        $this->assertTrue($form['first']->isRequired());
        $this->assertTrue($form['second']->isRequired());
    }

    public function testSetRequired()
    {
        $form = $this->factory->create('repeated', null, array(
            'required' => false,
            'type'     => 'text',
        ));

        $this->assertFalse($form['first']->isRequired());
        $this->assertFalse($form['second']->isRequired());
    }

    public function testSetErrorBubblingToTrue()
    {
        $form = $this->factory->create('repeated', null, array(
            'error_bubbling' => true,
        ));

        $this->assertTrue($form->getConfig()->getOption('error_bubbling'));
        $this->assertTrue($form['first']->getConfig()->getOption('error_bubbling'));
        $this->assertTrue($form['second']->getConfig()->getOption('error_bubbling'));
    }

    public function testSetErrorBubblingToFalse()
    {
        $form = $this->factory->create('repeated', null, array(
            'error_bubbling' => false,
        ));

        $this->assertFalse($form->getConfig()->getOption('error_bubbling'));
        $this->assertFalse($form['first']->getConfig()->getOption('error_bubbling'));
        $this->assertFalse($form['second']->getConfig()->getOption('error_bubbling'));
    }

    public function testSetErrorBubblingIndividually()
    {
        $form = $this->factory->create('repeated', null, array(
            'error_bubbling' => true,
            'options' => array('error_bubbling' => false),
            'second_options' => array('error_bubbling' => true),
        ));

        $this->assertTrue($form->getConfig()->getOption('error_bubbling'));
        $this->assertFalse($form['first']->getConfig()->getOption('error_bubbling'));
        $this->assertTrue($form['second']->getConfig()->getOption('error_bubbling'));
    }

    public function testSetOptionsPerChildAndOverwrite()
    {
        $form = $this->factory->create('repeated', null, array(
            'type'           => 'text',
            'options'        => array('label' => 'Label'),
            'second_options' => array('label' => 'Second label')
        ));

        $this->assertEquals('Label', $form['first']->getConfig()->getOption('label'));
        $this->assertEquals('Second label', $form['second']->getConfig()->getOption('label'));
        $this->assertTrue($form['first']->isRequired());
        $this->assertTrue($form['second']->isRequired());
    }

    public function testSubmitUnequal()
    {
        $input = array('first' => 'foo', 'second' => 'bar');

        $this->form->submit($input);

        $this->assertEquals('foo', $this->form['first']->getViewData());
        $this->assertEquals('bar', $this->form['second']->getViewData());
        $this->assertFalse($this->form->isSynchronized());
        $this->assertEquals($input, $this->form->getViewData());
        $this->assertNull($this->form->getData());
    }

    public function testSubmitEqual()
    {
        $input = array('first' => 'foo', 'second' => 'foo');

        $this->form->submit($input);

        $this->assertEquals('foo', $this->form['first']->getViewData());
        $this->assertEquals('foo', $this->form['second']->getViewData());
        $this->assertTrue($this->form->isSynchronized());
        $this->assertEquals($input, $this->form->getViewData());
        $this->assertEquals('foo', $this->form->getData());
    }
}
PK/1[k�ƅ��IForm/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Intl\Util\IntlTestHelper;

class IntegerTypeTest extends TypeTestCase
{
    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        parent::setUp();
    }

    public function testSubmitCastsToInteger()
    {
        $form = $this->factory->create('integer');

        $form->submit('1.678');

        $this->assertSame(1, $form->getData());
        $this->assertSame('1', $form->getViewData());
    }
}
PK/1[I��E����HForm/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\Form\Extension\Core\ChoiceList\ObjectChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class ChoiceTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    private $choices = array(
        'a' => 'Bernhard',
        'b' => 'Fabien',
        'c' => 'Kris',
        'd' => 'Jon',
        'e' => 'Roman',
    );

    private $numericChoices = array(
        0 => 'Bernhard',
        1 => 'Fabien',
        2 => 'Kris',
        3 => 'Jon',
        4 => 'Roman',
    );

    private $objectChoices;

    protected $groupedChoices = array(
        'Symfony' => array(
            'a' => 'Bernhard',
            'b' => 'Fabien',
            'c' => 'Kris',
        ),
        'Doctrine' => array(
            'd' => 'Jon',
            'e' => 'Roman',
        )
    );

    protected function setUp()
    {
        parent::setUp();

        $this->objectChoices = array(
            (object) array('id' => 1, 'name' => 'Bernhard'),
            (object) array('id' => 2, 'name' => 'Fabien'),
            (object) array('id' => 3, 'name' => 'Kris'),
            (object) array('id' => 4, 'name' => 'Jon'),
            (object) array('id' => 5, 'name' => 'Roman'),
        );
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->objectChoices = null;
    }

    /**
     * @expectedException \PHPUnit_Framework_Error
     */
    public function testChoicesOptionExpectsArray()
    {
        $this->factory->create('choice', null, array(
            'choices' => new \ArrayObject(),
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testChoiceListOptionExpectsChoiceListInterface()
    {
        $this->factory->create('choice', null, array(
            'choice_list' => array('foo' => 'foo'),
        ));
    }

    public function testChoiceListAndChoicesCanBeEmpty()
    {
        $this->factory->create('choice');
    }

    public function testExpandedChoicesOptionsTurnIntoChildren()
    {
        $form = $this->factory->create('choice', null, array(
            'expanded'  => true,
            'choices'   => $this->choices,
        ));

        $this->assertCount(count($this->choices), $form, 'Each choice should become a new field');
    }

    public function testPlaceholderPresentOnNonRequiredExpandedSingleChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple'  => false,
            'expanded'  => true,
            'required'  => false,
            'choices'   => $this->choices,
        ));

        $this->assertTrue(isset($form['placeholder']));
        $this->assertCount(count($this->choices) + 1, $form, 'Each choice should become a new field');
    }

    public function testPlaceholderNotPresentIfRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple'  => false,
            'expanded'  => true,
            'required'  => true,
            'choices'   => $this->choices,
        ));

        $this->assertFalse(isset($form['placeholder']));
        $this->assertCount(count($this->choices), $form, 'Each choice should become a new field');
    }

    public function testPlaceholderNotPresentIfMultiple()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple'  => true,
            'expanded'  => true,
            'required'  => false,
            'choices'   => $this->choices,
        ));

        $this->assertFalse(isset($form['placeholder']));
        $this->assertCount(count($this->choices), $form, 'Each choice should become a new field');
    }

    public function testPlaceholderNotPresentIfEmptyChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple'  => false,
            'expanded'  => true,
            'required'  => false,
            'choices' => array(
                '' => 'Empty',
                1 => 'Not empty',
            ),
        ));

        $this->assertFalse(isset($form['placeholder']));
        $this->assertCount(2, $form, 'Each choice should become a new field');
    }

    public function testExpandedChoicesOptionsAreFlattened()
    {
        $form = $this->factory->create('choice', null, array(
            'expanded'  => true,
            'choices'   => $this->groupedChoices,
        ));

        $flattened = array();
        foreach ($this->groupedChoices as $choices) {
            $flattened = array_merge($flattened, array_keys($choices));
        }

        $this->assertCount($form->count(), $flattened, 'Each nested choice should become a new field, not the groups');

        foreach ($flattened as $value => $choice) {
            $this->assertTrue($form->has($value), 'Flattened choice is named after it\'s value');
        }
    }

    public function testExpandedCheckboxesAreNeverRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        foreach ($form as $child) {
            $this->assertFalse($child->isRequired());
        }
    }

    public function testExpandedRadiosAreRequiredIfChoiceChildIsRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        foreach ($form as $child) {
            $this->assertTrue($child->isRequired());
        }
    }

    public function testExpandedRadiosAreNotRequiredIfChoiceChildIsNotRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        foreach ($form as $child) {
            $this->assertFalse($child->isRequired());
        }
    }

    public function testSubmitSingleNonExpanded()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => false,
            'choices' => $this->choices,
        ));

        $form->submit('b');

        $this->assertEquals('b', $form->getData());
        $this->assertEquals('b', $form->getViewData());
    }

    public function testSubmitSingleNonExpandedInvalidChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => false,
            'choices' => $this->choices,
        ));

        $form->submit('foobar');

        $this->assertNull($form->getData());
        $this->assertEquals('foobar', $form->getViewData());
        $this->assertFalse($form->isSynchronized());
    }

    public function testSubmitSingleNonExpandedObjectChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => false,
            'choice_list' => new ObjectChoiceList(
                $this->objectChoices,
                // label path
                'name',
                array(),
                null,
                // value path
                'id'
            ),
        ));

        // "id" value of the second entry
        $form->submit('2');

        $this->assertEquals($this->objectChoices[1], $form->getData());
        $this->assertEquals('2', $form->getViewData());
    }

    public function testSubmitMultipleNonExpanded()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choices' => $this->choices,
        ));

        $form->submit(array('a', 'b'));

        $this->assertEquals(array('a', 'b'), $form->getData());
        $this->assertEquals(array('a', 'b'), $form->getViewData());
    }

    public function testSubmitMultipleNonExpandedInvalidScalarChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choices' => $this->choices,
        ));

        $form->submit('foobar');

        $this->assertNull($form->getData());
        $this->assertEquals('foobar', $form->getViewData());
        $this->assertFalse($form->isSynchronized());
    }

    public function testSubmitMultipleNonExpandedInvalidArrayChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choices' => $this->choices,
        ));

        $form->submit(array('a', 'foobar'));

        $this->assertNull($form->getData());
        $this->assertEquals(array('a', 'foobar'), $form->getViewData());
        $this->assertFalse($form->isSynchronized());
    }

    public function testSubmitMultipleNonExpandedObjectChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choice_list' => new ObjectChoiceList(
                $this->objectChoices,
                // label path
                'name',
                array(),
                null,
                // value path
                'id'
            ),
        ));

        $form->submit(array('2', '3'));

        $this->assertEquals(array($this->objectChoices[1], $this->objectChoices[2]), $form->getData());
        $this->assertEquals(array('2', '3'), $form->getViewData());
    }

    public function testSubmitSingleExpandedRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        $form->submit('b');

        $this->assertSame('b', $form->getData());
        $this->assertSame(array(
            0 => false,
            1 => true,
            2 => false,
            3 => false,
            4 => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertSame('b', $form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedRequiredInvalidChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        $form->submit('foobar');

        $this->assertSame(null, $form->getData());
        $this->assertSame('foobar', $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertFalse($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNonRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        $form->submit('b');

        $this->assertSame('b', $form->getData());
        $this->assertSame(array(
            0 => false,
            1 => true,
            2 => false,
            3 => false,
            4 => false,
            'placeholder' => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertFalse($form['placeholder']->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form['placeholder']->getViewData());
        $this->assertNull($form[0]->getViewData());
        $this->assertSame('b', $form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNonRequiredInvalidChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        $form->submit('foobar');

        $this->assertSame(null, $form->getData());
        $this->assertSame('foobar', $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertFalse($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedRequiredNull()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        $form->submit(null);

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedRequiredEmpty()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        $form->submit('');

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedRequiredFalse()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => true,
            'choices' => $this->choices,
        ));

        $form->submit(false);

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNonRequiredNull()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        $form->submit(null);

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
            'placeholder' => true,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertTrue($form['placeholder']->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertSame('', $form['placeholder']->getViewData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNonRequiredEmpty()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        $form->submit('');

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
            'placeholder' => true,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertTrue($form['placeholder']->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertSame('', $form['placeholder']->getViewData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNonRequiredFalse()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'required' => false,
            'choices' => $this->choices,
        ));

        $form->submit(false);

        $this->assertNull($form->getData());
        $this->assertSame(array(
            0 => false,
            1 => false,
            2 => false,
            3 => false,
            4 => false,
            'placeholder' => true,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertTrue($form['placeholder']->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertSame('', $form['placeholder']->getViewData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedWithEmptyChild()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'choices' => array(
                '' => 'Empty',
                1 => 'Not empty',
            ),
        ));

        $form->submit('');

        $this->assertNull($form->getData());
        $this->assertTrue($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertSame('', $form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
    }

    public function testSubmitSingleExpandedObjectChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'choice_list' => new ObjectChoiceList(
                $this->objectChoices,
                // label path
                'name',
                array(),
                null,
                // value path
                'id'
            ),
        ));

        $form->submit('2');

        $this->assertSame($this->objectChoices[1], $form->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertSame('2', $form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitSingleExpandedNumericChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => true,
            'choices' => $this->numericChoices,
        ));

        $form->submit('1');

        $this->assertSame(1, $form->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertSame('1', $form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpanded()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => $this->choices,
        ));

        $form->submit(array('a', 'c'));

        $this->assertSame(array('a', 'c'), $form->getData());
        $this->assertSame(array(
            0 => true,
            1 => false,
            2 => true,
            3 => false,
            4 => false,
        ), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertTrue($form->isSynchronized());

        $this->assertTrue($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertTrue($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertSame('a', $form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertSame('c', $form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpandedInvalidScalarChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => $this->choices,
        ));

        $form->submit('foobar');

        $this->assertNull($form->getData());
        $this->assertSame('foobar', $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertFalse($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpandedInvalidArrayChoice()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => $this->choices,
        ));

        $form->submit(array('a', 'foobar'));

        $this->assertNull($form->getData());
        $this->assertSame(array('a', 'foobar'), $form->getViewData());
        $this->assertEmpty($form->getExtraData());
        $this->assertFalse($form->isSynchronized());

        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpandedEmpty()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => $this->choices,
        ));

        $form->submit(array());

        $this->assertSame(array(), $form->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpandedWithEmptyChild()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => array(
                '' => 'Empty',
                1 => 'Not Empty',
                2 => 'Not Empty 2',
            )
        ));

        $form->submit(array('', '2'));

        $this->assertSame(array('', 2), $form->getData());
        $this->assertTrue($form[0]->getData());
        $this->assertFalse($form[1]->getData());
        $this->assertTrue($form[2]->getData());
        $this->assertSame('', $form[0]->getViewData());
        $this->assertNull($form[1]->getViewData());
        $this->assertSame('2', $form[2]->getViewData());
    }

    public function testSubmitMultipleExpandedObjectChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choice_list' => new ObjectChoiceList(
                $this->objectChoices,
                // label path
                'name',
                array(),
                null,
                // value path
                'id'
            ),
        ));

        $form->submit(array('1', '2'));

        $this->assertSame(array($this->objectChoices[0], $this->objectChoices[1]), $form->getData());
        $this->assertTrue($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertFalse($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertSame('1', $form[0]->getViewData());
        $this->assertSame('2', $form[1]->getViewData());
        $this->assertNull($form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    public function testSubmitMultipleExpandedNumericChoices()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => true,
            'choices' => $this->numericChoices,
        ));

        $form->submit(array('1', '2'));

        $this->assertSame(array(1, 2), $form->getData());
        $this->assertFalse($form[0]->getData());
        $this->assertTrue($form[1]->getData());
        $this->assertTrue($form[2]->getData());
        $this->assertFalse($form[3]->getData());
        $this->assertFalse($form[4]->getData());
        $this->assertNull($form[0]->getViewData());
        $this->assertSame('1', $form[1]->getViewData());
        $this->assertSame('2', $form[2]->getViewData());
        $this->assertNull($form[3]->getViewData());
        $this->assertNull($form[4]->getViewData());
    }

    /*
     * We need this functionality to create choice fields for Boolean types,
     * e.g. false => 'No', true => 'Yes'
     */
    public function testSetDataSingleNonExpandedAcceptsBoolean()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'expanded' => false,
            'choices' => $this->numericChoices,
        ));

        $form->setData(false);

        $this->assertFalse($form->getData());
        $this->assertEquals('0', $form->getViewData());
    }

    public function testSetDataMultipleNonExpandedAcceptsBoolean()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choices' => $this->numericChoices,
        ));

        $form->setData(array(false, true));

        $this->assertEquals(array(false, true), $form->getData());
        $this->assertEquals(array('0', '1'), $form->getViewData());
    }

    public function testPassRequiredToView()
    {
        $form = $this->factory->create('choice', null, array(
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertTrue($view->vars['required']);
    }

    public function testPassNonRequiredToView()
    {
        $form = $this->factory->create('choice', null, array(
            'required' => false,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertFalse($view->vars['required']);
    }

    public function testPassMultipleToView()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => true,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertTrue($view->vars['multiple']);
    }

    public function testPassExpandedToView()
    {
        $form = $this->factory->create('choice', null, array(
            'expanded' => true,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertTrue($view->vars['expanded']);
    }

    public function testEmptyValueIsNullByDefaultIfRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'required' => true,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertNull($view->vars['empty_value']);
    }

    public function testEmptyValueIsEmptyStringByDefaultIfNotRequired()
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => false,
            'required' => false,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertSame('', $view->vars['empty_value']);
    }

    /**
     * @dataProvider getOptionsWithEmptyValue
     */
    public function testPassEmptyValueToView($multiple, $expanded, $required, $emptyValue, $viewValue)
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => $multiple,
            'expanded' => $expanded,
            'required' => $required,
            'empty_value' => $emptyValue,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertEquals($viewValue, $view->vars['empty_value']);
        $this->assertFalse($view->vars['empty_value_in_choices']);
    }

    /**
     * @dataProvider getOptionsWithEmptyValue
     */
    public function testDontPassEmptyValueIfContainedInChoices($multiple, $expanded, $required, $emptyValue, $viewValue)
    {
        $form = $this->factory->create('choice', null, array(
            'multiple' => $multiple,
            'expanded' => $expanded,
            'required' => $required,
            'empty_value' => $emptyValue,
            'choices' => array('a' => 'A', '' => 'Empty'),
        ));
        $view = $form->createView();

        $this->assertNull($view->vars['empty_value']);
        $this->assertTrue($view->vars['empty_value_in_choices']);
    }

    public function getOptionsWithEmptyValue()
    {
        return array(
            // single non-expanded
            array(false, false, false, 'foobar', 'foobar'),
            array(false, false, false, '', ''),
            array(false, false, false, null, null),
            array(false, false, false, false, null),
            array(false, false, true, 'foobar', 'foobar'),
            array(false, false, true, '', ''),
            array(false, false, true, null, null),
            array(false, false, true, false, null),
            // single expanded
            array(false, true, false, 'foobar', 'foobar'),
            // radios should never have an empty label
            array(false, true, false, '', 'None'),
            array(false, true, false, null, null),
            array(false, true, false, false, null),
            array(false, true, true, 'foobar', 'foobar'),
            // radios should never have an empty label
            array(false, true, true, '', 'None'),
            array(false, true, true, null, null),
            array(false, true, true, false, null),
            // multiple non-expanded
            array(true, false, false, 'foobar', null),
            array(true, false, false, '', null),
            array(true, false, false, null, null),
            array(true, false, false, false, null),
            array(true, false, true, 'foobar', null),
            array(true, false, true, '', null),
            array(true, false, true, null, null),
            array(true, false, true, false, null),
            // multiple expanded
            array(true, true, false, 'foobar', null),
            array(true, true, false, '', null),
            array(true, true, false, null, null),
            array(true, true, false, false, null),
            array(true, true, true, 'foobar', null),
            array(true, true, true, '', null),
            array(true, true, true, null, null),
            array(true, true, true, false, null),
        );
    }

    public function testPassChoicesToView()
    {
        $choices = array('a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D');
        $form = $this->factory->create('choice', null, array(
            'choices' => $choices,
        ));
        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView('a', 'a', 'A'),
            new ChoiceView('b', 'b', 'B'),
            new ChoiceView('c', 'c', 'C'),
            new ChoiceView('d', 'd', 'D'),
        ), $view->vars['choices']);
    }

    public function testPassPreferredChoicesToView()
    {
        $choices = array('a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D');
        $form = $this->factory->create('choice', null, array(
            'choices' => $choices,
            'preferred_choices' => array('b', 'd'),
        ));
        $view = $form->createView();

        $this->assertEquals(array(
            0 => new ChoiceView('a', 'a', 'A'),
            2 => new ChoiceView('c', 'c', 'C'),
        ), $view->vars['choices']);
        $this->assertEquals(array(
            1 => new ChoiceView('b', 'b', 'B'),
            3 => new ChoiceView('d', 'd', 'D'),
        ), $view->vars['preferred_choices']);
    }

    public function testPassHierarchicalChoicesToView()
    {
        $form = $this->factory->create('choice', null, array(
            'choices' => $this->groupedChoices,
            'preferred_choices' => array('b', 'd'),
        ));
        $view = $form->createView();

        $this->assertEquals(array(
            'Symfony' => array(
                0 => new ChoiceView('a', 'a', 'Bernhard'),
                2 => new ChoiceView('c', 'c', 'Kris'),
            ),
            'Doctrine' => array(
                4 => new ChoiceView('e', 'e', 'Roman'),
            ),
        ), $view->vars['choices']);
        $this->assertEquals(array(
            'Symfony' => array(
                1 => new ChoiceView('b', 'b', 'Fabien'),
            ),
            'Doctrine' => array(
                3 => new ChoiceView('d', 'd', 'Jon'),
            ),
        ), $view->vars['preferred_choices']);
    }

    public function testPassChoiceDataToView()
    {
        $obj1 = (object) array('value' => 'a', 'label' => 'A');
        $obj2 = (object) array('value' => 'b', 'label' => 'B');
        $obj3 = (object) array('value' => 'c', 'label' => 'C');
        $obj4 = (object) array('value' => 'd', 'label' => 'D');
        $form = $this->factory->create('choice', null, array(
            'choice_list' => new ObjectChoiceList(array($obj1, $obj2, $obj3, $obj4), 'label', array(), null, 'value'),
        ));
        $view = $form->createView();

        $this->assertEquals(array(
            new ChoiceView($obj1, 'a', 'A'),
            new ChoiceView($obj2, 'b', 'B'),
            new ChoiceView($obj3, 'c', 'C'),
            new ChoiceView($obj4, 'd', 'D'),
        ), $view->vars['choices']);
    }

    public function testAdjustFullNameForMultipleNonExpanded()
    {
        $form = $this->factory->createNamed('name', 'choice', null, array(
            'multiple' => true,
            'expanded' => false,
            'choices' => $this->choices,
        ));
        $view = $form->createView();

        $this->assertSame('name[]', $view->vars['full_name']);
    }

    // https://github.com/symfony/symfony/issues/3298
    public function testInitializeWithEmptyChoices()
    {
        $this->factory->createNamed('name', 'choice', null, array(
            'choices' => array(),
        ));
    }

    public function testInitializeWithDefaultObjectChoice()
    {
        $obj1 = (object) array('value' => 'a', 'label' => 'A');
        $obj2 = (object) array('value' => 'b', 'label' => 'B');
        $obj3 = (object) array('value' => 'c', 'label' => 'C');
        $obj4 = (object) array('value' => 'd', 'label' => 'D');

        $form = $this->factory->create('choice', null, array(
            'choice_list' => new ObjectChoiceList(array($obj1, $obj2, $obj3, $obj4), 'label', array(), null, 'value'),
            // Used to break because "data_class" was inferred, which needs to
            // remain null in every case (because it refers to the view format)
            'data' => $obj3,
        ));

        // Trigger data initialization
        $form->getViewData();
    }
}
PK/1[�jGgJgJFForm/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Tests\Fixtures\Author;
use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer;
use Symfony\Component\Form\FormError;

class FormTest_AuthorWithoutRefSetter
{
    protected $reference;

    protected $referenceCopy;

    public function __construct($reference)
    {
        $this->reference = $reference;
        $this->referenceCopy = $reference;
    }

    // The returned object should be modified by reference without having
    // to provide a setReference() method
    public function getReference()
    {
        return $this->reference;
    }

    // The returned object is a copy, so setReferenceCopy() must be used
    // to update it
    public function getReferenceCopy()
    {
        return is_object($this->referenceCopy) ? clone $this->referenceCopy : $this->referenceCopy;
    }

    public function setReferenceCopy($reference)
    {
        $this->referenceCopy = $reference;
    }
}

class FormTypeTest extends BaseTypeTest
{
    public function testCreateFormInstances()
    {
        $this->assertInstanceOf('Symfony\Component\Form\Form', $this->factory->create('form'));
    }

    public function testPassRequiredAsOption()
    {
        $form = $this->factory->create('form', null, array('required' => false));

        $this->assertFalse($form->isRequired());

        $form = $this->factory->create('form', null, array('required' => true));

        $this->assertTrue($form->isRequired());
    }

    public function testSubmittedDataIsTrimmedBeforeTransforming()
    {
        $form = $this->factory->createBuilder('form')
            ->addViewTransformer(new FixedDataTransformer(array(
                null => '',
                'reverse[a]' => 'a',
            )))
            ->setCompound(false)
            ->getForm();

        $form->submit(' a ');

        $this->assertEquals('a', $form->getViewData());
        $this->assertEquals('reverse[a]', $form->getData());
    }

    public function testSubmittedDataIsNotTrimmedBeforeTransformingIfNoTrimming()
    {
        $form = $this->factory->createBuilder('form', null, array('trim' => false))
            ->addViewTransformer(new FixedDataTransformer(array(
                null => '',
                'reverse[ a ]' => ' a ',
            )))
            ->setCompound(false)
            ->getForm();

        $form->submit(' a ');

        $this->assertEquals(' a ', $form->getViewData());
        $this->assertEquals('reverse[ a ]', $form->getData());
    }

    public function testNonReadOnlyFormWithReadOnlyParentIsReadOnly()
    {
        $view = $this->factory->createNamedBuilder('parent', 'form', null, array('read_only' => true))
            ->add('child', 'form')
            ->getForm()
            ->createView();

        $this->assertTrue($view['child']->vars['read_only']);
    }

    public function testReadOnlyFormWithNonReadOnlyParentIsReadOnly()
    {
        $view = $this->factory->createNamedBuilder('parent', 'form')
            ->add('child', 'form', array('read_only' => true))
            ->getForm()
            ->createView();

        $this->assertTrue($view['child']->vars['read_only']);
    }

    public function testNonReadOnlyFormWithNonReadOnlyParentIsNotReadOnly()
    {
        $view = $this->factory->createNamedBuilder('parent', 'form')
                ->add('child', 'form')
                ->getForm()
                ->createView();

        $this->assertFalse($view['child']->vars['read_only']);
    }

    public function testPassMaxLengthToView()
    {
        $form = $this->factory->create('form', null, array('max_length' => 10));
        $view = $form->createView();

        $this->assertSame(10, $view->vars['max_length']);
    }

    public function testSubmitWithEmptyDataCreatesObjectIfClassAvailable()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'required' => false,
        ));
        $builder->add('firstName', 'text');
        $builder->add('lastName', 'text');
        $form = $builder->getForm();

        $form->setData(null);
        // partially empty, still an object is created
        $form->submit(array('firstName' => 'Bernhard', 'lastName' => ''));

        $author = new Author();
        $author->firstName = 'Bernhard';
        $author->setLastName('');

        $this->assertEquals($author, $form->getData());
    }

    public function testSubmitWithEmptyDataCreatesObjectIfInitiallySubmittedWithObject()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            // data class is inferred from the passed object
            'data' => new Author(),
            'required' => false,
        ));
        $builder->add('firstName', 'text');
        $builder->add('lastName', 'text');
        $form = $builder->getForm();

        $form->setData(null);
        // partially empty, still an object is created
        $form->submit(array('firstName' => 'Bernhard', 'lastName' => ''));

        $author = new Author();
        $author->firstName = 'Bernhard';
        $author->setLastName('');

        $this->assertEquals($author, $form->getData());
    }

    public function testSubmitWithEmptyDataCreatesArrayIfDataClassIsNull()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => null,
            'required' => false,
        ));
        $builder->add('firstName', 'text');
        $form = $builder->getForm();

        $form->setData(null);
        $form->submit(array('firstName' => 'Bernhard'));

        $this->assertSame(array('firstName' => 'Bernhard'), $form->getData());
    }

    public function testSubmitEmptyWithEmptyDataCreatesNoObjectIfNotRequired()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'required' => false,
        ));
        $builder->add('firstName', 'text');
        $builder->add('lastName', 'text');
        $form = $builder->getForm();

        $form->setData(null);
        $form->submit(array('firstName' => '', 'lastName' => ''));

        $this->assertNull($form->getData());
    }

    public function testSubmitEmptyWithEmptyDataCreatesObjectIfRequired()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'required' => true,
        ));
        $builder->add('firstName', 'text');
        $builder->add('lastName', 'text');
        $form = $builder->getForm();

        $form->setData(null);
        $form->submit(array('firstName' => '', 'lastName' => ''));

        $this->assertEquals(new Author(), $form->getData());
    }

    /*
     * We need something to write the field values into
     */
    public function testSubmitWithEmptyDataStoresArrayIfNoClassAvailable()
    {
        $form = $this->factory->createBuilder('form')
            ->add('firstName', 'text')
            ->getForm();

        $form->setData(null);
        $form->submit(array('firstName' => 'Bernhard'));

        $this->assertSame(array('firstName' => 'Bernhard'), $form->getData());
    }

    public function testSubmitWithEmptyDataPassesEmptyStringToTransformerIfNotCompound()
    {
        $form = $this->factory->createBuilder('form')
            ->addViewTransformer(new FixedDataTransformer(array(
                // required for the initial, internal setData(null)
                null => 'null',
                // required to test that submit(null) is converted to ''
                'empty' => '',
            )))
            ->setCompound(false)
            ->getForm();

        $form->submit(null);

        $this->assertSame('empty', $form->getData());
    }

    public function testSubmitWithEmptyDataUsesEmptyDataOption()
    {
        $author = new Author();

        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'empty_data' => $author,
        ));
        $builder->add('firstName', 'text');
        $form = $builder->getForm();

        $form->submit(array('firstName' => 'Bernhard'));

        $this->assertSame($author, $form->getData());
        $this->assertEquals('Bernhard', $author->firstName);
    }

    public function provideZeros()
    {
        return array(
            array(0, '0'),
            array('0', '0'),
            array('00000', '00000'),
        );
    }

    /**
     * @dataProvider provideZeros
     * @see https://github.com/symfony/symfony/issues/1986
     */
    public function testSetDataThroughParamsWithZero($data, $dataAsString)
    {
        $form = $this->factory->create('form', null, array(
            'data' => $data,
            'compound' => false,
        ));
        $view = $form->createView();

        $this->assertFalse($form->isEmpty());

        $this->assertSame($dataAsString, $view->vars['value']);
        $this->assertSame($dataAsString, $form->getData());
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testAttributesException()
    {
        $this->factory->create('form', null, array('attr' => ''));
    }

    public function testNameCanBeEmptyString()
    {
        $form = $this->factory->createNamed('', 'form');

        $this->assertEquals('', $form->getName());
    }

    public function testSubformDoesntCallSetters()
    {
        $author = new FormTest_AuthorWithoutRefSetter(new Author());

        $builder = $this->factory->createBuilder('form', $author);
        $builder->add('reference', 'form', array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
        ));
        $builder->get('reference')->add('firstName', 'text');
        $form = $builder->getForm();

        $form->submit(array(
            // reference has a getter, but not setter
            'reference' => array(
                'firstName' => 'Foo',
            )
        ));

        $this->assertEquals('Foo', $author->getReference()->firstName);
    }

    public function testSubformCallsSettersIfTheObjectChanged()
    {
        // no reference
        $author = new FormTest_AuthorWithoutRefSetter(null);
        $newReference = new Author();

        $builder = $this->factory->createBuilder('form', $author);
        $builder->add('referenceCopy', 'form', array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
        ));
        $builder->get('referenceCopy')->add('firstName', 'text');
        $form = $builder->getForm();

        $form['referenceCopy']->setData($newReference); // new author object

        $form->submit(array(
        // referenceCopy has a getter that returns a copy
            'referenceCopy' => array(
                'firstName' => 'Foo',
        )
        ));

        $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
    }

    public function testSubformCallsSettersIfByReferenceIsFalse()
    {
        $author = new FormTest_AuthorWithoutRefSetter(new Author());

        $builder = $this->factory->createBuilder('form', $author);
        $builder->add('referenceCopy', 'form', array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'by_reference' => false
        ));
        $builder->get('referenceCopy')->add('firstName', 'text');
        $form = $builder->getForm();

        $form->submit(array(
            // referenceCopy has a getter that returns a copy
            'referenceCopy' => array(
                'firstName' => 'Foo',
            )
        ));

        // firstName can only be updated if setReferenceCopy() was called
        $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
    }

    public function testSubformCallsSettersIfReferenceIsScalar()
    {
        $author = new FormTest_AuthorWithoutRefSetter('scalar');

        $builder = $this->factory->createBuilder('form', $author);
        $builder->add('referenceCopy', 'form');
        $builder->get('referenceCopy')->addViewTransformer(new CallbackTransformer(
            function () {},
            function ($value) { // reverseTransform

                return 'foobar';
            }
        ));
        $form = $builder->getForm();

        $form->submit(array(
            'referenceCopy' => array(), // doesn't matter actually
        ));

        // firstName can only be updated if setReferenceCopy() was called
        $this->assertEquals('foobar', $author->getReferenceCopy());
    }

    public function testSubformAlwaysInsertsIntoArrays()
    {
        $ref1 = new Author();
        $ref2 = new Author();
        $author = array('referenceCopy' => $ref1);

        $builder = $this->factory->createBuilder('form');
        $builder->setData($author);
        $builder->add('referenceCopy', 'form');
        $builder->get('referenceCopy')->addViewTransformer(new CallbackTransformer(
            function () {},
            function ($value) use ($ref2) { // reverseTransform

                return $ref2;
            }
        ));
        $form = $builder->getForm();

        $form->submit(array(
            'referenceCopy' => array('a' => 'b'), // doesn't matter actually
        ));

        // the new reference was inserted into the array
        $author = $form->getData();
        $this->assertSame($ref2, $author['referenceCopy']);
    }

    public function testPassMultipartTrueIfAnyChildIsMultipartToView()
    {
        $view = $this->factory->createBuilder('form')
            ->add('foo', 'text')
            ->add('bar', 'file')
            ->getForm()
            ->createView();

        $this->assertTrue($view->vars['multipart']);
    }

    public function testViewIsNotRenderedByDefault()
    {
        $view = $this->factory->createBuilder('form')
                ->add('foo', 'form')
                ->getForm()
                ->createView();

        $this->assertFalse($view->isRendered());
    }

    public function testErrorBubblingIfCompound()
    {
        $form = $this->factory->create('form', null, array(
            'compound' => true,
        ));

        $this->assertTrue($form->getConfig()->getErrorBubbling());
    }

    public function testNoErrorBubblingIfNotCompound()
    {
        $form = $this->factory->create('form', null, array(
            'compound' => false,
        ));

        $this->assertFalse($form->getConfig()->getErrorBubbling());
    }

    public function testOverrideErrorBubbling()
    {
        $form = $this->factory->create('form', null, array(
            'compound' => false,
            'error_bubbling' => true,
        ));

        $this->assertTrue($form->getConfig()->getErrorBubbling());
    }

    public function testPropertyPath()
    {
        $form = $this->factory->create('form', null, array(
            'property_path' => 'foo',
        ));

        $this->assertEquals(new PropertyPath('foo'), $form->getPropertyPath());
        $this->assertTrue($form->getConfig()->getMapped());
    }

    public function testPropertyPathNullImpliesDefault()
    {
        $form = $this->factory->createNamed('name', 'form', null, array(
            'property_path' => null,
        ));

        $this->assertEquals(new PropertyPath('name'), $form->getPropertyPath());
        $this->assertTrue($form->getConfig()->getMapped());
    }

    public function testNotMapped()
    {
        $form = $this->factory->create('form', null, array(
            'property_path' => 'foo',
            'mapped' => false,
        ));

        $this->assertEquals(new PropertyPath('foo'), $form->getPropertyPath());
        $this->assertFalse($form->getConfig()->getMapped());
    }

    public function testViewValidNotSubmitted()
    {
        $form = $this->factory->create('form');
        $view = $form->createView();
        $this->assertTrue($view->vars['valid']);
    }

    public function testViewNotValidSubmitted()
    {
        $form = $this->factory->create('form');
        $form->submit(array());
        $form->addError(new FormError('An error'));
        $view = $form->createView();
        $this->assertFalse($view->vars['valid']);
    }

    public function testViewSubmittedNotSubmitted()
    {
        $form = $this->factory->create('form');
        $view = $form->createView();
        $this->assertFalse($view->vars['submitted']);
    }

    public function testViewSubmittedSubmitted()
    {
        $form = $this->factory->create('form');
        $form->submit(array());
        $view = $form->createView();
        $this->assertTrue($view->vars['submitted']);
    }

    public function testDataOptionSupersedesSetDataCalls()
    {
        $form = $this->factory->create('form', null, array(
            'data' => 'default',
            'compound' => false,
        ));

        $form->setData('foobar');

        $this->assertSame('default', $form->getData());
    }

    public function testDataOptionSupersedesSetDataCallsIfNull()
    {
        $form = $this->factory->create('form', null, array(
            'data' => null,
            'compound' => false,
        ));

        $form->setData('foobar');

        $this->assertNull($form->getData());
    }

    public function testNormDataIsPassedToView()
    {
        $view = $this->factory->createBuilder('form')
            ->addViewTransformer(new FixedDataTransformer(array(
                'foo' => 'bar',
            )))
            ->setData('foo')
            ->getForm()
            ->createView();

        $this->assertSame('foo', $view->vars['data']);
        $this->assertSame('bar', $view->vars['value']);
    }

    // https://github.com/symfony/symfony/issues/6862
    public function testPassZeroLabelToView()
    {
        $view = $this->factory->create('form', null, array(
                'label' => '0'
            ))
            ->createView();

        $this->assertSame('0', $view->vars['label']);
    }

    public function testCanGetErrorsWhenButtonInForm()
    {
        $builder = $this->factory->createBuilder('form', null, array(
            'data_class' => 'Symfony\Component\Form\Tests\Fixtures\Author',
            'required' => false,
        ));
        $builder->add('foo', 'text');
        $builder->add('submit', 'submit');
        $form = $builder->getForm();

        //This method should not throw a Fatal Error Exception.
        $form->getErrorsAsString();
    }

    protected function getTestedType()
    {
        return 'form';
    }
}
PK/1[&����FForm/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\Core\Type;

class FileTypeTest extends \Symfony\Component\Form\Test\TypeTestCase
{
    // https://github.com/symfony/symfony/pull/5028
    public function testSetData()
    {
        $form = $this->factory->createBuilder('file')->getForm();
        $data = $this->createUploadedFileMock('abcdef', 'original.jpg', true);

        $form->setData($data);

        $this->assertSame($data, $form->getData());
    }

    public function testSubmit()
    {
        $form = $this->factory->createBuilder('file')->getForm();
        $data = $this->createUploadedFileMock('abcdef', 'original.jpg', true);

        $form->submit($data);

        $this->assertSame($data, $form->getData());
    }

    // https://github.com/symfony/symfony/issues/6134
    public function testSubmitEmpty()
    {
        $form = $this->factory->createBuilder('file')->getForm();

        $form->submit(null);

        $this->assertNull($form->getData());
    }

    public function testDontPassValueToView()
    {
        $form = $this->factory->create('file');
        $form->submit(array(
            'file' => $this->createUploadedFileMock('abcdef', 'original.jpg', true),
        ));
        $view = $form->createView();

        $this->assertEquals('', $view->vars['value']);
    }

    private function createUploadedFileMock($name, $originalName, $valid)
    {
        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $file
            ->expects($this->any())
            ->method('getBasename')
            ->will($this->returnValue($name))
        ;
        $file
            ->expects($this->any())
            ->method('getClientOriginalName')
            ->will($this->returnValue($originalName))
        ;
        $file
            ->expects($this->any())
            ->method('isValid')
            ->will($this->returnValue($valid))
        ;

        return $file;
    }
}
PK/1[����>�>SForm/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.phpnu�[���<?php
/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\DataCollector;

use Symfony\Component\Form\Extension\DataCollector\FormDataCollector;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormView;

class FormDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dataExtractor;

    /**
     * @var FormDataCollector
     */
    private $dataCollector;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $factory;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dataMapper;

    /**
     * @var Form
     */
    private $form;

    /**
     * @var Form
     */
    private $childForm;

    /**
     * @var FormView
     */
    private $view;

    /**
     * @var FormView
     */
    private $childView;

    protected function setUp()
    {
        $this->dataExtractor = $this->getMock('Symfony\Component\Form\Extension\DataCollector\FormDataExtractorInterface');
        $this->dataCollector = new FormDataCollector($this->dataExtractor);
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
        $this->dataMapper = $this->getMock('Symfony\Component\Form\DataMapperInterface');
        $this->form = $this->createForm('name');
        $this->childForm = $this->createForm('child');
        $this->view = new FormView();
        $this->childView = new FormView();
    }

    public function testBuildPreliminaryFormTree()
    {
        $this->form->add($this->childForm);

        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($this->form)
            ->will($this->returnValue(array('config' => 'foo')));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractConfiguration')
            ->with($this->childForm)
            ->will($this->returnValue(array('config' => 'bar')));

        $this->dataExtractor->expects($this->at(2))
            ->method('extractDefaultData')
            ->with($this->form)
            ->will($this->returnValue(array('default_data' => 'foo')));
        $this->dataExtractor->expects($this->at(3))
            ->method('extractDefaultData')
            ->with($this->childForm)
            ->will($this->returnValue(array('default_data' => 'bar')));

        $this->dataExtractor->expects($this->at(4))
            ->method('extractSubmittedData')
            ->with($this->form)
            ->will($this->returnValue(array('submitted_data' => 'foo')));
        $this->dataExtractor->expects($this->at(5))
            ->method('extractSubmittedData')
            ->with($this->childForm)
            ->will($this->returnValue(array('submitted_data' => 'bar')));

        $this->dataCollector->collectConfiguration($this->form);
        $this->dataCollector->collectDefaultData($this->form);
        $this->dataCollector->collectSubmittedData($this->form);
        $this->dataCollector->buildPreliminaryFormTree($this->form);

        $this->assertSame(array(
             'forms' => array(
                 'name' => array(
                     'config' => 'foo',
                     'default_data' => 'foo',
                     'submitted_data' => 'foo',
                     'children' => array(
                         'child' => array(
                             'config' => 'bar',
                             'default_data' => 'bar',
                             'submitted_data' => 'bar',
                             'children' => array(),
                         ),
                     ),
                 ),
             ),
             'nb_errors' => 0,
         ), $this->dataCollector->getData());
    }

    public function testBuildMultiplePreliminaryFormTrees()
    {
        $form1 = $this->createForm('form1');
        $form2 = $this->createForm('form2');

        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($form1)
            ->will($this->returnValue(array('config' => 'foo')));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractConfiguration')
            ->with($form2)
            ->will($this->returnValue(array('config' => 'bar')));

        $this->dataCollector->collectConfiguration($form1);
        $this->dataCollector->collectConfiguration($form2);
        $this->dataCollector->buildPreliminaryFormTree($form1);

        $this->assertSame(array(
            'forms' => array(
                'form1' => array(
                    'config' => 'foo',
                    'children' => array(),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());

        $this->dataCollector->buildPreliminaryFormTree($form2);

        $this->assertSame(array(
            'forms' => array(
                'form1' => array(
                    'config' => 'foo',
                    'children' => array(),
                ),
                'form2' => array(
                    'config' => 'bar',
                    'children' => array(),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testBuildSamePreliminaryFormTreeMultipleTimes()
    {
        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($this->form)
            ->will($this->returnValue(array('config' => 'foo')));

        $this->dataExtractor->expects($this->at(1))
            ->method('extractDefaultData')
            ->with($this->form)
            ->will($this->returnValue(array('default_data' => 'foo')));

        $this->dataCollector->collectConfiguration($this->form);
        $this->dataCollector->buildPreliminaryFormTree($this->form);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'config' => 'foo',
                    'children' => array(),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());

        $this->dataCollector->collectDefaultData($this->form);
        $this->dataCollector->buildPreliminaryFormTree($this->form);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'config' => 'foo',
                    'default_data' => 'foo',
                    'children' => array(),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testBuildPreliminaryFormTreeWithoutCollectingAnyData()
    {
        $this->dataCollector->buildPreliminaryFormTree($this->form);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'children' => array(),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testBuildFinalFormTree()
    {
        $this->form->add($this->childForm);
        $this->view->children['child'] = $this->childView;

        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($this->form)
            ->will($this->returnValue(array('config' => 'foo')));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractConfiguration')
            ->with($this->childForm)
            ->will($this->returnValue(array('config' => 'bar')));

        $this->dataExtractor->expects($this->at(2))
            ->method('extractDefaultData')
            ->with($this->form)
            ->will($this->returnValue(array('default_data' => 'foo')));
        $this->dataExtractor->expects($this->at(3))
            ->method('extractDefaultData')
            ->with($this->childForm)
            ->will($this->returnValue(array('default_data' => 'bar')));

        $this->dataExtractor->expects($this->at(4))
            ->method('extractSubmittedData')
            ->with($this->form)
            ->will($this->returnValue(array('submitted_data' => 'foo')));
        $this->dataExtractor->expects($this->at(5))
            ->method('extractSubmittedData')
            ->with($this->childForm)
            ->will($this->returnValue(array('submitted_data' => 'bar')));

        $this->dataExtractor->expects($this->at(6))
            ->method('extractViewVariables')
            ->with($this->view)
            ->will($this->returnValue(array('view_vars' => 'foo')));

        $this->dataExtractor->expects($this->at(7))
            ->method('extractViewVariables')
            ->with($this->childView)
            ->will($this->returnValue(array('view_vars' => 'bar')));

        $this->dataCollector->collectConfiguration($this->form);
        $this->dataCollector->collectDefaultData($this->form);
        $this->dataCollector->collectSubmittedData($this->form);
        $this->dataCollector->collectViewVariables($this->view);
        $this->dataCollector->buildFinalFormTree($this->form, $this->view);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'view_vars' => 'foo',
                    'config' => 'foo',
                    'default_data' => 'foo',
                    'submitted_data' => 'foo',
                    'children' => array(
                        'child' => array(
                            'view_vars' => 'bar',
                            'config' => 'bar',
                            'default_data' => 'bar',
                            'submitted_data' => 'bar',
                            'children' => array(),
                        ),
                    ),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testFinalFormReliesOnFormViewStructure()
    {
        $this->form->add($this->createForm('first'));
        $this->form->add($this->createForm('second'));

        $this->view->children['second'] = $this->childView;

        $this->dataCollector->buildPreliminaryFormTree($this->form);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'children' => array(
                        'first' => array(
                            'children' => array(),
                        ),
                        'second' => array(
                            'children' => array(),
                        ),
                    ),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());

        $this->dataCollector->buildFinalFormTree($this->form, $this->view);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'children' => array(
                        // "first" not present in FormView
                        'second' => array(
                            'children' => array(),
                        ),
                    ),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testChildViewsCanBeWithoutCorrespondingChildForms()
    {
        // don't add $this->childForm to $this->form!

        $this->view->children['child'] = $this->childView;

        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($this->form)
            ->will($this->returnValue(array('config' => 'foo')));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractConfiguration')
            ->with($this->childForm)
            ->will($this->returnValue(array('config' => 'bar')));

        // explicitly call collectConfiguration(), since $this->childForm is not
        // contained in the form tree
        $this->dataCollector->collectConfiguration($this->form);
        $this->dataCollector->collectConfiguration($this->childForm);
        $this->dataCollector->buildFinalFormTree($this->form, $this->view);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'config' => 'foo',
                    'children' => array(
                        'child' => array(
                            // no "config" key
                            'children' => array(),
                        ),
                    ),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testChildViewsWithoutCorrespondingChildFormsMayBeExplicitlyAssociated()
    {
        // don't add $this->childForm to $this->form!

        $this->view->children['child'] = $this->childView;

        // but associate the two
        $this->dataCollector->associateFormWithView($this->childForm, $this->childView);

        $this->dataExtractor->expects($this->at(0))
            ->method('extractConfiguration')
            ->with($this->form)
            ->will($this->returnValue(array('config' => 'foo')));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractConfiguration')
            ->with($this->childForm)
            ->will($this->returnValue(array('config' => 'bar')));

        // explicitly call collectConfiguration(), since $this->childForm is not
        // contained in the form tree
        $this->dataCollector->collectConfiguration($this->form);
        $this->dataCollector->collectConfiguration($this->childForm);
        $this->dataCollector->buildFinalFormTree($this->form, $this->view);

        $this->assertSame(array(
            'forms' => array(
                'name' => array(
                    'config' => 'foo',
                    'children' => array(
                        'child' => array(
                            'config' => 'bar',
                            'children' => array(),
                        ),
                    ),
                ),
            ),
            'nb_errors' => 0,
        ), $this->dataCollector->getData());
    }

    public function testCollectSubmittedDataCountsErrors()
    {
        $form1 = $this->createForm('form1');
        $childForm1 = $this->createForm('child1');
        $form2 = $this->createForm('form2');

        $form1->add($childForm1);

        $this->dataExtractor->expects($this->at(0))
            ->method('extractSubmittedData')
            ->with($form1)
            ->will($this->returnValue(array('errors' => array('foo'))));
        $this->dataExtractor->expects($this->at(1))
            ->method('extractSubmittedData')
            ->with($childForm1)
            ->will($this->returnValue(array('errors' => array('bar', 'bam'))));
        $this->dataExtractor->expects($this->at(2))
            ->method('extractSubmittedData')
            ->with($form2)
            ->will($this->returnValue(array('errors' => array('baz'))));

        $this->dataCollector->collectSubmittedData($form1);

        $data = $this->dataCollector->getData();
        $this->assertSame(3, $data['nb_errors']);

        $this->dataCollector->collectSubmittedData($form2);

        $data = $this->dataCollector->getData();
        $this->assertSame(4, $data['nb_errors']);

    }

    private function createForm($name)
    {
        $builder = new FormBuilder($name, null, $this->dispatcher, $this->factory);
        $builder->setCompound(true);
        $builder->setDataMapper($this->dataMapper);

        return $builder->getForm();
    }
}
PK/1[b�,�<<XForm/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\DataCollector;

use Symfony\Component\Form\Extension\DataCollector\DataCollectorExtension;

/**
 * @covers Symfony\Component\Form\Extension\DataCollector\DataCollectorExtension
 */
class DataCollectorExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DataCollectorExtension
     */
    private $extension;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dataCollector;

    public function setUp()
    {
        $this->dataCollector = $this->getMock('Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface');
        $this->extension = new DataCollectorExtension($this->dataCollector);
    }

    public function testLoadTypeExtensions()
    {
        $typeExtensions = $this->extension->getTypeExtensions('form');

        $this->assertInternalType('array', $typeExtensions);
        $this->assertCount(1, $typeExtensions);
        $this->assertInstanceOf('Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension', array_shift($typeExtensions));
    }
}
PK/1[�{�(�,�,SForm/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\DataCollector;

use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Exception\TransformationFailedException;
use Symfony\Component\Form\Extension\DataCollector\FormDataExtractor;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Tests\Fixtures\FixedDataTransformer;
use Symfony\Component\HttpKernel\DataCollector\Util\ValueExporter;

class FormDataExtractorTest_SimpleValueExporter extends ValueExporter
{
    /**
     * {@inheritdoc}
     */
    public function exportValue($value)
    {
        return var_export($value, true);
    }
}

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class FormDataExtractorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FormDataExtractorTest_SimpleValueExporter
     */
    private $valueExporter;

    /**
     * @var FormDataExtractor
     */
    private $dataExtractor;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dispatcher;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $factory;

    protected function setUp()
    {
        $this->valueExporter = new FormDataExtractorTest_SimpleValueExporter();
        $this->dataExtractor = new FormDataExtractor($this->valueExporter);
        $this->dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->factory = $this->getMock('Symfony\Component\Form\FormFactoryInterface');
    }

    public function testExtractConfiguration()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('type_name'));
        $type->expects($this->any())
            ->method('getInnerType')
            ->will($this->returnValue(new \stdClass()));

        $form = $this->createBuilder('name')
            ->setType($type)
            ->getForm();

        $this->assertSame(array(
            'id' => 'name',
            'type' => 'type_name',
            'type_class' => 'stdClass',
            'synchronized' => 'true',
            'passed_options' => array(),
            'resolved_options' => array(),
        ), $this->dataExtractor->extractConfiguration($form));
    }

    public function testExtractConfigurationSortsPassedOptions()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('type_name'));
        $type->expects($this->any())
            ->method('getInnerType')
            ->will($this->returnValue(new \stdClass()));

        $options = array(
            'b' => 'foo',
            'a' => 'bar',
            'c' => 'baz',
        );

        $form = $this->createBuilder('name')
            ->setType($type)
            // passed options are stored in an attribute by
            // ResolvedTypeDataCollectorProxy
            ->setAttribute('data_collector/passed_options', $options)
            ->getForm();

        $this->assertSame(array(
            'id' => 'name',
            'type' => 'type_name',
            'type_class' => 'stdClass',
            'synchronized' => 'true',
            'passed_options' => array(
                'a' => "'bar'",
                'b' => "'foo'",
                'c' => "'baz'",
            ),
            'resolved_options' => array(),
        ), $this->dataExtractor->extractConfiguration($form));
    }

    public function testExtractConfigurationSortsResolvedOptions()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('type_name'));
        $type->expects($this->any())
            ->method('getInnerType')
            ->will($this->returnValue(new \stdClass()));

        $options = array(
            'b' => 'foo',
            'a' => 'bar',
            'c' => 'baz',
        );

        $form = $this->createBuilder('name', $options)
            ->setType($type)
            ->getForm();

        $this->assertSame(array(
            'id' => 'name',
            'type' => 'type_name',
            'type_class' => 'stdClass',
            'synchronized' => 'true',
            'passed_options' => array(),
            'resolved_options' => array(
                'a' => "'bar'",
                'b' => "'foo'",
                'c' => "'baz'",
            ),
        ), $this->dataExtractor->extractConfiguration($form));
    }

    public function testExtractConfigurationBuildsIdRecursively()
    {
        $type = $this->getMock('Symfony\Component\Form\ResolvedFormTypeInterface');
        $type->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('type_name'));
        $type->expects($this->any())
            ->method('getInnerType')
            ->will($this->returnValue(new \stdClass()));

        $grandParent = $this->createBuilder('grandParent')
            ->setCompound(true)
            ->setDataMapper($this->getMock('Symfony\Component\Form\DataMapperInterface'))
            ->getForm();
        $parent = $this->createBuilder('parent')
            ->setCompound(true)
            ->setDataMapper($this->getMock('Symfony\Component\Form\DataMapperInterface'))
            ->getForm();
        $form = $this->createBuilder('name')
            ->setType($type)
            ->getForm();

        $grandParent->add($parent);
        $parent->add($form);

        $this->assertSame(array(
            'id' => 'grandParent_parent_name',
            'type' => 'type_name',
            'type_class' => 'stdClass',
            'synchronized' => 'true',
            'passed_options' => array(),
            'resolved_options' => array(),
        ), $this->dataExtractor->extractConfiguration($form));
    }

    public function testExtractDefaultData()
    {
        $form = $this->createBuilder('name')->getForm();

        $form->setData('Foobar');

        $this->assertSame(array(
            'default_data' => array(
                'norm' => "'Foobar'",
            ),
            'submitted_data' => array(),
        ), $this->dataExtractor->extractDefaultData($form));
    }

    public function testExtractDefaultDataStoresModelDataIfDifferent()
    {
        $form = $this->createBuilder('name')
            ->addModelTransformer(new FixedDataTransformer(array(
                'Foo' => 'Bar'
            )))
            ->getForm();

        $form->setData('Foo');

        $this->assertSame(array(
            'default_data' => array(
                'norm' => "'Bar'",
                'model' => "'Foo'",
            ),
            'submitted_data' => array(),
        ), $this->dataExtractor->extractDefaultData($form));
    }

    public function testExtractDefaultDataStoresViewDataIfDifferent()
    {
        $form = $this->createBuilder('name')
            ->addViewTransformer(new FixedDataTransformer(array(
                'Foo' => 'Bar'
            )))
            ->getForm();

        $form->setData('Foo');

        $this->assertSame(array(
            'default_data' => array(
                'norm' => "'Foo'",
                'view' => "'Bar'",
            ),
            'submitted_data' => array(),
        ), $this->dataExtractor->extractDefaultData($form));
    }

    public function testExtractSubmittedData()
    {
        $form = $this->createBuilder('name')->getForm();

        $form->submit('Foobar');

        $this->assertSame(array(
            'submitted_data' => array(
                'norm' => "'Foobar'",
            ),
            'errors' => array(),
            'synchronized' => 'true',
        ), $this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataStoresModelDataIfDifferent()
    {
        $form = $this->createBuilder('name')
            ->addModelTransformer(new FixedDataTransformer(array(
                'Foo' => 'Bar',
                '' => '',
            )))
            ->getForm();

        $form->submit('Bar');

        $this->assertSame(array(
            'submitted_data' => array(
                'norm' => "'Bar'",
                'model' => "'Foo'",
            ),
            'errors' => array(),
            'synchronized' => 'true',
        ), $this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataStoresViewDataIfDifferent()
    {
        $form = $this->createBuilder('name')
            ->addViewTransformer(new FixedDataTransformer(array(
                'Foo' => 'Bar',
                '' => '',
            )))
            ->getForm();

        $form->submit('Bar');

        $this->assertSame(array(
            'submitted_data' => array(
                'norm' => "'Foo'",
                'view' => "'Bar'",
            ),
            'errors' => array(),
            'synchronized' => 'true',
        ), $this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataStoresErrors()
    {
        $form = $this->createBuilder('name')->getForm();

        $form->submit('Foobar');
        $form->addError(new FormError('Invalid!'));

        $this->assertSame(array(
            'submitted_data' => array(
                'norm' => "'Foobar'",
            ),
            'errors' => array(
                array('message' => 'Invalid!'),
            ),
            'synchronized' => 'true',
        ), $this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractSubmittedDataRemembersIfNonSynchronized()
    {
        $form = $this->createBuilder('name')
            ->addModelTransformer(new CallbackTransformer(
                function () {},
                function () {
                    throw new TransformationFailedException('Fail!');
                }
            ))
            ->getForm();

        $form->submit('Foobar');

        $this->assertSame(array(
            'submitted_data' => array(
                'norm' => "'Foobar'",
                'model' => 'NULL',
            ),
            'errors' => array(),
            'synchronized' => 'false',
        ), $this->dataExtractor->extractSubmittedData($form));
    }

    public function testExtractViewVariables()
    {
        $view = new FormView();

        $view->vars = array(
            'b' => 'foo',
            'a' => 'bar',
            'c' => 'baz',
            'id' => 'foo_bar',
        );

        $this->assertSame(array(
            'id' => 'foo_bar',
            'view_vars' => array(
                'a' => "'bar'",
                'b' => "'foo'",
                'c' => "'baz'",
                'id' => "'foo_bar'",
            ),
        ), $this->dataExtractor->extractViewVariables($view));
    }

    /**
     * @param string $name
     * @param array  $options
     *
     * @return FormBuilder
     */
    private function createBuilder($name, array $options = array())
    {
        return new FormBuilder($name, null, $this->dispatcher, $this->factory, $options);
    }
}
PK/1[��q��aForm/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.phpnu�[���<?php
/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests\Extension\DataCollector\Type;

use Symfony\Component\Form\Extension\DataCollector\Type\DataCollectorTypeExtension;

class DataCollectorTypeExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var DataCollectorTypeExtension
     */
    private $extension;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $dataCollector;

    public function setUp()
    {
        $this->dataCollector = $this->getMock('Symfony\Component\Form\Extension\DataCollector\FormDataCollectorInterface');
        $this->extension = new DataCollectorTypeExtension($this->dataCollector);
    }

    public function testGetExtendedType()
    {
        $this->assertEquals('form', $this->extension->getExtendedType());
    }

    public function testBuildForm()
    {
        $builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface');
        $builder->expects($this->atLeastOnce())
            ->method('addEventSubscriber')
            ->with($this->isInstanceOf('Symfony\Component\Form\Extension\DataCollector\EventListener\DataCollectorListener'));

        $this->extension->buildForm($builder, array());
    }
}
PK/1[�'�;Form/Symfony/Component/Form/Tests/AbstractExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Form\Tests;

use Symfony\Component\Form\AbstractExtension;
use Symfony\Component\Form\Tests\Fixtures\FooType;

class AbstractExtensionTest extends \PHPUnit_Framework_TestCase
{
    public function testHasType()
    {
        $loader = new ConcreteExtension();
        $this->assertTrue($loader->hasType('foo'));
        $this->assertFalse($loader->hasType('bar'));
    }

    public function testGetType()
    {
        $loader = new ConcreteExtension();
        $this->assertInstanceOf('Symfony\Component\Form\Tests\Fixtures\FooType', $loader->getType('foo'));
    }
}

class ConcreteExtension extends AbstractExtension
{
    protected function loadTypes()
    {
        return array(new FooType());
    }

    protected function loadTypeGuesser()
    {
    }
}
PK/1[�g	�33,Form/Symfony/Component/Form/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Form Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK/1[�ԍZP5P5DSecurity/Symfony/Component/Security/Acl/Tests/Voter/AclVoterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Voter;

use Symfony\Component\Security\Acl\Exception\NoAceFoundException;
use Symfony\Component\Security\Acl\Voter\FieldVote;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Acl\Voter\AclVoter;

class AclVoterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getSupportsAttributeTests
     */
    public function testSupportsAttribute($attribute, $supported)
    {
        list($voter,, $permissionMap,,) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('contains')
            ->with($this->identicalTo($attribute))
            ->will($this->returnValue($supported))
        ;

        $this->assertSame($supported, $voter->supportsAttribute($attribute));
    }

    public function getSupportsAttributeTests()
    {
        return array(
            array('foo', true),
            array('foo', false),
        );
    }

    /**
     * @dataProvider getSupportsClassTests
     */
    public function testSupportsClass($class)
    {
        list($voter,,,,) = $this->getVoter();

        $this->assertTrue($voter->supportsClass($class));
    }

    public function getSupportsClassTests()
    {
        return array(
            array('foo'),
            array('bar'),
            array('moo'),
        );
    }

    public function testVote()
    {
        list($voter,, $permissionMap,,) = $this->getVoter();
        $permissionMap
            ->expects($this->atLeastOnce())
            ->method('getMasks')
            ->will($this->returnValue(null))
        ;

        $this->assertSame(VoterInterface::ACCESS_ABSTAIN, $voter->vote($this->getToken(), null, array('VIEW', 'EDIT', 'DELETE')));
    }

    /**
     * @dataProvider getTrueFalseTests
     */
    public function testVoteWhenNoObjectIsPassed($allowIfObjectIdentityUnavailable)
    {
        list($voter,, $permissionMap,,) = $this->getVoter($allowIfObjectIdentityUnavailable);
        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->will($this->returnValue(array()))
        ;

        if ($allowIfObjectIdentityUnavailable) {
            $vote = VoterInterface::ACCESS_GRANTED;
        } else {
            $vote = VoterInterface::ACCESS_ABSTAIN;
        }

        $this->assertSame($vote, $voter->vote($this->getToken(), null, array('VIEW')));
    }

    /**
     * @dataProvider getTrueFalseTests
     */
    public function testVoteWhenOidStrategyReturnsNull($allowIfUnavailable)
    {
        list($voter,, $permissionMap, $oidStrategy,) = $this->getVoter($allowIfUnavailable);
        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->will($this->returnValue(array()))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue(null))
        ;

        if ($allowIfUnavailable) {
            $vote = VoterInterface::ACCESS_GRANTED;
        } else {
            $vote = VoterInterface::ACCESS_ABSTAIN;
        }

        $this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
    }

    public function getTrueFalseTests()
    {
        return array(array(true), array(false));
    }

    public function testVoteNoAclFound()
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->will($this->returnValue(array()))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->throwException(new AclNotFoundException('Not found.')))
        ;

        $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
    }

    /**
     * @dataProvider getTrueFalseTests
     */
    public function testVoteGrantsAccess($grant)
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->with($this->equalTo('VIEW'))
            ->will($this->returnValue($masks = array(1, 2, 3)))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
        ;

        $acl
            ->expects($this->once())
            ->method('isGranted')
            ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
            ->will($this->returnValue($grant))
        ;

        if ($grant) {
            $vote = VoterInterface::ACCESS_GRANTED;
        } else {
            $vote = VoterInterface::ACCESS_DENIED;
        }

        $this->assertSame($vote, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
    }

    public function testVoteNoAceFound()
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->with($this->equalTo('VIEW'))
            ->will($this->returnValue($masks = array(1, 2, 3)))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
        ;

        $acl
            ->expects($this->once())
            ->method('isGranted')
            ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
            ->will($this->throwException(new NoAceFoundException('No ACE')))
        ;

        $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new \stdClass(), array('VIEW')));
    }

    /**
     * @dataProvider getTrueFalseTests
     */
    public function testVoteGrantsFieldAccess($grant)
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->with($this->equalTo('VIEW'))
            ->will($this->returnValue($masks = array(1, 2, 3)))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
        ;

        $acl
            ->expects($this->once())
            ->method('isFieldGranted')
            ->with($this->identicalTo('foo'), $this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
            ->will($this->returnValue($grant))
        ;

        if ($grant) {
            $vote = VoterInterface::ACCESS_GRANTED;
        } else {
            $vote = VoterInterface::ACCESS_DENIED;
        }

        $this->assertSame($vote, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
    }

    public function testVoteNoFieldAceFound()
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->with($this->equalTo('VIEW'))
            ->will($this->returnValue($masks = array(1, 2, 3)))
        ;

        $oidStrategy
            ->expects($this->once())
            ->method('getObjectIdentity')
            ->will($this->returnValue($oid = new ObjectIdentity('1', 'Foo')))
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
        ;

        $acl
            ->expects($this->once())
            ->method('isFieldGranted')
            ->with($this->identicalTo('foo'), $this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
            ->will($this->throwException(new NoAceFoundException('No ACE')))
        ;

        $this->assertSame(VoterInterface::ACCESS_DENIED, $voter->vote($this->getToken(), new FieldVote(new \stdClass(), 'foo'), array('VIEW')));
    }

    public function testWhenReceivingAnObjectIdentityInterfaceWeDontRetrieveANewObjectIdentity()
    {
        list($voter, $provider, $permissionMap, $oidStrategy, $sidStrategy) = $this->getVoter();

        $oid = new ObjectIdentity('someID','someType');

        $permissionMap
            ->expects($this->once())
            ->method('getMasks')
            ->with($this->equalTo('VIEW'))
            ->will($this->returnValue($masks = array(1, 2, 3)))
        ;

        $oidStrategy
            ->expects($this->never())
            ->method('getObjectIdentity')
        ;

        $sidStrategy
            ->expects($this->once())
            ->method('getSecurityIdentities')
            ->will($this->returnValue($sids = array(new UserSecurityIdentity('johannes', 'Foo'), new RoleSecurityIdentity('ROLE_FOO'))))
        ;

        $provider
            ->expects($this->once())
            ->method('findAcl')
            ->with($this->equalTo($oid), $this->equalTo($sids))
            ->will($this->returnValue($acl = $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface')))
        ;

        $acl
            ->expects($this->once())
            ->method('isGranted')
            ->with($this->identicalTo($masks), $this->equalTo($sids), $this->isFalse())
            ->will($this->throwException(new NoAceFoundException('No ACE')))
        ;

        $voter->vote($this->getToken(), $oid, array('VIEW'));
    }

    protected function getToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }

    protected function getVoter($allowIfObjectIdentityUnavailable = true)
    {
        $provider = $this->getMock('Symfony\Component\Security\Acl\Model\AclProviderInterface');
        $permissionMap = $this->getMock('Symfony\Component\Security\Acl\Permission\PermissionMapInterface');
        $oidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\ObjectIdentityRetrievalStrategyInterface');
        $sidStrategy = $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityRetrievalStrategyInterface');

        return array(
            new AclVoter($provider, $oidStrategy, $sidStrategy, $permissionMap, null, $allowIfObjectIdentityUnavailable),
            $provider,
            $permissionMap,
            $oidStrategy,
            $sidStrategy,
        );
    }
}
PK/1[�޻>�Q�QMSecurity/Symfony/Component/Security/Acl/Tests/Dbal/MutableAclProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Dbal;

use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Model\FieldEntryInterface;
use Symfony\Component\Security\Acl\Model\AuditableEntryInterface;
use Symfony\Component\Security\Acl\Model\EntryInterface;
use Symfony\Component\Security\Acl\Domain\Entry;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Exception\AclNotFoundException;
use Symfony\Component\Security\Acl\Exception\ConcurrentModificationException;
use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Dbal\MutableAclProvider;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\DriverManager;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;

class MutableAclProviderTest extends \PHPUnit_Framework_TestCase
{
    protected $con;

    public static function assertAceEquals(EntryInterface $a, EntryInterface $b)
    {
        self::assertInstanceOf(get_class($a), $b);

        foreach (array('getId', 'getMask', 'getStrategy', 'isGranting') as $getter) {
            self::assertSame($a->$getter(), $b->$getter());
        }

        self::assertTrue($a->getSecurityIdentity()->equals($b->getSecurityIdentity()));
        self::assertSame($a->getAcl()->getId(), $b->getAcl()->getId());

        if ($a instanceof AuditableEntryInterface) {
            self::assertSame($a->isAuditSuccess(), $b->isAuditSuccess());
            self::assertSame($a->isAuditFailure(), $b->isAuditFailure());
        }

        if ($a instanceof FieldEntryInterface) {
            self::assertSame($a->getField(), $b->getField());
        }
    }

    /**
     * @expectedException \Symfony\Component\Security\Acl\Exception\AclAlreadyExistsException
     */
    public function testCreateAclThrowsExceptionWhenAclAlreadyExists()
    {
        $provider = $this->getProvider();
        $oid = new ObjectIdentity('123456', 'FOO');
        $provider->createAcl($oid);
        $provider->createAcl($oid);
    }

    public function testCreateAcl()
    {
        $provider = $this->getProvider();
        $oid = new ObjectIdentity('123456', 'FOO');
        $acl = $provider->createAcl($oid);
        $cachedAcl = $provider->findAcl($oid);

        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl);
        $this->assertSame($acl, $cachedAcl);
        $this->assertTrue($acl->getObjectIdentity()->equals($oid));
    }

    public function testDeleteAcl()
    {
        $provider = $this->getProvider();
        $oid = new ObjectIdentity(1, 'Foo');
        $acl = $provider->createAcl($oid);

        $provider->deleteAcl($oid);
        $loadedAcls = $this->getField($provider, 'loadedAcls');
        $this->assertCount(0, $loadedAcls['Foo']);

        try {
            $provider->findAcl($oid);
            $this->fail('ACL has not been properly deleted.');
        } catch (AclNotFoundException $notFound) { }
    }

    public function testDeleteAclDeletesChildren()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $parentAcl = $provider->createAcl(new ObjectIdentity(2, 'Foo'));
        $acl->setParentAcl($parentAcl);
        $provider->updateAcl($acl);
        $provider->deleteAcl($parentAcl->getObjectIdentity());

        try {
            $provider->findAcl(new ObjectIdentity(1, 'Foo'));
            $this->fail('Child-ACLs have not been deleted.');
        } catch (AclNotFoundException $notFound) { }
    }

    public function testFindAclsAddsPropertyListener()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));

        $propertyChanges = $this->getField($provider, 'propertyChanges');
        $this->assertCount(1, $propertyChanges);
        $this->assertTrue($propertyChanges->contains($acl));
        $this->assertEquals(array(), $propertyChanges->offsetGet($acl));

        $listeners = $this->getField($acl, 'listeners');
        $this->assertSame($provider, $listeners[0]);
    }

    public function testFindAclsAddsPropertyListenerOnlyOnce()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $acl = $provider->findAcl(new ObjectIdentity(1, 'Foo'));

        $propertyChanges = $this->getField($provider, 'propertyChanges');
        $this->assertCount(1, $propertyChanges);
        $this->assertTrue($propertyChanges->contains($acl));
        $this->assertEquals(array(), $propertyChanges->offsetGet($acl));

        $listeners = $this->getField($acl, 'listeners');
        $this->assertCount(1, $listeners);
        $this->assertSame($provider, $listeners[0]);
    }

    public function testFindAclsAddsPropertyListenerToParentAcls()
    {
        $provider = $this->getProvider();
        $this->importAcls($provider, array(
            'main' => array(
                'object_identifier' => '1',
                'class_type' => 'foo',
                'parent_acl' => 'parent',
            ),
            'parent' => array(
                'object_identifier' => '1',
                'class_type' => 'anotherFoo',
            )
        ));

        $propertyChanges = $this->getField($provider, 'propertyChanges');
        $this->assertCount(0, $propertyChanges);

        $acl = $provider->findAcl(new ObjectIdentity('1', 'foo'));
        $this->assertCount(2, $propertyChanges);
        $this->assertTrue($propertyChanges->contains($acl));
        $this->assertTrue($propertyChanges->contains($acl->getParentAcl()));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testPropertyChangedDoesNotTrackUnmanagedAcls()
    {
        $provider = $this->getProvider();
        $acl = new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), array(), false);

        $provider->propertyChanged($acl, 'classAces', array(), array('foo'));
    }

    public function testPropertyChangedTracksChangesToAclProperties()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $propertyChanges = $this->getField($provider, 'propertyChanges');

        $provider->propertyChanged($acl, 'entriesInheriting', false, true);
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertTrue(isset($changes['entriesInheriting']));
        $this->assertFalse($changes['entriesInheriting'][0]);
        $this->assertTrue($changes['entriesInheriting'][1]);

        $provider->propertyChanged($acl, 'entriesInheriting', true, false);
        $provider->propertyChanged($acl, 'entriesInheriting', false, true);
        $provider->propertyChanged($acl, 'entriesInheriting', true, false);
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertFalse(isset($changes['entriesInheriting']));
    }

    public function testPropertyChangedTracksChangesToAceProperties()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $ace = new Entry(1, $acl, new UserSecurityIdentity('foo', 'FooClass'), 'all', 1, true, true, true);
        $ace2 = new Entry(2, $acl, new UserSecurityIdentity('foo', 'FooClass'), 'all', 1, true, true, true);
        $propertyChanges = $this->getField($provider, 'propertyChanges');

        $provider->propertyChanged($ace, 'mask', 1, 3);
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertTrue(isset($changes['aces']));
        $this->assertInstanceOf('\SplObjectStorage', $changes['aces']);
        $this->assertTrue($changes['aces']->contains($ace));
        $aceChanges = $changes['aces']->offsetGet($ace);
        $this->assertTrue(isset($aceChanges['mask']));
        $this->assertEquals(1, $aceChanges['mask'][0]);
        $this->assertEquals(3, $aceChanges['mask'][1]);

        $provider->propertyChanged($ace, 'strategy', 'all', 'any');
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertTrue(isset($changes['aces']));
        $this->assertInstanceOf('\SplObjectStorage', $changes['aces']);
        $this->assertTrue($changes['aces']->contains($ace));
        $aceChanges = $changes['aces']->offsetGet($ace);
        $this->assertTrue(isset($aceChanges['mask']));
        $this->assertTrue(isset($aceChanges['strategy']));
        $this->assertEquals('all', $aceChanges['strategy'][0]);
        $this->assertEquals('any', $aceChanges['strategy'][1]);

        $provider->propertyChanged($ace, 'mask', 3, 1);
        $changes = $propertyChanges->offsetGet($acl);
        $aceChanges = $changes['aces']->offsetGet($ace);
        $this->assertFalse(isset($aceChanges['mask']));
        $this->assertTrue(isset($aceChanges['strategy']));

        $provider->propertyChanged($ace2, 'mask', 1, 3);
        $provider->propertyChanged($ace, 'strategy', 'any', 'all');
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertTrue(isset($changes['aces']));
        $this->assertFalse($changes['aces']->contains($ace));
        $this->assertTrue($changes['aces']->contains($ace2));

        $provider->propertyChanged($ace2, 'mask', 3, 4);
        $provider->propertyChanged($ace2, 'mask', 4, 1);
        $changes = $propertyChanges->offsetGet($acl);
        $this->assertFalse(isset($changes['aces']));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testUpdateAclDoesNotAcceptUntrackedAcls()
    {
        $provider = $this->getProvider();
        $acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), array(), true);
        $provider->updateAcl($acl);
    }

    public function testUpdateDoesNothingWhenThereAreNoChanges()
    {
        $con = $this->getMock('Doctrine\DBAL\Connection', array(), array(), '', false);
        $con
            ->expects($this->never())
            ->method('beginTransaction')
        ;
        $con
            ->expects($this->never())
            ->method('executeQuery')
        ;

        $provider = new MutableAclProvider($con, new PermissionGrantingStrategy(), array());
        $acl = new Acl(1, new ObjectIdentity(1, 'Foo'), new PermissionGrantingStrategy(), array(), true);
        $propertyChanges = $this->getField($provider, 'propertyChanges');
        $propertyChanges->offsetSet($acl, array());
        $provider->updateAcl($acl);
    }

    public function testUpdateAclThrowsExceptionOnConcurrentModificationOfSharedProperties()
    {
        $provider = $this->getProvider();
        $acl1 = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $acl2 = $provider->createAcl(new ObjectIdentity(2, 'Foo'));
        $acl3 = $provider->createAcl(new ObjectIdentity(1, 'AnotherFoo'));
        $sid = new RoleSecurityIdentity('ROLE_FOO');

        $acl1->insertClassAce($sid, 1);
        $acl3->insertClassAce($sid, 1);
        $provider->updateAcl($acl1);
        $provider->updateAcl($acl3);

        $acl2->insertClassAce($sid, 16);
        $provider->updateAcl($acl2);

        $acl1->insertClassAce($sid, 3);
        $acl2->insertClassAce($sid, 5);
        try {
            $provider->updateAcl($acl1);
            $this->fail('Provider failed to detect a concurrent modification.');
        } catch (ConcurrentModificationException $ex) { }
    }

    public function testUpdateAcl()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $sid = new UserSecurityIdentity('johannes', 'FooClass');
        $acl->setEntriesInheriting(!$acl->isEntriesInheriting());

        $acl->insertObjectAce($sid, 1);
        $acl->insertClassAce($sid, 5, 0, false);
        $acl->insertObjectAce($sid, 2, 1, true);
        $acl->insertClassFieldAce('field', $sid, 2, 0, true);
        $provider->updateAcl($acl);

        $acl->updateObjectAce(0, 3);
        $acl->deleteObjectAce(1);
        $acl->updateObjectAuditing(0, true, false);
        $acl->updateClassFieldAce(0, 'field', 15);
        $provider->updateAcl($acl);

        $reloadProvider = $this->getProvider();
        $reloadedAcl = $reloadProvider->findAcl(new ObjectIdentity(1, 'Foo'));
        $this->assertNotSame($acl, $reloadedAcl);
        $this->assertSame($acl->isEntriesInheriting(), $reloadedAcl->isEntriesInheriting());

        $aces = $acl->getObjectAces();
        $reloadedAces = $reloadedAcl->getObjectAces();
        $this->assertEquals(count($aces), count($reloadedAces));
        foreach ($aces as $index => $ace) {
            $this->assertAceEquals($ace, $reloadedAces[$index]);
        }
    }

    public function testUpdateAclWorksForChangingTheParentAcl()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));
        $parentAcl = $provider->createAcl(new ObjectIdentity(1, 'AnotherFoo'));
        $acl->setParentAcl($parentAcl);
        $provider->updateAcl($acl);

        $reloadProvider = $this->getProvider();
        $reloadedAcl = $reloadProvider->findAcl(new ObjectIdentity(1, 'Foo'));
        $this->assertNotSame($acl, $reloadedAcl);
        $this->assertSame($parentAcl->getId(), $reloadedAcl->getParentAcl()->getId());
    }

    public function testUpdateAclUpdatesChildAclsCorrectly()
    {
        $provider = $this->getProvider();
        $acl = $provider->createAcl(new ObjectIdentity(1, 'Foo'));

        $parentAcl = $provider->createAcl(new ObjectIdentity(1, 'Bar'));
        $acl->setParentAcl($parentAcl);
        $provider->updateAcl($acl);

        $parentParentAcl = $provider->createAcl(new ObjectIdentity(1, 'Baz'));
        $parentAcl->setParentAcl($parentParentAcl);
        $provider->updateAcl($parentAcl);

        $newParentParentAcl = $provider->createAcl(new ObjectIdentity(2, 'Baz'));
        $parentAcl->setParentAcl($newParentParentAcl);
        $provider->updateAcl($parentAcl);

        $reloadProvider = $this->getProvider();
        $reloadedAcl = $reloadProvider->findAcl(new ObjectIdentity(1, 'Foo'));
        $this->assertEquals($newParentParentAcl->getId(), $reloadedAcl->getParentAcl()->getParentAcl()->getId());
    }

    public function testUpdateAclInsertingMultipleObjectFieldAcesThrowsDBConstraintViolations()
    {
        $provider = $this->getProvider();
        $oid = new ObjectIdentity(1, 'Foo');
        $sid1 = new UserSecurityIdentity('johannes', 'FooClass');
        $sid2 = new UserSecurityIdentity('guilro', 'FooClass');
        $sid3 = new UserSecurityIdentity('bmaz', 'FooClass');
        $fieldName = 'fieldName';

        $acl = $provider->createAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid1, 4);
        $provider->updateAcl($acl);

        $acl = $provider->findAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid2, 4);
        $provider->updateAcl($acl);

        $acl = $provider->findAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid3, 4);
        $provider->updateAcl($acl);
    }

    public function testUpdateAclDeletingObjectFieldAcesThrowsDBConstraintViolations()
    {
        $provider = $this->getProvider();
        $oid = new ObjectIdentity(1, 'Foo');
        $sid1 = new UserSecurityIdentity('johannes', 'FooClass');
        $sid2 = new UserSecurityIdentity('guilro', 'FooClass');
        $sid3 = new UserSecurityIdentity('bmaz', 'FooClass');
        $fieldName = 'fieldName';

        $acl = $provider->createAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid1, 4);
        $provider->updateAcl($acl);

        $acl = $provider->findAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid2, 4);
        $provider->updateAcl($acl);

        $index = 0;
        $acl->deleteObjectFieldAce($index, $fieldName);
        $provider->updateAcl($acl);

        $acl = $provider->findAcl($oid);
        $acl->insertObjectFieldAce($fieldName, $sid3, 4);
        $provider->updateAcl($acl);
    }

    /**
     * Data must have the following format:
     * array(
     *     *name* => array(
     *         'object_identifier' => *required*
     *         'class_type' => *required*,
     *         'parent_acl' => *name (optional)*
     *     ),
     * )
     *
     * @param AclProvider $provider
     * @param array       $data
     * @throws \InvalidArgumentException
     * @throws \Exception
     */
    protected function importAcls(AclProvider $provider, array $data)
    {
        $aclIds = $parentAcls = array();
        $con = $this->getField($provider, 'connection');
        $con->beginTransaction();
        try {
            foreach ($data as $name => $aclData) {
                if (!isset($aclData['object_identifier'], $aclData['class_type'])) {
                    throw new \InvalidArgumentException('"object_identifier", and "class_type" must be present.');
                }

                $this->callMethod($provider, 'createObjectIdentity', array(new ObjectIdentity($aclData['object_identifier'], $aclData['class_type'])));
                $aclId = $con->lastInsertId();
                $aclIds[$name] = $aclId;

                $sql = $this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclId));
                $con->executeQuery($sql);

                if (isset($aclData['parent_acl'])) {
                    if (isset($aclIds[$aclData['parent_acl']])) {
                        $con->executeQuery("UPDATE acl_object_identities SET parent_object_identity_id = ".$aclIds[$aclData['parent_acl']]." WHERE id = ".$aclId);
                        $con->executeQuery($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclIds[$aclData['parent_acl']])));
                    } else {
                        $parentAcls[$aclId] = $aclData['parent_acl'];
                    }
                }
            }

            foreach ($parentAcls as $aclId => $name) {
                if (!isset($aclIds[$name])) {
                    throw new \InvalidArgumentException(sprintf('"%s" does not exist.', $name));
                }

                $con->executeQuery(sprintf("UPDATE acl_object_identities SET parent_object_identity_id = %d WHERE id = %d", $aclIds[$name], $aclId));
                $con->executeQuery($this->callMethod($provider, 'getInsertObjectIdentityRelationSql', array($aclId, $aclIds[$name])));
            }

            $con->commit();
        } catch (\Exception $e) {
            $con->rollBack();

            throw $e;
        }
    }

    protected function callMethod($object, $method, array $args)
    {
        $method = new \ReflectionMethod($object, $method);
        $method->setAccessible(true);

        return $method->invokeArgs($object, $args);
    }

    protected function setUp()
    {
        if (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
            self::markTestSkipped('This test requires SQLite support in your environment');
        }

        $this->con = DriverManager::getConnection(array(
            'driver' => 'pdo_sqlite',
            'memory' => true,
        ));

        // import the schema
        $schema = new Schema($this->getOptions());
        foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
            $this->con->exec($sql);
        }
    }

    protected function tearDown()
    {
        $this->con = null;
    }

    protected function getField($object, $field)
    {
        $reflection = new \ReflectionProperty($object, $field);
        $reflection->setAccessible(true);

        return $reflection->getValue($object);
    }

    public function setField($object, $field, $value)
    {
        $reflection = new \ReflectionProperty($object, $field);
        $reflection->setAccessible(true);
        $reflection->setValue($object, $value);
        $reflection->setAccessible(false);
    }

    protected function getOptions()
    {
        return array(
            'oid_table_name' => 'acl_object_identities',
            'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
            'class_table_name' => 'acl_classes',
            'sid_table_name' => 'acl_security_identities',
            'entry_table_name' => 'acl_entries',
        );
    }

    protected function getStrategy()
    {
        return new PermissionGrantingStrategy();
    }

    protected function getProvider($cache = null)
    {
        return new MutableAclProvider($this->con, $this->getStrategy(), $this->getOptions(), $cache);
    }
}
PK/1[�
�� � OSecurity/Symfony/Component/Security/Acl/Tests/Dbal/AclProviderBenchmarkTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Dbal;

use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\DriverManager;

/**
 * @group benchmark
 */
class AclProviderBenchmarkTest extends \PHPUnit_Framework_TestCase
{
    /** @var \Doctrine\DBAL\Connection */
    protected $con;
    protected $insertClassStmt;
    protected $insertSidStmt;
    protected $insertOidAncestorStmt;
    protected $insertOidStmt;
    protected $insertEntryStmt;

    protected function setUp()
    {
        try {
            $this->con = DriverManager::getConnection(array(
                'driver' => 'pdo_mysql',
                'host' => 'localhost',
                'user' => 'root',
                'dbname' => 'testdb',
            ));
            $this->con->connect();
        } catch (\Exception $e) {
            $this->markTestSkipped('Unable to connect to the database: '.$e->getMessage());
        }
    }

    protected function tearDown()
    {
        $this->con = null;
    }

    public function testFindAcls()
    {
        // $this->generateTestData();

        // get some random test object identities from the database
        $oids = array();
        $stmt = $this->con->executeQuery("SELECT object_identifier, class_type FROM acl_object_identities o INNER JOIN acl_classes c ON c.id = o.class_id ORDER BY RAND() LIMIT 25");
        foreach ($stmt->fetchAll() as $oid) {
            $oids[] = new ObjectIdentity($oid['object_identifier'], $oid['class_type']);
        }

        $provider = $this->getProvider();

        $start = microtime(true);
        $provider->findAcls($oids);
        $time = microtime(true) - $start;
        echo "Total Time: ".$time."s\n";
    }

    /**
     * This generates a huge amount of test data to be used mainly for benchmarking
     * purposes, not so much for testing. That's why it's not called by default.
     */
    protected function generateTestData()
    {
        $sm = $this->con->getSchemaManager();
        $sm->dropAndCreateDatabase('testdb');
        $this->con->exec("USE testdb");

        // import the schema
        $schema = new Schema($options = $this->getOptions());
        foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
            $this->con->exec($sql);
        }

        // setup prepared statements
        $this->insertClassStmt = $this->con->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
        $this->insertSidStmt = $this->con->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
        $this->insertOidStmt = $this->con->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
        $this->insertEntryStmt = $this->con->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        $this->insertOidAncestorStmt = $this->con->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');

        for ($i=0; $i<40000; $i++) {
            $this->generateAclHierarchy();
        }
    }

    protected function generateAclHierarchy()
    {
        $rootId = $this->generateAcl($this->chooseClassId(), null, array());

        $this->generateAclLevel(rand(1, 15), $rootId, array($rootId));
    }

    protected function generateAclLevel($depth, $parentId, $ancestors)
    {
        $level = count($ancestors);
        for ($i=0,$t=rand(1, 10); $i<$t; $i++) {
            $id = $this->generateAcl($this->chooseClassId(), $parentId, $ancestors);

            if ($level < $depth) {
                $this->generateAclLevel($depth, $id, array_merge($ancestors, array($id)));
            }
        }
    }

    protected function chooseClassId()
    {
        static $id = 1000;

        if ($id === 1000 || ($id < 1500 && rand(0, 1))) {
            $this->insertClassStmt->execute(array($id, $this->getRandomString(rand(20, 100), 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\_')));
            $id += 1;

            return $id-1;
        } else {
            return rand(1000, $id-1);
        }
    }

    protected function generateAcl($classId, $parentId, $ancestors)
    {
        static $id = 1000;

        $this->insertOidStmt->execute(array(
            $id,
            $classId,
            $this->getRandomString(rand(20, 50)),
            $parentId,
            rand(0, 1),
        ));

        $this->insertOidAncestorStmt->execute(array($id, $id));
        foreach ($ancestors as $ancestor) {
            $this->insertOidAncestorStmt->execute(array($id, $ancestor));
        }

        $this->generateAces($classId, $id);
        $id += 1;

        return $id-1;
    }

    protected function chooseSid()
    {
        static $id = 1000;

        if ($id === 1000 || ($id < 11000 && rand(0, 1))) {
            $this->insertSidStmt->execute(array(
                $id,
                $this->getRandomString(rand(5, 30)),
                rand(0, 1)
            ));
            $id += 1;

            return $id-1;
        } else {
            return rand(1000, $id-1);
        }
    }

    protected function generateAces($classId, $objectId)
    {
        static $id = 1000;

        $sids = array();
        $fieldOrder = array();

        for ($i=0; $i<=30; $i++) {
            $fieldName = rand(0, 1) ? null : $this->getRandomString(rand(10, 20));

            do {
                $sid = $this->chooseSid();
            } while (array_key_exists($sid, $sids) && in_array($fieldName, $sids[$sid], true));

            $fieldOrder[$fieldName] = array_key_exists($fieldName, $fieldOrder) ? $fieldOrder[$fieldName]+1 : 0;
            if (!isset($sids[$sid])) {
                $sids[$sid] = array();
            }
            $sids[$sid][] = $fieldName;

            $strategy = rand(0, 2);
            if ($strategy === 0) {
                $strategy = PermissionGrantingStrategy::ALL;
            } elseif ($strategy === 1) {
                $strategy = PermissionGrantingStrategy::ANY;
            } else {
                $strategy = PermissionGrantingStrategy::EQUAL;
            }

            // id, cid, oid, field, order, sid, mask, granting, strategy, a success, a failure
            $this->insertEntryStmt->execute(array(
                $id,
                $classId,
                rand(0, 5) ? $objectId : null,
                $fieldName,
                $fieldOrder[$fieldName],
                $sid,
                $this->generateMask(),
                rand(0, 1),
                $strategy,
                rand(0, 1),
                rand(0, 1),
            ));

            $id += 1;
        }
    }

    protected function generateMask()
    {
        $i = rand(1, 30);
        $mask = 0;

        while ($i <= 30) {
            $mask |= 1 << rand(0, 30);
            $i++;
        }

        return $mask;
    }

    protected function getRandomString($length, $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
    {
        $s = '';
        $cLength = strlen($chars);

        while (strlen($s) < $length) {
            $s .= $chars[mt_rand(0, $cLength-1)];
        }

        return $s;
    }

    protected function getOptions()
    {
        return array(
            'oid_table_name' => 'acl_object_identities',
            'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
            'class_table_name' => 'acl_classes',
            'sid_table_name' => 'acl_security_identities',
            'entry_table_name' => 'acl_entries',
        );
    }

    protected function getStrategy()
    {
        return new PermissionGrantingStrategy();
    }

    protected function getProvider()
    {
        return new AclProvider($this->con, $this->getStrategy(), $this->getOptions());
    }
}
PK/1[�'(��'�'FSecurity/Symfony/Component/Security/Acl/Tests/Dbal/AclProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Dbal;

use Symfony\Component\Security\Acl\Dbal\AclProvider;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Dbal\Schema;
use Doctrine\DBAL\DriverManager;

class AclProviderTest extends \PHPUnit_Framework_TestCase
{
    protected $con;
    protected $insertClassStmt;
    protected $insertEntryStmt;
    protected $insertOidStmt;
    protected $insertOidAncestorStmt;
    protected $insertSidStmt;

    /**
     * @expectedException \Symfony\Component\Security\Acl\Exception\AclNotFoundException
     * @expectedMessage There is no ACL for the given object identity.
     */
    public function testFindAclThrowsExceptionWhenNoAclExists()
    {
        $this->getProvider()->findAcl(new ObjectIdentity('foo', 'foo'));
    }

    public function testFindAclsThrowsExceptionUnlessAnACLIsFoundForEveryOID()
    {
        $oids = array();
        $oids[] = new ObjectIdentity('1', 'foo');
        $oids[] = new ObjectIdentity('foo', 'foo');

        try {
            $this->getProvider()->findAcls($oids);

            $this->fail('Provider did not throw an expected exception.');
        } catch (\Exception $ex) {
            $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\AclNotFoundException', $ex);
            $this->assertInstanceOf('Symfony\Component\Security\Acl\Exception\NotAllAclsFoundException', $ex);

            $partialResult = $ex->getPartialResult();
            $this->assertTrue($partialResult->contains($oids[0]));
            $this->assertFalse($partialResult->contains($oids[1]));
        }
    }

    public function testFindAcls()
    {
        $oids = array();
        $oids[] = new ObjectIdentity('1', 'foo');
        $oids[] = new ObjectIdentity('2', 'foo');

        $provider = $this->getProvider();

        $acls = $provider->findAcls($oids);
        $this->assertInstanceOf('SplObjectStorage', $acls);
        $this->assertCount(2, $acls);
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl0 = $acls->offsetGet($oids[0]));
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl1 = $acls->offsetGet($oids[1]));
        $this->assertTrue($oids[0]->equals($acl0->getObjectIdentity()));
        $this->assertTrue($oids[1]->equals($acl1->getObjectIdentity()));
    }

    public function testFindAclsWithDifferentTypes()
    {
        $oids = array();
        $oids[] = new ObjectIdentity('123', 'Bundle\SomeVendor\MyBundle\Entity\SomeEntity');
        $oids[] = new ObjectIdentity('123', 'Bundle\MyBundle\Entity\AnotherEntity');

        $provider = $this->getProvider();

        $acls = $provider->findAcls($oids);
        $this->assertInstanceOf('SplObjectStorage', $acls);
        $this->assertCount(2, $acls);
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl0 = $acls->offsetGet($oids[0]));
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl1 = $acls->offsetGet($oids[1]));
        $this->assertTrue($oids[0]->equals($acl0->getObjectIdentity()));
        $this->assertTrue($oids[1]->equals($acl1->getObjectIdentity()));
    }

    public function testFindAclCachesAclInMemory()
    {
        $oid = new ObjectIdentity('1', 'foo');
        $provider = $this->getProvider();

        $acl = $provider->findAcl($oid);
        $this->assertSame($acl, $cAcl = $provider->findAcl($oid));

        $cAces = $cAcl->getObjectAces();
        foreach ($acl->getObjectAces() as $index => $ace) {
            $this->assertSame($ace, $cAces[$index]);
        }
    }

    public function testFindAcl()
    {
        $oid = new ObjectIdentity('1', 'foo');
        $provider = $this->getProvider();

        $acl = $provider->findAcl($oid);

        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Acl', $acl);
        $this->assertTrue($oid->equals($acl->getObjectIdentity()));
        $this->assertEquals(4, $acl->getId());
        $this->assertCount(0, $acl->getClassAces());
        $this->assertCount(0, $this->getField($acl, 'classFieldAces'));
        $this->assertCount(3, $acl->getObjectAces());
        $this->assertCount(0, $this->getField($acl, 'objectFieldAces'));

        $aces = $acl->getObjectAces();
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\Entry', $aces[0]);
        $this->assertTrue($aces[0]->isGranting());
        $this->assertTrue($aces[0]->isAuditSuccess());
        $this->assertTrue($aces[0]->isAuditFailure());
        $this->assertEquals('all', $aces[0]->getStrategy());
        $this->assertSame(2, $aces[0]->getMask());

        // check ACE are in correct order
        $i = 0;
        foreach ($aces as $index => $ace) {
            $this->assertEquals($i, $index);
            $i++;
        }

        $sid = $aces[0]->getSecurityIdentity();
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Domain\UserSecurityIdentity', $sid);
        $this->assertEquals('john.doe', $sid->getUsername());
        $this->assertEquals('SomeClass', $sid->getClass());
    }

    protected function setUp()
    {
        if (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
            self::markTestSkipped('This test requires SQLite support in your environment');
        }

        $this->con = DriverManager::getConnection(array(
            'driver' => 'pdo_sqlite',
            'memory' => true,
        ));

        // import the schema
        $schema = new Schema($options = $this->getOptions());
        foreach ($schema->toSql($this->con->getDatabasePlatform()) as $sql) {
            $this->con->exec($sql);
        }

        // populate the schema with some test data
        $this->insertClassStmt = $this->con->prepare('INSERT INTO acl_classes (id, class_type) VALUES (?, ?)');
        foreach ($this->getClassData() as $data) {
            $this->insertClassStmt->execute($data);
        }

        $this->insertSidStmt = $this->con->prepare('INSERT INTO acl_security_identities (id, identifier, username) VALUES (?, ?, ?)');
        foreach ($this->getSidData() as $data) {
            $this->insertSidStmt->execute($data);
        }

        $this->insertOidStmt = $this->con->prepare('INSERT INTO acl_object_identities (id, class_id, object_identifier, parent_object_identity_id, entries_inheriting) VALUES (?, ?, ?, ?, ?)');
        foreach ($this->getOidData() as $data) {
            $this->insertOidStmt->execute($data);
        }

        $this->insertEntryStmt = $this->con->prepare('INSERT INTO acl_entries (id, class_id, object_identity_id, field_name, ace_order, security_identity_id, mask, granting, granting_strategy, audit_success, audit_failure) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
        foreach ($this->getEntryData() as $data) {
            $this->insertEntryStmt->execute($data);
        }

        $this->insertOidAncestorStmt = $this->con->prepare('INSERT INTO acl_object_identity_ancestors (object_identity_id, ancestor_id) VALUES (?, ?)');
        foreach ($this->getOidAncestorData() as $data) {
            $this->insertOidAncestorStmt->execute($data);
        }
    }

    protected function tearDown()
    {
        $this->con = null;
    }

    protected function getField($object, $field)
    {
        $reflection = new \ReflectionProperty($object, $field);
        $reflection->setAccessible(true);

        return $reflection->getValue($object);
    }

    protected function getEntryData()
    {
        // id, cid, oid, field, order, sid, mask, granting, strategy, a success, a failure
        return array(
            array(1, 1, 1, null, 0, 1, 1, 1, 'all', 1, 1),
            array(2, 1, 1, null, 1, 2, 1 << 2 | 1 << 1, 0, 'any', 0, 0),
            array(3, 3, 4, null, 0, 1, 2, 1, 'all', 1, 1),
            array(4, 3, 4, null, 2, 2, 1, 1, 'all', 1, 1),
            array(5, 3, 4, null, 1, 3, 1, 1, 'all', 1, 1),
        );
    }

    protected function getOidData()
    {
        // id, cid, oid, parent_oid, entries_inheriting
        return array(
            array(1, 1, '123', null, 1),
            array(2, 2, '123', 1, 1),
            array(3, 2, 'i:3:123', 1, 1),
            array(4, 3, '1', 2, 1),
            array(5, 3, '2', 2, 1),
        );
    }

    protected function getOidAncestorData()
    {
        return array(
            array(1, 1),
            array(2, 1),
            array(2, 2),
            array(3, 1),
            array(3, 3),
            array(4, 2),
            array(4, 1),
            array(4, 4),
            array(5, 2),
            array(5, 1),
            array(5, 5),
        );
    }

    protected function getSidData()
    {
        return array(
            array(1, 'SomeClass-john.doe', 1),
            array(2, 'MyClass-john.doe@foo.com', 1),
            array(3, 'FooClass-123', 1),
            array(4, 'MooClass-ROLE_USER', 1),
            array(5, 'ROLE_USER', 0),
            array(6, 'IS_AUTHENTICATED_FULLY', 0),
        );
    }

    protected function getClassData()
    {
        return array(
            array(1, 'Bundle\SomeVendor\MyBundle\Entity\SomeEntity'),
            array(2, 'Bundle\MyBundle\Entity\AnotherEntity'),
            array(3, 'foo'),
        );
    }

    protected function getOptions()
    {
        return array(
            'oid_table_name' => 'acl_object_identities',
            'oid_ancestors_table_name' => 'acl_object_identity_ancestors',
            'class_table_name' => 'acl_classes',
            'sid_table_name' => 'acl_security_identities',
            'entry_table_name' => 'acl_entries',
        );
    }

    protected function getStrategy()
    {
        return new PermissionGrantingStrategy();
    }

    protected function getProvider()
    {
        return new AclProvider($this->con, $this->getStrategy(), $this->getOptions());
    }
}
PK01[�ˆ5HSecurity/Symfony/Component/Security/Acl/Tests/Domain/AuditLoggerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

class AuditLoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTestLogData
     */
    public function testLogIfNeeded($granting, $audit)
    {
        $logger = $this->getLogger();
        $ace = $this->getEntry();

        if (true === $granting) {
            $ace
                ->expects($this->once())
                ->method('isAuditSuccess')
                ->will($this->returnValue($audit))
           ;

           $ace
               ->expects($this->never())
               ->method('isAuditFailure')
           ;
        } else {
            $ace
                ->expects($this->never())
                ->method('isAuditSuccess')
            ;

            $ace
                ->expects($this->once())
                ->method('isAuditFailure')
                ->will($this->returnValue($audit))
            ;
        }

        if (true === $audit) {
            $logger
               ->expects($this->once())
               ->method('doLog')
               ->with($this->equalTo($granting), $this->equalTo($ace))
            ;
        } else {
            $logger
                ->expects($this->never())
                ->method('doLog')
            ;
        }

        $logger->logIfNeeded($granting, $ace);
    }

    public function getTestLogData()
    {
        return array(
            array(true, false),
            array(true, true),
            array(false, false),
            array(false, true),
        );
    }

    protected function getEntry()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface');
    }

    protected function getLogger()
    {
        return $this->getMockForAbstractClass('Symfony\Component\Security\Acl\Domain\AuditLogger');
    }
}
PK01[6x�}&&GSecurity/Symfony/Component/Security/Acl/Tests/Domain/FieldEntryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\FieldEntry;

class FieldEntryTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $ace = $this->getAce();

        $this->assertEquals('foo', $ace->getField());
    }

    public function testSerializeUnserialize()
    {
        $ace = $this->getAce();

        $serialized = serialize($ace);
        $uAce = unserialize($serialized);

        $this->assertNull($uAce->getAcl());
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity());
        $this->assertEquals($ace->getId(), $uAce->getId());
        $this->assertEquals($ace->getField(), $uAce->getField());
        $this->assertEquals($ace->getMask(), $uAce->getMask());
        $this->assertEquals($ace->getStrategy(), $uAce->getStrategy());
        $this->assertEquals($ace->isGranting(), $uAce->isGranting());
        $this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess());
        $this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure());
    }

    protected function getAce($acl = null, $sid = null)
    {
        if (null === $acl) {
            $acl = $this->getAcl();
        }
        if (null === $sid) {
            $sid = $this->getSid();
        }

        return new FieldEntry(
            123,
            $acl,
            'foo',
            $sid,
            'foostrat',
            123456,
            true,
            false,
            true
        );
    }

    protected function getAcl()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
    }

    protected function getSid()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
    }
}
PK01[��+&KSecurity/Symfony/Component/Security/Acl/Tests/Domain/ObjectIdentityTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain
{
    use Symfony\Component\Security\Acl\Domain\ObjectIdentity;

    class ObjectIdentityTest extends \PHPUnit_Framework_TestCase
    {
        public function testConstructor()
        {
            $id = new ObjectIdentity('fooid', 'footype');

            $this->assertEquals('fooid', $id->getIdentifier());
            $this->assertEquals('footype', $id->getType());
        }

        // Test that constructor never changes passed type, even with proxies
        public function testConstructorWithProxy()
        {
            $id = new ObjectIdentity('fooid', 'Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject');

            $this->assertEquals('fooid', $id->getIdentifier());
            $this->assertEquals('Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject', $id->getType());
        }

        public function testFromDomainObjectPrefersInterfaceOverGetId()
        {
            $domainObject = $this->getMock('Symfony\Component\Security\Acl\Model\DomainObjectInterface');
            $domainObject
                ->expects($this->once())
                ->method('getObjectIdentifier')
                ->will($this->returnValue('getObjectIdentifier()'))
            ;
            $domainObject
                ->expects($this->never())
                ->method('getId')
                ->will($this->returnValue('getId()'))
            ;

            $id = ObjectIdentity::fromDomainObject($domainObject);
            $this->assertEquals('getObjectIdentifier()', $id->getIdentifier());
        }

        public function testFromDomainObjectWithoutInterface()
        {
            $id = ObjectIdentity::fromDomainObject(new TestDomainObject());
            $this->assertEquals('getId()', $id->getIdentifier());
            $this->assertEquals('Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject', $id->getType());
        }

        public function testFromDomainObjectWithProxy()
        {
            $id = ObjectIdentity::fromDomainObject(new \Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject());
            $this->assertEquals('getId()', $id->getIdentifier());
            $this->assertEquals('Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject', $id->getType());
        }

        /**
         * @dataProvider getCompareData
         */
        public function testEquals($oid1, $oid2, $equal)
        {
            if ($equal) {
                $this->assertTrue($oid1->equals($oid2));
            } else {
                $this->assertFalse($oid1->equals($oid2));
            }
        }

        public function getCompareData()
        {
            return array(
                array(new ObjectIdentity('123', 'foo'), new ObjectIdentity('123', 'foo'), true),
                array(new ObjectIdentity('123', 'foo'), new ObjectIdentity(123, 'foo'), true),
                array(new ObjectIdentity('1', 'foo'), new ObjectIdentity('2', 'foo'), false),
                array(new ObjectIdentity('1', 'bla'), new ObjectIdentity('1', 'blub'), false),
            );
        }
    }

    class TestDomainObject
    {
        public function getObjectIdentifier()
        {
            return 'getObjectIdentifier()';
        }

        public function getId()
        {
            return 'getId()';
        }
    }
}

namespace Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain
{
    class TestDomainObject extends \Symfony\Component\Security\Acl\Tests\Domain\TestDomainObject
    {
    }
}
PK01[_�~��\Security/Symfony/Component/Security/Acl/Tests/Domain/ObjectIdentityRetrievalStrategyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\ObjectIdentityRetrievalStrategy;

class ObjectIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testGetObjectIdentityReturnsNullForInvalidDomainObject()
    {
        $strategy = new ObjectIdentityRetrievalStrategy();
        $this->assertNull($strategy->getObjectIdentity('foo'));
    }

    public function testGetObjectIdentity()
    {
        $strategy = new ObjectIdentityRetrievalStrategy();
        $domainObject = new DomainObject();
        $objectIdentity = $strategy->getObjectIdentity($domainObject);

        $this->assertEquals($domainObject->getId(), $objectIdentity->getIdentifier());
        $this->assertEquals(get_class($domainObject), $objectIdentity->getType());
    }
}

class DomainObject
{
    public function getId()
    {
        return 'foo';
    }
}
PK01[��HHMSecurity/Symfony/Component/Security/Acl/Tests/Domain/DoctrineAclCacheTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\DoctrineAclCache;
use Doctrine\Common\Cache\ArrayCache;

class DoctrineAclCacheTest extends \PHPUnit_Framework_TestCase
{
    protected $permissionGrantingStrategy;

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getEmptyValue
     */
    public function testConstructorDoesNotAcceptEmptyPrefix($empty)
    {
        new DoctrineAclCache(new ArrayCache(), $this->getPermissionGrantingStrategy(), $empty);
    }

    public function getEmptyValue()
    {
        return array(
            array(null),
            array(false),
            array(''),
        );
    }

    public function test()
    {
        $cache = $this->getCache();

        $aclWithParent = $this->getAcl(1);
        $acl = $this->getAcl();

        $cache->putInCache($aclWithParent);
        $cache->putInCache($acl);

        $cachedAcl = $cache->getFromCacheByIdentity($acl->getObjectIdentity());
        $this->assertEquals($acl->getId(), $cachedAcl->getId());
        $this->assertNull($acl->getParentAcl());

        $cachedAclWithParent = $cache->getFromCacheByIdentity($aclWithParent->getObjectIdentity());
        $this->assertEquals($aclWithParent->getId(), $cachedAclWithParent->getId());
        $this->assertNotNull($cachedParentAcl = $cachedAclWithParent->getParentAcl());
        $this->assertEquals($aclWithParent->getParentAcl()->getId(), $cachedParentAcl->getId());
    }

    protected function getAcl($depth = 0)
    {
        static $id = 1;

        $acl = new Acl($id, new ObjectIdentity($id, 'foo'), $this->getPermissionGrantingStrategy(), array(), $depth > 0);

        // insert some ACEs
        $sid = new UserSecurityIdentity('johannes', 'Foo');
        $acl->insertClassAce($sid, 1);
        $acl->insertClassFieldAce('foo', $sid, 1);
        $acl->insertObjectAce($sid, 1);
        $acl->insertObjectFieldAce('foo', $sid, 1);
        $id++;

        if ($depth > 0) {
            $acl->setParentAcl($this->getAcl($depth - 1));
        }

        return $acl;
    }

    protected function getPermissionGrantingStrategy()
    {
        if (null === $this->permissionGrantingStrategy) {
            $this->permissionGrantingStrategy = new PermissionGrantingStrategy();
        }

        return $this->permissionGrantingStrategy;
    }

    protected function getCache($cacheDriver = null, $prefix = DoctrineAclCache::PREFIX)
    {
        if (null === $cacheDriver) {
            $cacheDriver = new ArrayCache();
        }

        return new DoctrineAclCache($cacheDriver, $this->getPermissionGrantingStrategy(), $prefix);
    }
}
PK01[��v��WSecurity/Symfony/Component/Security/Acl/Tests/Domain/PermissionGrantingStrategyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\Acl;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Exception\NoAceFoundException;

class PermissionGrantingStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testIsGrantedObjectAcesHavePriority()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $acl->insertClassAce($sid, 1);
        $acl->insertObjectAce($sid, 1, 0, false);
        $this->assertFalse($strategy->isGranted($acl, array(1), array($sid)));
    }

    public function testIsGrantedFallsBackToClassAcesIfNoApplicableObjectAceWasFound()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $acl->insertClassAce($sid, 1);
        $this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
    }

    public function testIsGrantedFavorsLocalAcesOverParentAclAces()
    {
        $strategy = new PermissionGrantingStrategy();
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $acl = $this->getAcl($strategy);
        $acl->insertClassAce($sid, 1);

        $parentAcl = $this->getAcl($strategy);
        $acl->setParentAcl($parentAcl);
        $parentAcl->insertClassAce($sid, 1, 0, false);

        $this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
    }

    public function testIsGrantedFallsBackToParentAcesIfNoLocalAcesAreApplicable()
    {
        $strategy = new PermissionGrantingStrategy();
        $sid = new UserSecurityIdentity('johannes', 'Foo');
        $anotherSid = new UserSecurityIdentity('ROLE_USER', 'Foo');

        $acl = $this->getAcl($strategy);
        $acl->insertClassAce($anotherSid, 1, 0, false);

        $parentAcl = $this->getAcl($strategy);
        $acl->setParentAcl($parentAcl);
        $parentAcl->insertClassAce($sid, 1);

        $this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
    }

    /**
     * @expectedException \Symfony\Component\Security\Acl\Exception\NoAceFoundException
     */
    public function testIsGrantedReturnsExceptionIfNoAceIsFound()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $strategy->isGranted($acl, array(1), array($sid));
    }

    public function testIsGrantedFirstApplicableEntryMakesUltimateDecisionForPermissionIdentityCombination()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');
        $aSid = new RoleSecurityIdentity('ROLE_USER');

        $acl->insertClassAce($aSid, 1);
        $acl->insertClassAce($sid, 1, 1, false);
        $acl->insertClassAce($sid, 1, 2);
        $this->assertFalse($strategy->isGranted($acl, array(1), array($sid, $aSid)));

        $acl->insertObjectAce($sid, 1, 0, false);
        $acl->insertObjectAce($aSid, 1, 1);
        $this->assertFalse($strategy->isGranted($acl, array(1), array($sid, $aSid)));
    }

    public function testIsGrantedCallsAuditLoggerOnGrant()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $logger = $this->getMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
        $logger
            ->expects($this->once())
            ->method('logIfNeeded')
        ;
        $strategy->setAuditLogger($logger);

        $acl->insertObjectAce($sid, 1);
        $acl->updateObjectAuditing(0, true, false);

        $this->assertTrue($strategy->isGranted($acl, array(1), array($sid)));
    }

    public function testIsGrantedCallsAuditLoggerOnDeny()
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $logger = $this->getMock('Symfony\Component\Security\Acl\Model\AuditLoggerInterface');
        $logger
            ->expects($this->once())
            ->method('logIfNeeded')
        ;
        $strategy->setAuditLogger($logger);

        $acl->insertObjectAce($sid, 1, 0, false);
        $acl->updateObjectAuditing(0, false, true);

        $this->assertFalse($strategy->isGranted($acl, array(1), array($sid)));
    }

    /**
     * @dataProvider getAllStrategyTests
     */
    public function testIsGrantedStrategies($maskStrategy, $aceMask, $requiredMask, $result)
    {
        $strategy = new PermissionGrantingStrategy();
        $acl = $this->getAcl($strategy);
        $sid = new UserSecurityIdentity('johannes', 'Foo');

        $acl->insertObjectAce($sid, $aceMask, 0, true, $maskStrategy);

        if (false === $result) {
            try {
                $strategy->isGranted($acl, array($requiredMask), array($sid));
                $this->fail('The ACE is not supposed to match.');
            } catch (NoAceFoundException $noAce) { }
        } else {
            $this->assertTrue($strategy->isGranted($acl, array($requiredMask), array($sid)));
        }
    }

    public function getAllStrategyTests()
    {
        return array(
            array('all', 1 << 0 | 1 << 1, 1 << 0, true),
            array('all', 1 << 0 | 1 << 1, 1 << 2, false),
            array('all', 1 << 0 | 1 << 10, 1 << 0 | 1 << 10, true),
            array('all', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1 || 1 << 2, false),
            array('any', 1 << 0 | 1 << 1, 1 << 0, true),
            array('any', 1 << 0 | 1 << 1, 1 << 0 | 1 << 2, true),
            array('any', 1 << 0 | 1 << 1, 1 << 2, false),
            array('equal', 1 << 0 | 1 << 1, 1 << 0, false),
            array('equal', 1 << 0 | 1 << 1, 1 << 1, false),
            array('equal', 1 << 0 | 1 << 1, 1 << 0 | 1 << 1, true),
        );
    }

    protected function getAcl($strategy)
    {
        static $id = 1;

        return new Acl($id++, new ObjectIdentity(1, 'Foo'), $strategy, array(), true);
    }
}
PK01[/bAbA@Security/Symfony/Component/Security/Acl/Tests/Domain/AclTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;

use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\PermissionGrantingStrategy;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\Acl;

class AclTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $acl = new Acl(1, $oid = new ObjectIdentity('foo', 'foo'), $permissionStrategy = new PermissionGrantingStrategy(), array(), true);

        $this->assertSame(1, $acl->getId());
        $this->assertSame($oid, $acl->getObjectIdentity());
        $this->assertNull($acl->getParentAcl());
        $this->assertTrue($acl->isEntriesInheriting());
    }

    /**
     * @expectedException \OutOfBoundsException
     * @dataProvider getDeleteAceTests
     */
    public function testDeleteAceThrowsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'delete'.$type.'Ace'}(0);
    }

    /**
     * @dataProvider getDeleteAceTests
     */
    public function testDeleteAce($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 1);
        $acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 2, 1);
        $acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 3, 2);

        $listener = $this->getListener(array(
            $type.'Aces', 'aceOrder', 'aceOrder', $type.'Aces',
        ));
        $acl->addPropertyChangedListener($listener);

        $this->assertCount(3, $acl->{'get'.$type.'Aces'}());

        $acl->{'delete'.$type.'Ace'}(0);
        $this->assertCount(2, $aces = $acl->{'get'.$type.'Aces'}());
        $this->assertEquals(2, $aces[0]->getMask());
        $this->assertEquals(3, $aces[1]->getMask());

        $acl->{'delete'.$type.'Ace'}(1);
        $this->assertCount(1, $aces = $acl->{'get'.$type.'Aces'}());
        $this->assertEquals(2, $aces[0]->getMask());
    }

    public function getDeleteAceTests()
    {
        return array(
            array('class'),
            array('object'),
        );
    }

    /**
     * @expectedException \OutOfBoundsException
     * @dataProvider getDeleteFieldAceTests
     */
    public function testDeleteFieldAceThrowsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'delete'.$type.'Ace'}('foo', 0);
    }

    /**
     * @dataProvider getDeleteFieldAceTests
     */
    public function testDeleteFieldAce($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 1, 0);
        $acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 2, 1);
        $acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 3, 2);

        $listener = $this->getListener(array(
            $type.'Aces', 'aceOrder', 'aceOrder', $type.'Aces',
        ));
        $acl->addPropertyChangedListener($listener);

        $this->assertCount(3, $acl->{'get'.$type.'Aces'}('foo'));

        $acl->{'delete'.$type.'Ace'}(0, 'foo');
        $this->assertCount(2, $aces = $acl->{'get'.$type.'Aces'}('foo'));
        $this->assertEquals(2, $aces[0]->getMask());
        $this->assertEquals(3, $aces[1]->getMask());

        $acl->{'delete'.$type.'Ace'}(1, 'foo');
        $this->assertCount(1, $aces = $acl->{'get'.$type.'Aces'}('foo'));
        $this->assertEquals(2, $aces[0]->getMask());
    }

    public function getDeleteFieldAceTests()
    {
        return array(
            array('classField'),
            array('objectField'),
        );
    }

    /**
     * @dataProvider getInsertAceTests
     */
    public function testInsertAce($property, $method)
    {
        $acl = $this->getAcl();

        $listener = $this->getListener(array(
            $property, 'aceOrder', $property, 'aceOrder', $property
        ));
        $acl->addPropertyChangedListener($listener);

        $sid = new RoleSecurityIdentity('foo');
        $acl->$method($sid, 1);
        $acl->$method($sid, 2);
        $acl->$method($sid, 3, 1, false);

        $this->assertCount(3, $aces = $acl->{'get'.$property}());
        $this->assertEquals(2, $aces[0]->getMask());
        $this->assertEquals(3, $aces[1]->getMask());
        $this->assertEquals(1, $aces[2]->getMask());
    }

    /**
     * @expectedException \OutOfBoundsException
     * @dataProvider getInsertAceTests
     */
    public function testInsertClassAceThrowsExceptionOnInvalidIndex($property, $method)
    {
        $acl = $this->getAcl();
        $acl->$method(new RoleSecurityIdentity('foo'), 1, 1);
    }

    public function getInsertAceTests()
    {
        return array(
            array('classAces', 'insertClassAce'),
            array('objectAces', 'insertObjectAce'),
        );
    }

    /**
     * @dataProvider getInsertFieldAceTests
     */
    public function testInsertClassFieldAce($property, $method)
    {
        $acl = $this->getAcl();

        $listener = $this->getListener(array(
            $property, $property, 'aceOrder', $property,
            'aceOrder', 'aceOrder', $property,
        ));
        $acl->addPropertyChangedListener($listener);

        $sid = new RoleSecurityIdentity('foo');
        $acl->$method('foo', $sid, 1);
        $acl->$method('foo2', $sid, 1);
        $acl->$method('foo', $sid, 3);
        $acl->$method('foo', $sid, 2);

        $this->assertCount(3, $aces = $acl->{'get'.$property}('foo'));
        $this->assertCount(1, $acl->{'get'.$property}('foo2'));
        $this->assertEquals(2, $aces[0]->getMask());
        $this->assertEquals(3, $aces[1]->getMask());
        $this->assertEquals(1, $aces[2]->getMask());
    }

    /**
     * @expectedException \OutOfBoundsException
     * @dataProvider getInsertFieldAceTests
     */
    public function testInsertClassFieldAceThrowsExceptionOnInvalidIndex($property, $method)
    {
        $acl = $this->getAcl();
        $acl->$method('foo', new RoleSecurityIdentity('foo'), 1, 1);
    }

    public function getInsertFieldAceTests()
    {
        return array(
            array('classFieldAces', 'insertClassFieldAce'),
            array('objectFieldAces', 'insertObjectFieldAce'),
        );
    }

    public function testIsFieldGranted()
    {
        $sids = array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD'));
        $masks = array(1, 2, 4);
        $strategy = $this->getMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
        $acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, array(), true);

        $strategy
            ->expects($this->once())
            ->method('isFieldGranted')
            ->with($this->equalTo($acl), $this->equalTo('foo'), $this->equalTo($masks), $this->equalTo($sids), $this->isTrue())
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($acl->isFieldGranted('foo', $masks, $sids, true));
    }

    public function testIsGranted()
    {
        $sids = array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_IDDQD'));
        $masks = array(1, 2, 4);
        $strategy = $this->getMock('Symfony\Component\Security\Acl\Model\PermissionGrantingStrategyInterface');
        $acl = new Acl(1, new ObjectIdentity(1, 'foo'), $strategy, array(), true);

        $strategy
            ->expects($this->once())
            ->method('isGranted')
            ->with($this->equalTo($acl), $this->equalTo($masks), $this->equalTo($sids), $this->isTrue())
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($acl->isGranted($masks, $sids, true));
    }

    public function testSetGetParentAcl()
    {
        $acl = $this->getAcl();
        $parentAcl = $this->getAcl();

        $listener = $this->getListener(array('parentAcl'));
        $acl->addPropertyChangedListener($listener);

        $this->assertNull($acl->getParentAcl());
        $acl->setParentAcl($parentAcl);
        $this->assertSame($parentAcl, $acl->getParentAcl());

        $acl->setParentAcl(null);
        $this->assertNull($acl->getParentAcl());
    }

    public function testSetIsEntriesInheriting()
    {
        $acl = $this->getAcl();

        $listener = $this->getListener(array('entriesInheriting'));
        $acl->addPropertyChangedListener($listener);

        $this->assertTrue($acl->isEntriesInheriting());
        $acl->setEntriesInheriting(false);
        $this->assertFalse($acl->isEntriesInheriting());
    }

    public function testIsSidLoadedWhenAllSidsAreLoaded()
    {
        $acl = $this->getAcl();

        $this->assertTrue($acl->isSidLoaded(new UserSecurityIdentity('foo', 'Foo')));
        $this->assertTrue($acl->isSidLoaded(new RoleSecurityIdentity('ROLE_FOO', 'Foo')));
    }

    public function testIsSidLoaded()
    {
        $acl = new Acl(1, new ObjectIdentity('1', 'foo'), new PermissionGrantingStrategy(), array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('johannes', 'Bar')), true);

        $this->assertTrue($acl->isSidLoaded(new UserSecurityIdentity('foo', 'Foo')));
        $this->assertTrue($acl->isSidLoaded(new UserSecurityIdentity('johannes', 'Bar')));
        $this->assertTrue($acl->isSidLoaded(array(
            new UserSecurityIdentity('foo', 'Foo'),
            new UserSecurityIdentity('johannes', 'Bar'),
        )));
        $this->assertFalse($acl->isSidLoaded(new RoleSecurityIdentity('ROLE_FOO')));
        $this->assertFalse($acl->isSidLoaded(new UserSecurityIdentity('schmittjoh@gmail.com', 'Moo')));
        $this->assertFalse($acl->isSidLoaded(array(
            new UserSecurityIdentity('foo', 'Foo'),
            new UserSecurityIdentity('johannes', 'Bar'),
            new RoleSecurityIdentity('ROLE_FOO'),
        )));
    }

    /**
     * @dataProvider getUpdateAceTests
     * @expectedException \OutOfBoundsException
     */
    public function testUpdateAceThrowsOutOfBoundsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'update'.$type}(0, 1);
    }

    /**
     * @dataProvider getUpdateAceTests
     */
    public function testUpdateAce($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type}(new RoleSecurityIdentity('foo'), 1);

        $listener = $this->getListener(array(
            'mask', 'mask', 'strategy',
        ));
        $acl->addPropertyChangedListener($listener);

        $aces = $acl->{'get'.$type.'s'}();
        $ace = reset($aces);
        $this->assertEquals(1, $ace->getMask());
        $this->assertEquals('all', $ace->getStrategy());

        $acl->{'update'.$type}(0, 3);
        $this->assertEquals(3, $ace->getMask());
        $this->assertEquals('all', $ace->getStrategy());

        $acl->{'update'.$type}(0, 1, 'foo');
        $this->assertEquals(1, $ace->getMask());
        $this->assertEquals('foo', $ace->getStrategy());
    }

    public function getUpdateAceTests()
    {
        return array(
            array('classAce'),
            array('objectAce'),
        );
    }

    /**
     * @dataProvider getUpdateFieldAceTests
     * @expectedException \OutOfBoundsException
     */
    public function testUpdateFieldAceThrowsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'update'.$type}(0, 'foo', 1);
    }

    /**
     * @dataProvider getUpdateFieldAceTests
     */
    public function testUpdateFieldAce($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type}('foo', new UserSecurityIdentity('foo', 'Foo'), 1);

        $listener = $this->getListener(array(
            'mask', 'mask', 'strategy'
        ));
        $acl->addPropertyChangedListener($listener);

        $aces = $acl->{'get'.$type.'s'}('foo');
        $ace = reset($aces);
        $this->assertEquals(1, $ace->getMask());
        $this->assertEquals('all', $ace->getStrategy());

        $acl->{'update'.$type}(0, 'foo', 3);
        $this->assertEquals(3, $ace->getMask());
        $this->assertEquals('all', $ace->getStrategy());

        $acl->{'update'.$type}(0, 'foo', 1, 'foo');
        $this->assertEquals(1, $ace->getMask());
        $this->assertEquals('foo', $ace->getStrategy());
    }

    public function getUpdateFieldAceTests()
    {
        return array(
            array('classFieldAce'),
            array('objectFieldAce'),
        );
    }

    /**
     * @dataProvider getUpdateAuditingTests
     * @expectedException \OutOfBoundsException
     */
    public function testUpdateAuditingThrowsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'update'.$type.'Auditing'}(0, true, false);
    }

    /**
     * @dataProvider getUpdateAuditingTests
     */
    public function testUpdateAuditing($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type.'Ace'}(new RoleSecurityIdentity('foo'), 1);

        $listener = $this->getListener(array(
            'auditFailure', 'auditSuccess', 'auditFailure',
        ));
        $acl->addPropertyChangedListener($listener);

        $aces = $acl->{'get'.$type.'Aces'}();
        $ace = reset($aces);
        $this->assertFalse($ace->isAuditSuccess());
        $this->assertFalse($ace->isAuditFailure());

        $acl->{'update'.$type.'Auditing'}(0, false, true);
        $this->assertFalse($ace->isAuditSuccess());
        $this->assertTrue($ace->isAuditFailure());

        $acl->{'update'.$type.'Auditing'}(0, true, false);
        $this->assertTrue($ace->isAuditSuccess());
        $this->assertFalse($ace->isAuditFailure());
    }

    public function getUpdateAuditingTests()
    {
        return array(
            array('class'),
            array('object'),
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getUpdateFieldAuditingTests
     */
    public function testUpdateFieldAuditingThrowsExceptionOnInvalidField($type)
    {
        $acl = $this->getAcl();
        $acl->{'update'.$type.'Auditing'}(0, 'foo', true, true);
    }

    /**
     * @expectedException \OutOfBoundsException
     * @dataProvider getUpdateFieldAuditingTests
     */
    public function testUpdateFieldAuditingThrowsExceptionOnInvalidIndex($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 1);
        $acl->{'update'.$type.'Auditing'}(1, 'foo', true, false);
    }

    /**
     * @dataProvider getUpdateFieldAuditingTests
     */
    public function testUpdateFieldAuditing($type)
    {
        $acl = $this->getAcl();
        $acl->{'insert'.$type.'Ace'}('foo', new RoleSecurityIdentity('foo'), 1);

        $listener = $this->getListener(array(
            'auditSuccess', 'auditSuccess', 'auditFailure',
        ));
        $acl->addPropertyChangedListener($listener);

        $aces = $acl->{'get'.$type.'Aces'}('foo');
        $ace = reset($aces);
        $this->assertFalse($ace->isAuditSuccess());
        $this->assertFalse($ace->isAuditFailure());

        $acl->{'update'.$type.'Auditing'}(0, 'foo', true, false);
        $this->assertTrue($ace->isAuditSuccess());
        $this->assertFalse($ace->isAuditFailure());

        $acl->{'update'.$type.'Auditing'}(0, 'foo', false, true);
        $this->assertFalse($ace->isAuditSuccess());
        $this->assertTrue($ace->isAuditFailure());
    }

    public function getUpdateFieldAuditingTests()
    {
        return array(
            array('classField'),
            array('objectField'),
        );
    }

    protected function getListener($expectedChanges)
    {
        $aceProperties = array('aceOrder', 'mask', 'strategy', 'auditSuccess', 'auditFailure');

        $listener = $this->getMock('Doctrine\Common\PropertyChangedListener');
        foreach ($expectedChanges as $index => $property) {
            if (in_array($property, $aceProperties)) {
                $class = 'Symfony\Component\Security\Acl\Domain\Entry';
            } else {
                $class = 'Symfony\Component\Security\Acl\Domain\Acl';
            }

            $listener
                ->expects($this->at($index))
                ->method('propertyChanged')
                ->with($this->isInstanceOf($class), $this->equalTo($property))
            ;
        }

        return $listener;
    }

    protected function getAcl()
    {
        return new Acl(1, new ObjectIdentity(1, 'foo'), new PermissionGrantingStrategy(), array(), true);
    }
}
PK01[5�QSecurity/Symfony/Component/Security/Acl/Tests/Domain/RoleSecurityIdentityTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;

class RoleSecurityIdentityTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $id = new RoleSecurityIdentity('ROLE_FOO');

        $this->assertEquals('ROLE_FOO', $id->getRole());
    }

    public function testConstructorWithRoleInstance()
    {
        $id = new RoleSecurityIdentity(new Role('ROLE_FOO'));

        $this->assertEquals('ROLE_FOO', $id->getRole());
    }

    /**
     * @dataProvider getCompareData
     */
    public function testEquals($id1, $id2, $equal)
    {
        if ($equal) {
            $this->assertTrue($id1->equals($id2));
        } else {
            $this->assertFalse($id1->equals($id2));
        }
    }

    public function getCompareData()
    {
        return array(
            array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity('ROLE_FOO'), true),
            array(new RoleSecurityIdentity('ROLE_FOO'), new RoleSecurityIdentity(new Role('ROLE_FOO')), true),
            array(new RoleSecurityIdentity('ROLE_USER'), new RoleSecurityIdentity('ROLE_FOO'), false),
            array(new RoleSecurityIdentity('ROLE_FOO'), new UserSecurityIdentity('ROLE_FOO', 'Foo'), false),
        );
    }
}
PK01[��a((QSecurity/Symfony/Component/Security/Acl/Tests/Domain/UserSecurityIdentityTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;

class UserSecurityIdentityTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $id = new UserSecurityIdentity('foo', 'Foo');

        $this->assertEquals('foo', $id->getUsername());
        $this->assertEquals('Foo', $id->getClass());
    }

    // Test that constructor never changes the type, even for proxies
    public function testConstructorWithProxy()
    {
        $id = new UserSecurityIdentity('foo', 'Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain\Foo');

        $this->assertEquals('foo', $id->getUsername());
        $this->assertEquals('Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Acl\Tests\Domain\Foo', $id->getClass());
    }

    /**
     * @dataProvider getCompareData
     */
    public function testEquals($id1, $id2, $equal)
    {
        $this->assertSame($equal, $id1->equals($id2));
    }

    public function getCompareData()
    {
        $account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')
                            ->setMockClassName('USI_AccountImpl')
                            ->getMock();
        $account
            ->expects($this->any())
            ->method('getUsername')
            ->will($this->returnValue('foo'))
        ;

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->any())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        return array(
            array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('foo', 'Foo'), true),
            array(new UserSecurityIdentity('foo', 'Bar'), new UserSecurityIdentity('foo', 'Foo'), false),
            array(new UserSecurityIdentity('foo', 'Foo'), new UserSecurityIdentity('bar', 'Foo'), false),
            array(new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromAccount($account), false),
            array(new UserSecurityIdentity('bla', 'Foo'), new UserSecurityIdentity('blub', 'Foo'), false),
            array(new UserSecurityIdentity('foo', 'Foo'), new RoleSecurityIdentity('foo'), false),
            array(new UserSecurityIdentity('foo', 'Foo'), UserSecurityIdentity::fromToken($token), false),
            array(new UserSecurityIdentity('foo', 'USI_AccountImpl'), UserSecurityIdentity::fromToken($token), true),
        );
    }
}
PK01[�am��^Security/Symfony/Component/Security/Acl/Tests/Domain/SecurityIdentityRetrievalStrategyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;
use Symfony\Component\Security\Acl\Domain\SecurityIdentityRetrievalStrategy;

class SecurityIdentityRetrievalStrategyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getSecurityIdentityRetrievalTests
     */
    public function testGetSecurityIdentities($user, array $roles, $authenticationStatus, array $sids)
    {
        $strategy = $this->getStrategy($roles, $authenticationStatus);

        if ('anonymous' === $authenticationStatus) {
            $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken')
                                ->disableOriginalConstructor()
                                ->getMock();
        } else {
            $class = '';
            if (is_string($user)) {
                $class = 'MyCustomTokenImpl';
            }

            $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')
                        ->setMockClassName($class)
                        ->getMock();
        }
        $token
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue(array('foo')))
        ;
        if ('anonymous' === $authenticationStatus) {
            $token
                ->expects($this->never())
                ->method('getUser')
            ;
        } else {
            $token
                ->expects($this->once())
                ->method('getUser')
                ->will($this->returnValue($user))
            ;
        }

        $extractedSids = $strategy->getSecurityIdentities($token);

        foreach ($extractedSids as $index => $extractedSid) {
            if (!isset($sids[$index])) {
                $this->fail(sprintf('Expected SID at index %d, but there was none.', true));
            }

            if (false === $sids[$index]->equals($extractedSid)) {
                $this->fail(sprintf('Index: %d, expected SID "%s", but got "%s".', $index, $sids[$index], $extractedSid));
            }
        }
    }

    public function getSecurityIdentityRetrievalTests()
    {
        return array(
            array($this->getAccount('johannes', 'FooUser'), array('ROLE_USER', 'ROLE_SUPERADMIN'), 'fullFledged', array(
                new UserSecurityIdentity('johannes', 'FooUser'),
                new RoleSecurityIdentity('ROLE_USER'),
                new RoleSecurityIdentity('ROLE_SUPERADMIN'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
            )),
            array('johannes', array('ROLE_FOO'), 'fullFledged', array(
                new UserSecurityIdentity('johannes', 'MyCustomTokenImpl'),
                new RoleSecurityIdentity('ROLE_FOO'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
            )),
            array(new CustomUserImpl('johannes'), array('ROLE_FOO'), 'fullFledged', array(
                new UserSecurityIdentity('johannes', 'Symfony\Component\Security\Acl\Tests\Domain\CustomUserImpl'),
                new RoleSecurityIdentity('ROLE_FOO'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_FULLY'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
            )),
            array($this->getAccount('foo', 'FooBarUser'), array('ROLE_FOO'), 'rememberMe', array(
                new UserSecurityIdentity('foo', 'FooBarUser'),
                new RoleSecurityIdentity('ROLE_FOO'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_REMEMBERED'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
            )),
            array('guest', array('ROLE_FOO'), 'anonymous', array(
                new RoleSecurityIdentity('ROLE_FOO'),
                new RoleSecurityIdentity('IS_AUTHENTICATED_ANONYMOUSLY'),
            ))
        );
    }

    protected function getAccount($username, $class)
    {
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface', array(), array(), $class);
        $account
            ->expects($this->any())
            ->method('getUsername')
            ->will($this->returnValue($username))
        ;

        return $account;
    }

    protected function getStrategy(array $roles = array(), $authenticationStatus = 'fullFledged')
    {
        $roleHierarchy = $this->getMock('Symfony\Component\Security\Core\Role\RoleHierarchyInterface');
        $roleHierarchy
            ->expects($this->once())
            ->method('getReachableRoles')
            ->with($this->equalTo(array('foo')))
            ->will($this->returnValue($roles))
        ;

        $trustResolver = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver', array(), array('', ''));

        $trustResolver
            ->expects($this->at(0))
            ->method('isAnonymous')
            ->will($this->returnValue('anonymous' === $authenticationStatus))
        ;

        if ('fullFledged' === $authenticationStatus) {
            $trustResolver
                ->expects($this->once())
                ->method('isFullFledged')
                ->will($this->returnValue(true))
            ;
            $trustResolver
                ->expects($this->never())
                ->method('isRememberMe')
            ;
        } elseif ('rememberMe' === $authenticationStatus) {
            $trustResolver
                ->expects($this->once())
                ->method('isFullFledged')
                ->will($this->returnValue(false))
            ;
            $trustResolver
                ->expects($this->once())
                ->method('isRememberMe')
                ->will($this->returnValue(true))
            ;
        } else {
            $trustResolver
                ->expects($this->at(1))
                ->method('isAnonymous')
                ->will($this->returnValue(true))
            ;
            $trustResolver
                ->expects($this->once())
                ->method('isFullFledged')
                ->will($this->returnValue(false))
            ;
            $trustResolver
                ->expects($this->once())
                ->method('isRememberMe')
                ->will($this->returnValue(false))
            ;
        }

        return new SecurityIdentityRetrievalStrategy($roleHierarchy, $trustResolver);
    }
}

class CustomUserImpl
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function __toString()
    {
        return $this->name;
    }
}
PK01[F��@�
�
BSecurity/Symfony/Component/Security/Acl/Tests/Domain/EntryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Domain;

use Symfony\Component\Security\Acl\Domain\Entry;

class EntryTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $ace = $this->getAce($acl = $this->getAcl(), $sid = $this->getSid());

        $this->assertEquals(123, $ace->getId());
        $this->assertSame($acl, $ace->getAcl());
        $this->assertSame($sid, $ace->getSecurityIdentity());
        $this->assertEquals('foostrat', $ace->getStrategy());
        $this->assertEquals(123456, $ace->getMask());
        $this->assertTrue($ace->isGranting());
        $this->assertTrue($ace->isAuditSuccess());
        $this->assertFalse($ace->isAuditFailure());
    }

    public function testSetAuditSuccess()
    {
        $ace = $this->getAce();

        $this->assertTrue($ace->isAuditSuccess());
        $ace->setAuditSuccess(false);
        $this->assertFalse($ace->isAuditSuccess());
        $ace->setAuditsuccess(true);
        $this->assertTrue($ace->isAuditSuccess());
    }

    public function testSetAuditFailure()
    {
        $ace = $this->getAce();

        $this->assertFalse($ace->isAuditFailure());
        $ace->setAuditFailure(true);
        $this->assertTrue($ace->isAuditFailure());
        $ace->setAuditFailure(false);
        $this->assertFalse($ace->isAuditFailure());
    }

    public function testSetMask()
    {
        $ace = $this->getAce();

        $this->assertEquals(123456, $ace->getMask());
        $ace->setMask(4321);
        $this->assertEquals(4321, $ace->getMask());
    }

    public function testSetStrategy()
    {
        $ace = $this->getAce();

        $this->assertEquals('foostrat', $ace->getStrategy());
        $ace->setStrategy('foo');
        $this->assertEquals('foo', $ace->getStrategy());
    }

    public function testSerializeUnserialize()
    {
        $ace = $this->getAce();

        $serialized = serialize($ace);
        $uAce = unserialize($serialized);

        $this->assertNull($uAce->getAcl());
        $this->assertInstanceOf('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface', $uAce->getSecurityIdentity());
        $this->assertEquals($ace->getId(), $uAce->getId());
        $this->assertEquals($ace->getMask(), $uAce->getMask());
        $this->assertEquals($ace->getStrategy(), $uAce->getStrategy());
        $this->assertEquals($ace->isGranting(), $uAce->isGranting());
        $this->assertEquals($ace->isAuditSuccess(), $uAce->isAuditSuccess());
        $this->assertEquals($ace->isAuditFailure(), $uAce->isAuditFailure());
    }

    protected function getAce($acl = null, $sid = null)
    {
        if (null === $acl) {
            $acl = $this->getAcl();
        }
        if (null === $sid) {
            $sid = $this->getSid();
        }

        return new Entry(
            123,
            $acl,
            $sid,
            'foostrat',
            123456,
            true,
            false,
            true
        );
    }

    protected function getAcl()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\AclInterface');
    }

    protected function getSid()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\SecurityIdentityInterface');
    }
}
PK01[���yySSecurity/Symfony/Component/Security/Acl/Tests/Permission/BasicPermissionMapTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Permission;

use Symfony\Component\Security\Acl\Permission\BasicPermissionMap;

class BasicPermissionMapTest extends \PHPUnit_Framework_TestCase
{
    public function testGetMasksReturnsNullWhenNotSupportedMask()
    {
        $map = new BasicPermissionMap();
        $this->assertNull($map->getMasks('IS_AUTHENTICATED_REMEMBERED', null));
    }
}
PK01[eE���LSecurity/Symfony/Component/Security/Acl/Tests/Permission/MaskBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Acl\Tests\Permission;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;

class MaskBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getInvalidConstructorData
     */
    public function testConstructorWithNonInteger($invalidMask)
    {
        new MaskBuilder($invalidMask);
    }

    public function getInvalidConstructorData()
    {
        return array(
            array(234.463),
            array('asdgasdf'),
            array(array()),
            array(new \stdClass()),
        );
    }

    public function testConstructorWithoutArguments()
    {
        $builder = new MaskBuilder();

        $this->assertEquals(0, $builder->get());
    }

    public function testConstructor()
    {
        $builder = new MaskBuilder(123456);

        $this->assertEquals(123456, $builder->get());
    }

    public function testAddAndRemove()
    {
        $builder = new MaskBuilder();

        $builder
            ->add('view')
            ->add('eDiT')
            ->add('ownEr')
        ;
        $mask = $builder->get();

        $this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
        $this->assertEquals(MaskBuilder::MASK_EDIT, $mask & MaskBuilder::MASK_EDIT);
        $this->assertEquals(MaskBuilder::MASK_OWNER, $mask & MaskBuilder::MASK_OWNER);
        $this->assertEquals(0, $mask & MaskBuilder::MASK_MASTER);
        $this->assertEquals(0, $mask & MaskBuilder::MASK_CREATE);
        $this->assertEquals(0, $mask & MaskBuilder::MASK_DELETE);
        $this->assertEquals(0, $mask & MaskBuilder::MASK_UNDELETE);

        $builder->remove('edit')->remove('OWner');
        $mask = $builder->get();
        $this->assertEquals(0, $mask & MaskBuilder::MASK_EDIT);
        $this->assertEquals(0, $mask & MaskBuilder::MASK_OWNER);
        $this->assertEquals(MaskBuilder::MASK_VIEW, $mask & MaskBuilder::MASK_VIEW);
    }

    public function testGetPattern()
    {
        $builder = new MaskBuilder();
        $this->assertEquals(MaskBuilder::ALL_OFF, $builder->getPattern());

        $builder->add('view');
        $this->assertEquals(str_repeat('.', 31).'V', $builder->getPattern());

        $builder->add('owner');
        $this->assertEquals(str_repeat('.', 24).'N......V', $builder->getPattern());

        $builder->add(1 << 10);
        $this->assertEquals(str_repeat('.', 21).MaskBuilder::ON.'..N......V', $builder->getPattern());
    }

    public function testReset()
    {
        $builder = new MaskBuilder();
        $this->assertEquals(0, $builder->get());

        $builder->add('view');
        $this->assertTrue($builder->get() > 0);

        $builder->reset();
        $this->assertEquals(0, $builder->get());
    }
}
PK01[ܲ#&;;8Security/Symfony/Component/Security/Acl/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Security Component ACL Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK01[C��)!"!"QSecurity/Symfony/Component/Security/Tests/Http/Firewall/ExceptionListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Tests\Http\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
use Symfony\Component\Security\Http\HttpUtils;

class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getAuthenticationExceptionProvider
     */
    public function testAuthenticationExceptionWithoutEntryPoint(\Exception $exception, \Exception $eventException = null)
    {
        $event = $this->createEvent($exception);

        $listener = $this->createExceptionListener();
        $listener->onKernelException($event);

        $this->assertNull($event->getResponse());
        $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException());
    }

    /**
     * @dataProvider getAuthenticationExceptionProvider
     */
    public function testAuthenticationExceptionWithEntryPoint(\Exception $exception, \Exception $eventException = null)
    {
        $event = $this->createEvent($exception = new AuthenticationException());

        $listener = $this->createExceptionListener(null, null, null, $this->createEntryPoint());
        $listener->onKernelException($event);

        $this->assertEquals('OK', $event->getResponse()->getContent());
        $this->assertSame($exception, $event->getException());
    }

    public function getAuthenticationExceptionProvider()
    {
        return array(
            array(new AuthenticationException()),
            array(new \LogicException('random', 0, $e = new AuthenticationException()), $e),
            array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AuthenticationException())), $e),
            array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AccessDeniedException())), $e),
            array(new AuthenticationException('random', 0, new \LogicException())),
        );
    }

    /**
     * @dataProvider getAccessDeniedExceptionProvider
     */
    public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithoutErrorPage(\Exception $exception, \Exception $eventException = null)
    {
        $event = $this->createEvent($exception);

        $listener = $this->createExceptionListener(null, $this->createTrustResolver(true));
        $listener->onKernelException($event);

        $this->assertNull($event->getResponse());
        $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
    }

    /**
     * @dataProvider getAccessDeniedExceptionProvider
     */
    public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithErrorPage(\Exception $exception, \Exception $eventException = null)
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $kernel->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));

        $event = $this->createEvent($exception, $kernel);

        $httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $httpUtils->expects($this->once())->method('createRequest')->will($this->returnValue(Request::create('/error')));

        $listener = $this->createExceptionListener(null, $this->createTrustResolver(true), $httpUtils, null, '/error');
        $listener->onKernelException($event);

        $this->assertEquals('error', $event->getResponse()->getContent());
        $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
    }

    /**
     * @dataProvider getAccessDeniedExceptionProvider
     */
    public function testAccessDeniedExceptionFullFledgedAndWithAccessDeniedHandlerAndWithoutErrorPage(\Exception $exception, \Exception $eventException = null)
    {
        $event = $this->createEvent($exception);

        $accessDeniedHandler = $this->getMock('Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface');
        $accessDeniedHandler->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));

        $listener = $this->createExceptionListener(null, $this->createTrustResolver(true), null, null, null, $accessDeniedHandler);
        $listener->onKernelException($event);

        $this->assertEquals('error', $event->getResponse()->getContent());
        $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
    }

    /**
     * @dataProvider getAccessDeniedExceptionProvider
     */
    public function testAccessDeniedExceptionNotFullFledged(\Exception $exception, \Exception $eventException = null)
    {
        $event = $this->createEvent($exception);

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context->expects($this->once())->method('getToken')->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));

        $listener = $this->createExceptionListener($context, $this->createTrustResolver(false), null, $this->createEntryPoint());
        $listener->onKernelException($event);

        $this->assertEquals('OK', $event->getResponse()->getContent());
        $this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
    }

    public function getAccessDeniedExceptionProvider()
    {
        return array(
            array(new AccessDeniedException()),
            array(new \LogicException('random', 0, $e = new AccessDeniedException()), $e),
            array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AccessDeniedException())), $e),
            array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AuthenticationException())), $e),
            array(new AccessDeniedException('random', new \LogicException())),
        );
    }

    private function createEntryPoint()
    {
        $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $entryPoint->expects($this->once())->method('start')->will($this->returnValue(new Response('OK')));

        return $entryPoint;
    }

    private function createTrustResolver($fullFledged)
    {
        $trustResolver = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface');
        $trustResolver->expects($this->once())->method('isFullFledged')->will($this->returnValue($fullFledged));

        return $trustResolver;
    }

    private function createEvent(\Exception $exception, $kernel = null)
    {
        if (null === $kernel) {
            $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        }

        return new GetResponseForExceptionEvent($kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $exception);
    }

    private function createExceptionListener(SecurityContextInterface $context = null, AuthenticationTrustResolverInterface $trustResolver = null, HttpUtils $httpUtils = null, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null)
    {
        return new ExceptionListener(
            $context ? $context : $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
            $trustResolver ? $trustResolver : $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface'),
            $httpUtils ? $httpUtils : $this->getMock('Symfony\Component\Security\Http\HttpUtils'),
            'key',
            $authenticationEntryPoint,
            $errorPage,
            $accessDeniedHandler
        );
    }
}
PK01[s�f�[[GSecurity/Symfony/Component/Security/Tests/Core/User/UserCheckerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Tests\Core\User;

use Symfony\Component\Security\Core\User\UserChecker;

class UserCheckerTest extends \PHPUnit_Framework_TestCase
{
    public function testCheckPostAuthNotAdvancedUserInterface()
    {
        $checker = new UserChecker();

        $this->assertNull($checker->checkPostAuth($this->getMock('Symfony\Component\Security\Core\User\UserInterface')));
    }

    public function testCheckPostAuthPass()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(true));

        $this->assertNull($checker->checkPostAuth($account));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
     */
    public function testCheckPostAuthCredentialsExpired()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isCredentialsNonExpired')->will($this->returnValue(false));

        $checker->checkPostAuth($account);
    }

    public function testCheckPreAuthNotAdvancedUserInterface()
    {
        $checker = new UserChecker();

        $this->assertNull($checker->checkPreAuth($this->getMock('Symfony\Component\Security\Core\User\UserInterface')));
    }

    public function testCheckPreAuthPass()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
        $account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
        $account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(true));

        $this->assertNull($checker->checkPreAuth($account));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\LockedException
     */
    public function testCheckPreAuthAccountLocked()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(false));

        $checker->checkPreAuth($account);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
     */
    public function testCheckPreAuthDisabled()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
        $account->expects($this->once())->method('isEnabled')->will($this->returnValue(false));

        $checker->checkPreAuth($account);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
     */
    public function testCheckPreAuthAccountExpired()
    {
        $checker = new UserChecker();

        $account = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');
        $account->expects($this->once())->method('isAccountNonLocked')->will($this->returnValue(true));
        $account->expects($this->once())->method('isEnabled')->will($this->returnValue(true));
        $account->expects($this->once())->method('isAccountNonExpired')->will($this->returnValue(false));

        $checker->checkPreAuth($account);
    }
}
PK01[����!!PSecurity/Symfony/Component/Security/Tests/Core/User/InMemoryUserProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Tests\Core\User;

use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;

class InMemoryUserProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $provider = new InMemoryUserProvider(array(
            'fabien' => array(
                'password' => 'foo',
                'enabled'  => false,
                'roles'    => array('ROLE_USER'),
            ),
        ));

        $user = $provider->loadUserByUsername('fabien');
        $this->assertEquals('foo', $user->getPassword());
        $this->assertEquals(array('ROLE_USER'), $user->getRoles());
        $this->assertFalse($user->isEnabled());
    }

    public function testCreateUser()
    {
        $provider = new InMemoryUserProvider();
        $provider->createUser(new User('fabien', 'foo'));

        $user = $provider->loadUserByUsername('fabien');
        $this->assertEquals('foo', $user->getPassword());
    }

    /**
     * @expectedException \LogicException
     */
    public function testCreateUserAlreadyExist()
    {
        $provider = new InMemoryUserProvider();
        $provider->createUser(new User('fabien', 'foo'));
        $provider->createUser(new User('fabien', 'foo'));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
     */
    public function testLoadUserByUsernameDoesNotExist()
    {
        $provider = new InMemoryUserProvider();
        $provider->loadUserByUsername('fabien');
    }
}
PK01[2�nBB[Security/Symfony/Component/Security/Tests/Core/Authentication/Token/RememberMeTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Tests\Core\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Role\Role;

class RememberMeTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $user = $this->getUser();
        $token = new RememberMeToken($user, 'fookey', 'foo');

        $this->assertEquals('fookey', $token->getProviderKey());
        $this->assertEquals('foo', $token->getKey());
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
        $this->assertSame($user, $token->getUser());
        $this->assertTrue($token->isAuthenticated());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorKeyCannotBeNull()
    {
        new RememberMeToken(
            $this->getUser(),
            null,
            null
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorKeyCannotBeEmptyString()
    {
        new RememberMeToken(
            $this->getUser(),
            '',
            ''
        );
    }

    /**
     * @expectedException \PHPUnit_Framework_Error
     * @dataProvider getUserArguments
     */
    public function testConstructorUserCannotBeNull($user)
    {
        new RememberMeToken($user, 'foo', 'foo');
    }

    public function getUserArguments()
    {
        return array(
            array(null),
            array('foo'),
        );
    }

    protected function getUser($roles = array('ROLE_FOO'))
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue($roles))
        ;

        return $user;
    }
}
PK01[9�#�		4Security/Symfony/Component/Security/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Security Component Test Suite">
            <directory>./Acl/Tests/</directory>
            <directory>./Core/Tests/</directory>
            <directory>./Http/Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Acl/Tests</directory>
                <directory>./Core/Tests</directory>
                <directory>./Http/Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK01[g3�%%?Security/Symfony/Component/Security/Http/Tests/FirewallTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests;

use Symfony\Component\Security\Http\Firewall;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class FirewallTest extends \PHPUnit_Framework_TestCase
{
    public function testOnKernelRequestRegistersExceptionListener()
    {
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');

        $listener = $this->getMock('Symfony\Component\Security\Http\Firewall\ExceptionListener', array(), array(), '', false);
        $listener
            ->expects($this->once())
            ->method('register')
            ->with($this->equalTo($dispatcher))
        ;

        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);

        $map = $this->getMock('Symfony\Component\Security\Http\FirewallMapInterface');
        $map
            ->expects($this->once())
            ->method('getListeners')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array(), $listener)))
        ;

        $event = new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);

        $firewall = new Firewall($map, $dispatcher);
        $firewall->onKernelRequest($event);
    }

    public function testOnKernelRequestStopsWhenThereIsAResponse()
    {
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');

        $first = $this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface');
        $first
            ->expects($this->once())
            ->method('handle')
        ;

        $second = $this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface');
        $second
            ->expects($this->never())
            ->method('handle')
        ;

        $map = $this->getMock('Symfony\Component\Security\Http\FirewallMapInterface');
        $map
            ->expects($this->once())
            ->method('getListeners')
            ->will($this->returnValue(array(array($first, $second), null)))
        ;

        $event = $this->getMock(
            'Symfony\Component\HttpKernel\Event\GetResponseEvent',
            array('hasResponse'),
            array(
                $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
                $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false),
                HttpKernelInterface::MASTER_REQUEST
            )
        );
        $event
            ->expects($this->once())
            ->method('hasResponse')
            ->will($this->returnValue(true))
        ;

        $firewall = new Firewall($map, $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'));
        $firewall->onKernelRequest($event);
    }

    public function testOnKernelRequestWithSubRequest()
    {
        $map = $this->getMock('Symfony\Component\Security\Http\FirewallMapInterface');
        $map
            ->expects($this->never())
            ->method('getListeners')
        ;

        $event = new GetResponseEvent(
            $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
            $this->getMock('Symfony\Component\HttpFoundation\Request'),
            HttpKernelInterface::SUB_REQUEST
        );

        $firewall = new Firewall($map, $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'));
        $firewall->onKernelRequest($event);

        $this->assertFalse($event->hasResponse());
    }
}
PK11[��+MbbBSecurity/Symfony/Component/Security/Http/Tests/FirewallMapTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests;

use Symfony\Component\Security\Http\FirewallMap;
use Symfony\Component\HttpFoundation\Request;

class FirewallMapTest extends \PHPUnit_Framework_TestCase
{
    public function testGetListeners()
    {
        $map = new FirewallMap();

        $request = new Request();

        $notMatchingMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $notMatchingMatcher
            ->expects($this->once())
            ->method('matches')
            ->with($this->equalTo($request))
            ->will($this->returnValue(false))
        ;

        $map->add($notMatchingMatcher, array($this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface')));

        $matchingMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $matchingMatcher
            ->expects($this->once())
            ->method('matches')
            ->with($this->equalTo($request))
            ->will($this->returnValue(true))
        ;
        $theListener = $this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface');
        $theException = $this->getMock('Symfony\Component\Security\Http\Firewall\ExceptionListener', array(), array(), '', false);

        $map->add($matchingMatcher, array($theListener), $theException);

        $tooLateMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $tooLateMatcher
            ->expects($this->never())
            ->method('matches')
        ;

        $map->add($tooLateMatcher, array($this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface')));

        list($listeners, $exception) = $map->getListeners($request);

        $this->assertEquals(array($theListener), $listeners);
        $this->assertEquals($theException, $exception);
    }

    public function testGetListenersWithAnEntryHavingNoRequestMatcher()
    {
        $map = new FirewallMap();

        $request = new Request();

        $notMatchingMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $notMatchingMatcher
            ->expects($this->once())
            ->method('matches')
            ->with($this->equalTo($request))
            ->will($this->returnValue(false))
        ;

        $map->add($notMatchingMatcher, array($this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface')));

        $theListener = $this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface');
        $theException = $this->getMock('Symfony\Component\Security\Http\Firewall\ExceptionListener', array(), array(), '', false);

        $map->add(null, array($theListener), $theException);

        $tooLateMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $tooLateMatcher
            ->expects($this->never())
            ->method('matches')
        ;

        $map->add($tooLateMatcher, array($this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface')));

        list($listeners, $exception) = $map->getListeners($request);

        $this->assertEquals(array($theListener), $listeners);
        $this->assertEquals($theException, $exception);
    }

    public function testGetListenersWithNoMatchingEntry()
    {
        $map = new FirewallMap();

        $request = new Request();

        $notMatchingMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcher');
        $notMatchingMatcher
            ->expects($this->once())
            ->method('matches')
            ->with($this->equalTo($request))
            ->will($this->returnValue(false))
        ;

        $map->add($notMatchingMatcher, array($this->getMock('Symfony\Component\Security\Http\Firewall\ListenerInterface')));

        list($listeners, $exception) = $map->getListeners($request);

        $this->assertEquals(array(), $listeners);
        $this->assertNull($exception);
    }
}
PK11[����%�%@Security/Symfony/Component/Security/Http/Tests/HttpUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\HttpUtils;

class HttpUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateRedirectResponseWithPath()
    {
        $utils = new HttpUtils($this->getUrlGenerator());
        $response = $utils->createRedirectResponse($this->getRequest(), '/foobar');

        $this->assertTrue($response->isRedirect('http://localhost/foobar'));
        $this->assertEquals(302, $response->getStatusCode());
    }

    public function testCreateRedirectResponseWithAbsoluteUrl()
    {
        $utils = new HttpUtils($this->getUrlGenerator());
        $response = $utils->createRedirectResponse($this->getRequest(), 'http://symfony.com/');

        $this->assertTrue($response->isRedirect('http://symfony.com/'));
    }

    public function testCreateRedirectResponseWithRouteName()
    {
        $utils = new HttpUtils($urlGenerator = $this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface'));

        $urlGenerator
            ->expects($this->any())
            ->method('generate')
            ->with('foobar', array(), true)
            ->will($this->returnValue('http://localhost/foo/bar'))
        ;
        $urlGenerator
            ->expects($this->any())
            ->method('getContext')
            ->will($this->returnValue($this->getMock('Symfony\Component\Routing\RequestContext')))
        ;

        $response = $utils->createRedirectResponse($this->getRequest(), 'foobar');

        $this->assertTrue($response->isRedirect('http://localhost/foo/bar'));
    }

    public function testCreateRequestWithPath()
    {
        $request = $this->getRequest();
        $request->server->set('Foo', 'bar');

        $utils = new HttpUtils($this->getUrlGenerator());
        $subRequest = $utils->createRequest($request, '/foobar');

        $this->assertEquals('GET', $subRequest->getMethod());
        $this->assertEquals('/foobar', $subRequest->getPathInfo());
        $this->assertEquals('bar', $subRequest->server->get('Foo'));
    }

    public function testCreateRequestWithRouteName()
    {
        $utils = new HttpUtils($urlGenerator = $this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface'));

        $urlGenerator
            ->expects($this->once())
            ->method('generate')
            ->will($this->returnValue('/foo/bar'))
        ;
        $urlGenerator
            ->expects($this->any())
            ->method('getContext')
            ->will($this->returnValue($this->getMock('Symfony\Component\Routing\RequestContext')))
        ;

        $subRequest = $utils->createRequest($this->getRequest(), 'foobar');

        $this->assertEquals('/foo/bar', $subRequest->getPathInfo());
    }

    public function testCreateRequestWithAbsoluteUrl()
    {
        $utils = new HttpUtils($this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface'));
        $subRequest = $utils->createRequest($this->getRequest(), 'http://symfony.com/');

        $this->assertEquals('/', $subRequest->getPathInfo());
    }

    public function testCreateRequestPassesSessionToTheNewRequest()
    {
        $request = $this->getRequest();
        $request->setSession($session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface'));

        $utils = new HttpUtils($this->getUrlGenerator());
        $subRequest = $utils->createRequest($request, '/foobar');

        $this->assertSame($session, $subRequest->getSession());
    }

    /**
     * @dataProvider provideSecurityContextAttributes
     */
    public function testCreateRequestPassesSecurityContextAttributesToTheNewRequest($attribute)
    {
        $request = $this->getRequest();
        $request->attributes->set($attribute, 'foo');

        $utils = new HttpUtils($this->getUrlGenerator());
        $subRequest = $utils->createRequest($request, '/foobar');

        $this->assertSame('foo', $subRequest->attributes->get($attribute));
    }

    public function provideSecurityContextAttributes()
    {
        return array(
            array(SecurityContextInterface::AUTHENTICATION_ERROR),
            array(SecurityContextInterface::ACCESS_DENIED_ERROR),
            array(SecurityContextInterface::LAST_USERNAME)
        );
    }

    public function testCheckRequestPath()
    {
        $utils = new HttpUtils($this->getUrlGenerator());

        $this->assertTrue($utils->checkRequestPath($this->getRequest(), '/'));
        $this->assertFalse($utils->checkRequestPath($this->getRequest(), '/foo'));
        $this->assertTrue($utils->checkRequestPath($this->getRequest('/foo%20bar'), '/foo bar'));
        // Plus must not decoded to space
        $this->assertTrue($utils->checkRequestPath($this->getRequest('/foo+bar'), '/foo+bar'));
        // Checking unicode
        $this->assertTrue($utils->checkRequestPath($this->getRequest(urlencode('/вход')), '/вход'));
    }

    public function testCheckRequestPathWithUrlMatcherAndResourceNotFound()
    {
        $urlMatcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $urlMatcher
            ->expects($this->any())
            ->method('match')
            ->with('/')
            ->will($this->throwException(new ResourceNotFoundException()))
        ;

        $utils = new HttpUtils(null, $urlMatcher);
        $this->assertFalse($utils->checkRequestPath($this->getRequest(), 'foobar'));
    }

    public function testCheckRequestPathWithUrlMatcherAndMethodNotAllowed()
    {
        $request = $this->getRequest();
        $urlMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
        $urlMatcher
            ->expects($this->any())
            ->method('matchRequest')
            ->with($request)
            ->will($this->throwException(new MethodNotAllowedException(array())))
        ;

        $utils = new HttpUtils(null, $urlMatcher);
        $this->assertFalse($utils->checkRequestPath($request, 'foobar'));
    }

    public function testCheckRequestPathWithUrlMatcherAndResourceFoundByUrl()
    {
        $urlMatcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $urlMatcher
            ->expects($this->any())
            ->method('match')
            ->with('/foo/bar')
            ->will($this->returnValue(array('_route' => 'foobar')))
        ;

        $utils = new HttpUtils(null, $urlMatcher);
        $this->assertTrue($utils->checkRequestPath($this->getRequest('/foo/bar'), 'foobar'));
    }

    public function testCheckRequestPathWithUrlMatcherAndResourceFoundByRequest()
    {
        $request = $this->getRequest();
        $urlMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
        $urlMatcher
            ->expects($this->any())
            ->method('matchRequest')
            ->with($request)
            ->will($this->returnValue(array('_route' => 'foobar')))
        ;

        $utils = new HttpUtils(null, $urlMatcher);
        $this->assertTrue($utils->checkRequestPath($request, 'foobar'));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testCheckRequestPathWithUrlMatcherLoadingException()
    {
        $urlMatcher = $this->getMock('Symfony\Component\Routing\Matcher\UrlMatcherInterface');
        $urlMatcher
            ->expects($this->any())
            ->method('match')
            ->will($this->throwException(new \RuntimeException()))
        ;

        $utils = new HttpUtils(null, $urlMatcher);
        $utils->checkRequestPath($this->getRequest(), 'foobar');
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Matcher must either implement UrlMatcherInterface or RequestMatcherInterface
     */
    public function testUrlMatcher()
    {
        new HttpUtils($this->getUrlGenerator(), new \stdClass());
    }

    public function testGenerateUriRemovesQueryString()
    {
        $utils = new HttpUtils($this->getUrlGenerator('/foo/bar'));
        $this->assertEquals('/foo/bar', $utils->generateUri(new Request(), 'route_name'));

        $utils = new HttpUtils($this->getUrlGenerator('/foo/bar?param=value'));
        $this->assertEquals('/foo/bar', $utils->generateUri(new Request(), 'route_name'));
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage You must provide a UrlGeneratorInterface instance to be able to use routes.
     */
    public function testUrlGeneratorIsRequiredToGenerateUrl()
    {
        $utils = new HttpUtils();
        $utils->generateUri(new Request(), 'route_name');
    }

    private function getUrlGenerator($generatedUrl = '/foo/bar')
    {
        $urlGenerator = $this->getMock('Symfony\Component\Routing\Generator\UrlGeneratorInterface');
        $urlGenerator
            ->expects($this->any())
            ->method('generate')
            ->will($this->returnValue($generatedUrl))
        ;

        return $urlGenerator;
    }

    private function getRequest($path = '/')
    {
        return Request::create($path, 'get');
    }
}
PK11[�ck�~
~
^Security/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\EntryPoint;

use Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class FormAuthenticationEntryPointTest extends \PHPUnit_Framework_TestCase
{
    public function testStart()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');

        $httpKernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $httpUtils
            ->expects($this->once())
            ->method('createRedirectResponse')
            ->with($this->equalTo($request), $this->equalTo('/the/login/path'))
            ->will($this->returnValue($response))
        ;

        $entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', false);

        $this->assertEquals($response, $entryPoint->start($request));
    }

    public function testStartWithUseForward()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $subRequest = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $response = new \Symfony\Component\HttpFoundation\Response('', 200);

        $httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $httpUtils
            ->expects($this->once())
            ->method('createRequest')
            ->with($this->equalTo($request), $this->equalTo('/the/login/path'))
            ->will($this->returnValue($subRequest))
        ;

        $httpKernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $httpKernel
            ->expects($this->once())
            ->method('handle')
            ->with($this->equalTo($subRequest), $this->equalTo(HttpKernelInterface::SUB_REQUEST))
            ->will($this->returnValue($response))
        ;

        $entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', true);

        $entryPointResponse = $entryPoint->start($request);

        $this->assertEquals($response, $entryPointResponse);
        $this->assertEquals(401, $entryPointResponse->headers->get('X-Status-Code'));
    }
}
PK11[e���_Security/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\EntryPoint;

use Symfony\Component\Security\Http\EntryPoint\BasicAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class BasicAuthenticationEntryPointTest extends \PHPUnit_Framework_TestCase
{
    public function testStart()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        $authException = new AuthenticationException('The exception message');

        $entryPoint = new BasicAuthenticationEntryPoint('TheRealmName');
        $response = $entryPoint->start($request, $authException);

        $this->assertEquals('Basic realm="TheRealmName"', $response->headers->get('WWW-Authenticate'));
        $this->assertEquals(401, $response->getStatusCode());
    }

    public function testStartWithoutAuthException()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        $entryPoint = new BasicAuthenticationEntryPoint('TheRealmName');

        $response = $entryPoint->start($request);

        $this->assertEquals('Basic realm="TheRealmName"', $response->headers->get('WWW-Authenticate'));
        $this->assertEquals(401, $response->getStatusCode());
    }
}
PK11[-Ɔ��_Security/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\EntryPoint;

use Symfony\Component\Security\Http\EntryPoint\RetryAuthenticationEntryPoint;
use Symfony\Component\HttpFoundation\Request;

class RetryAuthenticationEntryPointTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataForStart
     */
    public function testStart($httpPort, $httpsPort, $request, $expectedUrl)
    {
        $entryPoint = new RetryAuthenticationEntryPoint($httpPort, $httpsPort);
        $response = $entryPoint->start($request);

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
        $this->assertEquals($expectedUrl, $response->headers->get('Location'));
    }

    public function dataForStart()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            return array(array());
        }

        return array(
            array(
                80,
                443,
                Request::create('http://localhost/foo/bar?baz=bat'),
                'https://localhost/foo/bar?baz=bat'
            ),
            array(
                80,
                443,
                Request::create('https://localhost/foo/bar?baz=bat'),
                'http://localhost/foo/bar?baz=bat'
            ),
            array(
                80,
                123,
                Request::create('http://localhost/foo/bar?baz=bat'),
                'https://localhost:123/foo/bar?baz=bat'
            ),
            array(
                8080,
                443,
                Request::create('https://localhost/foo/bar?baz=bat'),
                'http://localhost:8080/foo/bar?baz=bat'
            )
        );
    }
}
PK11[GrT�		`Security/Symfony/Component/Security/Http/Tests/EntryPoint/DigestAuthenticationEntryPointTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\EntryPoint;

use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;

class DigestAuthenticationEntryPointTest extends \PHPUnit_Framework_TestCase
{
    public function testStart()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        $authenticationException = new AuthenticationException('TheAuthenticationExceptionMessage');

        $entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheKey');
        $response = $entryPoint->start($request, $authenticationException);

        $this->assertEquals(401, $response->getStatusCode());
        $this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
    }

    public function testStartWithNoException()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        $entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheKey');
        $response = $entryPoint->start($request);

        $this->assertEquals(401, $response->getStatusCode());
        $this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
    }

    public function testStartWithNonceExpiredException()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        $nonceExpiredException = new NonceExpiredException('TheNonceExpiredExceptionMessage');

        $entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheKey');
        $response = $entryPoint->start($request, $nonceExpiredException);

        $this->assertEquals(401, $response->getStatusCode());
        $this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}", stale="true"$/', $response->headers->get('WWW-Authenticate'));
    }
}
PK11[Ғ)��RSecurity/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\RememberMeListener;
use Symfony\Component\HttpFoundation\Request;

class RememberMeListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testOnCoreSecurityDoesNotTryToPopulateNonEmptySecurityContext()
    {
        list($listener, $context, $service,,) = $this->getListener();

        $context
            ->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
        ;

        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $this->assertNull($listener->handle($this->getGetResponseEvent()));
    }

    public function testOnCoreSecurityDoesNothingWhenNoCookieIsSet()
    {
        list($listener, $context, $service,,) = $this->getListener();

        $context
            ->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;

        $service
            ->expects($this->once())
            ->method('autoLogin')
            ->will($this->returnValue(null))
        ;

        $event = $this->getGetResponseEvent();
        $event
            ->expects($this->once())
            ->method('getRequest')
            ->will($this->returnValue(new Request()))
        ;

        $this->assertNull($listener->handle($event));
    }

    public function testOnCoreSecurityIgnoresAuthenticationExceptionThrownByAuthenticationManagerImplementation()
    {
        list($listener, $context, $service, $manager,) = $this->getListener();

        $context
            ->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;

        $service
            ->expects($this->once())
            ->method('autoLogin')
            ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
        ;

        $service
            ->expects($this->once())
            ->method('loginFail')
        ;

        $exception = new AuthenticationException('Authentication failed.');
        $manager
            ->expects($this->once())
            ->method('authenticate')
            ->will($this->throwException($exception))
        ;

        $event = $this->getGetResponseEvent();
        $event
            ->expects($this->once())
            ->method('getRequest')
            ->will($this->returnValue(new Request()))
        ;

        $listener->handle($event);
    }

    public function testOnCoreSecurity()
    {
        list($listener, $context, $service, $manager,) = $this->getListener();

        $context
            ->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $service
            ->expects($this->once())
            ->method('autoLogin')
            ->will($this->returnValue($token))
        ;

        $context
            ->expects($this->once())
            ->method('setToken')
            ->with($this->equalTo($token))
        ;

        $manager
            ->expects($this->once())
            ->method('authenticate')
            ->will($this->returnValue($token))
        ;

        $event = $this->getGetResponseEvent();
        $event
            ->expects($this->once())
            ->method('getRequest')
            ->will($this->returnValue(new Request()))
        ;

        $listener->handle($event);
    }

    protected function getGetResponseEvent()
    {
        return $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
    }

    protected function getFilterResponseEvent()
    {
        return $this->getMock('Symfony\Component\HttpKernel\Event\FilterResponseEvent', array(), array(), '', false);
    }

    protected function getListener()
    {
        $listener = new RememberMeListener(
            $context = $this->getContext(),
            $service = $this->getService(),
            $manager = $this->getManager(),
            $logger = $this->getLogger()
        );

        return array($listener, $context, $service, $manager, $logger);
    }

    protected function getLogger()
    {
        return $this->getMock('Psr\Log\LoggerInterface');
    }

    protected function getManager()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
    }

    protected function getService()
    {
        return $this->getMock('Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface');
    }

    protected function getContext()
    {
        return $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')
                    ->disableOriginalConstructor()
                    ->getMock();
    }
}
PK11[�G��

OSecurity/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Http\Firewall\ChannelListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;

class ChannelListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleWithNotSecuredRequestAndHttpChannel()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $request
            ->expects($this->any())
            ->method('isSecure')
            ->will($this->returnValue(false))
        ;

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array(), 'http')))
        ;

        $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $entryPoint
            ->expects($this->never())
            ->method('start')
        ;

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->never())
            ->method('setResponse')
        ;

        $listener = new ChannelListener($accessMap, $entryPoint);
        $listener->handle($event);
    }

    public function testHandleWithSecuredRequestAndHttpsChannel()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $request
            ->expects($this->any())
            ->method('isSecure')
            ->will($this->returnValue(true))
        ;

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array(), 'https')))
        ;

        $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $entryPoint
            ->expects($this->never())
            ->method('start')
        ;

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->never())
            ->method('setResponse')
        ;

        $listener = new ChannelListener($accessMap, $entryPoint);
        $listener->handle($event);
    }

    public function testHandleWithNotSecuredRequestAndHttpsChannel()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $request
            ->expects($this->any())
            ->method('isSecure')
            ->will($this->returnValue(false))
        ;

        $response = new Response();

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array(), 'https')))
        ;

        $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $entryPoint
            ->expects($this->once())
            ->method('start')
            ->with($this->equalTo($request))
            ->will($this->returnValue($response))
        ;

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->once())
            ->method('setResponse')
            ->with($this->equalTo($response))
        ;

        $listener = new ChannelListener($accessMap, $entryPoint);
        $listener->handle($event);
    }

    public function testHandleWithSecuredRequestAndHttpChannel()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);
        $request
            ->expects($this->any())
            ->method('isSecure')
            ->will($this->returnValue(true))
        ;

        $response = new Response();

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array(), 'http')))
        ;

        $entryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $entryPoint
            ->expects($this->once())
            ->method('start')
            ->with($this->equalTo($request))
            ->will($this->returnValue($response))
        ;

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->once())
            ->method('setResponse')
            ->with($this->equalTo($response))
        ;

        $listener = new ChannelListener($accessMap, $entryPoint);
        $listener->handle($event);
    }
}
PK11[�e��
�
_Security/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Http\Firewall\AnonymousAuthenticationListener;

class AnonymousAuthenticationListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleWithContextHavingAToken()
    {
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
        ;
        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $listener = new AnonymousAuthenticationListener($context, 'TheKey');
        $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
    }

    public function testHandleWithContextHavingNoToken()
    {
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;
        $context
            ->expects($this->once())
            ->method('setToken')
            ->with(self::logicalAnd(
                $this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken'),
                $this->attributeEqualTo('key', 'TheKey')
            ))
        ;

        $listener = new AnonymousAuthenticationListener($context, 'TheKey');
        $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
    }

    public function testHandledEventIsLogged()
    {
        if (!interface_exists('Psr\Log\LoggerInterface')) {
            $this->markTestSkipped('The "LoggerInterface" is not available');
        }

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->once())
            ->method('info')
            ->with('Populated SecurityContext with an anonymous Token')
        ;

        $listener = new AnonymousAuthenticationListener($context, 'TheKey', $logger);
        $listener->handle($this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false));
    }
}
PK11[��K�$$[Security/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;

class BasicAuthenticationListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleWithValidUsernameAndPasswordServerParameters()
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'PHP_AUTH_USER' => 'TheUsername',
            'PHP_AUTH_PW'   => 'ThePassword'
        ));

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;
        $context
            ->expects($this->once())
            ->method('setToken')
            ->with($this->equalTo($token))
        ;

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'))
            ->will($this->returnValue($token))
        ;

        $listener = new BasicAuthenticationListener(
            $context,
            $authenticationManager,
            'TheProviderKey',
            $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWhenAuthenticationFails()
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'PHP_AUTH_USER' => 'TheUsername',
            'PHP_AUTH_PW'   => 'ThePassword'
        ));

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;
        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $response = new Response();

        $authenticationEntryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $authenticationEntryPoint
            ->expects($this->any())
            ->method('start')
            ->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
            ->will($this->returnValue($response))
        ;

        $listener = new BasicAuthenticationListener(
            $context,
            new AuthenticationProviderManager(array($this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface'))),
            'TheProviderKey',
            $authenticationEntryPoint
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->once())
            ->method('setResponse')
            ->with($this->equalTo($response))
        ;

        $listener->handle($event);
    }

    public function testHandleWithNoUsernameServerParameter()
    {
        $request = new Request();

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->never())
            ->method('getToken')
        ;

        $listener = new BasicAuthenticationListener(
            $context,
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
            'TheProviderKey',
            $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWithASimilarAuthenticatedToken()
    {
        $request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_USER' => 'TheUsername'));

        $token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->never())
            ->method('authenticate')
        ;

        $listener = new BasicAuthenticationListener(
            $context,
            $authenticationManager,
            'TheProviderKey',
            $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage $providerKey must not be empty
     */
    public function testItRequiresProviderKey()
    {
        new BasicAuthenticationListener(
            $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
            '',
            $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')
        );
    }

    public function testHandleWithADifferentAuthenticatedToken()
    {
        $request = new Request(array(), array(), array(), array(), array(), array(
            'PHP_AUTH_USER' => 'TheUsername',
            'PHP_AUTH_PW'   => 'ThePassword'
        ));

        $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;
        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $response = new Response();

        $authenticationEntryPoint = $this->getMock('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface');
        $authenticationEntryPoint
            ->expects($this->any())
            ->method('start')
            ->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
            ->will($this->returnValue($response))
        ;

        $listener = new BasicAuthenticationListener(
            $context,
            new AuthenticationProviderManager(array($this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface'))),
            'TheProviderKey',
            $authenticationEntryPoint
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;
        $event
            ->expects($this->once())
            ->method('setResponse')
            ->with($this->equalTo($response))
        ;

        $listener->handle($event);
    }
}
PK11[��l���JSecurity/Symfony/Component/Security/Http/Tests/Firewall/DigestDataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Http\Firewall\DigestData;

class DigestDataTest extends \PHPUnit_Framework_TestCase
{
    public function testGetResponse()
    {
        $digestAuth = new DigestData(
            'username="user", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('b52938fc9e6d7c01be7702ece9031b42', $digestAuth->getResponse());
    }

    public function testGetUsername()
    {
        $digestAuth = new DigestData(
            'username="user", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('user', $digestAuth->getUsername());
    }

    public function testGetUsernameWithQuote()
    {
        $digestAuth = new DigestData(
            'username="\"user\"", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('"user"', $digestAuth->getUsername());
    }

    public function testGetUsernameWithQuoteAndEscape()
    {
        $digestAuth = new DigestData(
            'username="\"u\\\\\"ser\"", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('"u\\"ser"', $digestAuth->getUsername());
    }

    public function testGetUsernameWithSingleQuote()
    {
        $digestAuth = new DigestData(
            'username="\"u\'ser\"", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('"u\'ser"', $digestAuth->getUsername());
    }

    public function testGetUsernameWithSingleQuoteAndEscape()
    {
        $digestAuth = new DigestData(
            'username="\"u\\\'ser\"", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('"u\\\'ser"', $digestAuth->getUsername());
    }

    public function testGetUsernameWithEscape()
    {
        $digestAuth = new DigestData(
            'username="\"u\\ser\"", realm="Welcome, robot!", ' .
            'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $this->assertEquals('"u\\ser"', $digestAuth->getUsername());
    }

    public function testValidateAndDecode()
    {
        $time = microtime(true);
        $key = 'ThisIsAKey';
        $nonce = base64_encode($time.':'.md5($time.':'.$key));

        $digestAuth = new DigestData(
            'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        try {
            $digestAuth->validateAndDecode($key, 'Welcome, robot!');
        } catch (\Exception $e) {
            $this->fail(sprintf('testValidateAndDecode fail with message: %s', $e->getMessage()));
        }
    }

    public function testCalculateServerDigest()
    {
        $this->calculateServerDigest('user', 'Welcome, robot!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
    }

    public function testCalculateServerDigestWithQuote()
    {
        $this->calculateServerDigest('\"user\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
    }

    public function testCalculateServerDigestWithQuoteAndEscape()
    {
        $this->calculateServerDigest('\"u\\\\\"ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
    }

    public function testCalculateServerDigestEscape()
    {
        $this->calculateServerDigest('\"u\\ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
        $this->calculateServerDigest('\"u\\ser\\\\\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
    }

    public function testIsNonceExpired()
    {
        $time = microtime(true) + 10;
        $key = 'ThisIsAKey';
        $nonce = base64_encode($time.':'.md5($time.':'.$key));

        $digestAuth = new DigestData(
            'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", ' .
            'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", ' .
            'response="b52938fc9e6d7c01be7702ece9031b42"'
        );

        $digestAuth->validateAndDecode($key, 'Welcome, robot!');

        $this->assertFalse($digestAuth->isNonceExpired());
    }

    protected function setUp()
    {
        class_exists('Symfony\Component\Security\Http\Firewall\DigestAuthenticationListener', true);
    }

    private function calculateServerDigest($username, $realm, $password, $key, $nc, $cnonce, $qop, $method, $uri)
    {
        $time = microtime(true);
        $nonce = base64_encode($time.':'.md5($time.':'.$key));

        $response = md5(
            md5($username.':'.$realm.':'.$password).':'.$nonce.':'.$nc.':'.$cnonce.':'.$qop.':'.md5($method.':'.$uri)
        );

        $digest = sprintf('username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop="%s", response="%s"',
            $username, $realm, $nonce, $uri, $cnonce, $nc, $qop, $response
        );

        $digestAuth = new DigestData($digest);

        $this->assertEquals($digestAuth->getResponse(), $digestAuth->calculateServerDigest($password, $method));
    }
}
PK11[j�z9�"�"OSecurity/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Http\Firewall\ContextListener;

class ContextListenerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->securityContext = new SecurityContext(
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
            $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')
        );
    }

    protected function tearDown()
    {
        unset($this->securityContext);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage $contextKey must not be empty
     */
    public function testItRequiresContextKey()
    {
        new ContextListener(
            $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
            array(),
            ''
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface
     */
    public function testUserProvidersNeedToImplementAnInterface()
    {
        new ContextListener(
            $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface'),
            array(new \stdClass()),
            'key123'
        );
    }

    public function testOnKernelResponseWillAddSession()
    {
        $session = $this->runSessionOnKernelResponse(
            new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
            null
        );

        $token = unserialize($session->get('_security_session'));
        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
        $this->assertEquals('test1', $token->getUsername());
    }

    public function testOnKernelResponseWillReplaceSession()
    {
        $session = $this->runSessionOnKernelResponse(
            new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
            'C:10:"serialized"'
        );

        $token = unserialize($session->get('_security_session'));
        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
        $this->assertEquals('test1', $token->getUsername());
    }

    public function testOnKernelResponseWillRemoveSession()
    {
        $session = $this->runSessionOnKernelResponse(
            null,
            'C:10:"serialized"'
        );

        $this->assertFalse($session->has('_security_session'));
    }

    public function testOnKernelResponseWithoutSession()
    {
        $this->securityContext->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));
        $request = new Request();
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $event = new FilterResponseEvent(
            $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
            $request,
            HttpKernelInterface::MASTER_REQUEST,
            new Response()
        );

        $listener = new ContextListener($this->securityContext, array(), 'session');
        $listener->onKernelResponse($event);

        $this->assertTrue($session->isStarted());
    }

    public function testOnKernelResponseWithoutSessionNorToken()
    {
        $request = new Request();
        $session = new Session(new MockArraySessionStorage());
        $request->setSession($session);

        $event = new FilterResponseEvent(
            $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
            $request,
            HttpKernelInterface::MASTER_REQUEST,
            new Response()
        );

        $listener = new ContextListener($this->securityContext, array(), 'session');
        $listener->onKernelResponse($event);

        $this->assertFalse($session->isStarted());
    }

    /**
     * @dataProvider provideInvalidToken
     */
    public function testInvalidTokenInSession($token)
    {
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');

        $event->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request));
        $request->expects($this->any())
            ->method('hasPreviousSession')
            ->will($this->returnValue(true));
        $request->expects($this->any())
            ->method('getSession')
            ->will($this->returnValue($session));
        $session->expects($this->any())
            ->method('get')
            ->with('_security_key123')
            ->will($this->returnValue($token));
        $context->expects($this->once())
            ->method('setToken')
            ->with(null);

        $listener = new ContextListener($context, array(), 'key123');
        $listener->handle($event);
    }

    public function provideInvalidToken()
    {
        return array(
            array(serialize(new \__PHP_Incomplete_Class())),
            array(serialize(null)),
            array(null)
        );
    }

    public function testHandleAddsKernelResponseListener()
    {
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();

        $listener = new ContextListener($context, array(), 'key123', null, $dispatcher);

        $event->expects($this->any())
            ->method('isMasterRequest')
            ->will($this->returnValue(true));
        $event->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($this->getMock('Symfony\Component\HttpFoundation\Request')));

        $dispatcher->expects($this->once())
            ->method('addListener')
            ->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));

        $listener->handle($event);
    }

    public function testHandleRemovesTokenIfNoPreviousSessionWasFound()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $request->expects($this->any())->method('hasPreviousSession')->will($this->returnValue(false));

        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->any())->method('getRequest')->will($this->returnValue($request));

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context->expects($this->once())->method('setToken')->with(null);

        $listener = new ContextListener($context, array(), 'key123');
        $listener->handle($event);
    }

    protected function runSessionOnKernelResponse($newToken, $original = null)
    {
        $session = new Session(new MockArraySessionStorage());

        if ($original !== null) {
            $session->set('_security_session', $original);
        }

        $this->securityContext->setToken($newToken);

        $request = new Request();
        $request->setSession($session);
        $request->cookies->set('MOCKSESSID', true);

        $event = new FilterResponseEvent(
            $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'),
            $request,
            HttpKernelInterface::MASTER_REQUEST,
            new Response()
        );

        $listener = new ContextListener($this->securityContext, array(), 'session');
        $listener->onKernelResponse($event);

        return $session;
    }
}
PK11[<��%%`Security/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;

class AbstractPreAuthenticatedListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleWithValidValues()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $request = new Request(array(), array(), array(), array(), array(), array());

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;
        $context
            ->expects($this->once())
            ->method('setToken')
            ->with($this->equalTo($token))
        ;

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
            ->will($this->returnValue($token))
        ;

        $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
            $context,
            $authenticationManager,
            'TheProviderKey'
        ));
        $listener
            ->expects($this->once())
            ->method('getPreAuthenticatedData')
            ->will($this->returnValue($userCredentials));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWhenAuthenticationFails()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $request = new Request(array(), array(), array(), array(), array(), array());

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;
        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $exception = new AuthenticationException('Authentication failed.');
        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
            ->will($this->throwException($exception))
        ;

        $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
            $context,
            $authenticationManager,
            'TheProviderKey'
        ));
        $listener
            ->expects($this->once())
            ->method('getPreAuthenticatedData')
            ->will($this->returnValue($userCredentials));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWhenAuthenticationFailsWithDifferentToken()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));

        $request = new Request(array(), array(), array(), array(), array(), array());

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;
        $context
            ->expects($this->never())
            ->method('setToken')
        ;

        $exception = new AuthenticationException('Authentication failed.');
        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
            ->will($this->throwException($exception))
        ;

        $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
            $context,
            $authenticationManager,
            'TheProviderKey'
        ));
        $listener
            ->expects($this->once())
            ->method('getPreAuthenticatedData')
            ->will($this->returnValue($userCredentials));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWithASimilarAuthenticatedToken()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $request = new Request(array(), array(), array(), array(), array(), array());

        $token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->never())
            ->method('authenticate')
        ;

        $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
            $context,
            $authenticationManager,
            'TheProviderKey'
        ));
        $listener
            ->expects($this->once())
            ->method('getPreAuthenticatedData')
            ->will($this->returnValue($userCredentials));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWithAnInvalidSimilarToken()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $request = new Request(array(), array(), array(), array(), array(), array());

        $token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;
        $context
            ->expects($this->once())
            ->method('setToken')
            ->with($this->equalTo(null))
        ;

        $exception = new AuthenticationException('Authentication failed.');
        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authenticationManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
            ->will($this->throwException($exception))
        ;

        $listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
            $context,
            $authenticationManager,
            'TheProviderKey'
        ));
        $listener
            ->expects($this->once())
            ->method('getPreAuthenticatedData')
            ->will($this->returnValue($userCredentials));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }
}
PK11[q���NSecurity/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Http\Firewall\AccessListener;

class AccessListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
     */
    public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array('foo' => 'bar'), null)))
        ;

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->any())
            ->method('isAuthenticated')
            ->will($this->returnValue(true))
        ;

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;

        $accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
        $accessDecisionManager
            ->expects($this->once())
            ->method('decide')
            ->with($this->equalTo($token), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
            ->will($this->returnValue(false))
        ;

        $listener = new AccessListener(
            $context,
            $accessDecisionManager,
            $accessMap,
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWhenTheTokenIsNotAuthenticated()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(array('foo' => 'bar'), null)))
        ;

        $notAuthenticatedToken = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $notAuthenticatedToken
            ->expects($this->any())
            ->method('isAuthenticated')
            ->will($this->returnValue(false))
        ;

        $authenticatedToken = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $authenticatedToken
            ->expects($this->any())
            ->method('isAuthenticated')
            ->will($this->returnValue(true))
        ;

        $authManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $authManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->equalTo($notAuthenticatedToken))
            ->will($this->returnValue($authenticatedToken))
        ;

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($notAuthenticatedToken))
        ;
        $context
            ->expects($this->once())
            ->method('setToken')
            ->with($this->equalTo($authenticatedToken))
        ;

        $accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
        $accessDecisionManager
            ->expects($this->once())
            ->method('decide')
            ->with($this->equalTo($authenticatedToken), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
            ->will($this->returnValue(true))
        ;

        $listener = new AccessListener(
            $context,
            $accessDecisionManager,
            $accessMap,
            $authManager
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array(), array(), '', false, false);

        $accessMap = $this->getMock('Symfony\Component\Security\Http\AccessMapInterface');
        $accessMap
            ->expects($this->any())
            ->method('getPatterns')
            ->with($this->equalTo($request))
            ->will($this->returnValue(array(null, null)))
        ;

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->never())
            ->method('isAuthenticated')
        ;

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;

        $listener = new AccessListener(
            $context,
            $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'),
            $accessMap,
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);
        $event
            ->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request))
        ;

        $listener->handle($event);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
     */
    public function testHandleWhenTheSecurityContextHasNoToken()
    {
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $context
            ->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue(null))
        ;

        $listener = new AccessListener(
            $context,
            $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface'),
            $this->getMock('Symfony\Component\Security\Http\AccessMapInterface'),
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')
        );

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\GetResponseEvent', array(), array(), '', false);

        $listener->handle($event);
    }
}
PK11[�V�k��NSecurity/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\LogoutListener;

class LogoutListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testHandleUnmatchedPath()
    {
        list($listener, $context, $httpUtils, $options) = $this->getListener();

        list($event, $request) = $this->getGetResponseEvent();

        $event->expects($this->never())
            ->method('setResponse');

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request, $options['logout_path'])
            ->will($this->returnValue(false));

        $listener->handle($event);
    }

    public function testHandleMatchedPathWithSuccessHandlerAndCsrfValidation()
    {
        $successHandler = $this->getSuccessHandler();
        $tokenManager = $this->getTokenManager();

        list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler, $tokenManager);

        list($event, $request) = $this->getGetResponseEvent();

        $request->query->set('_csrf_token', 'token');

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request, $options['logout_path'])
            ->will($this->returnValue(true));

        $tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->will($this->returnValue(true));

        $successHandler->expects($this->once())
            ->method('onLogoutSuccess')
            ->with($request)
            ->will($this->returnValue($response = new Response()));

        $context->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue($token = $this->getToken()));

        $handler = $this->getHandler();
        $handler->expects($this->once())
            ->method('logout')
            ->with($request, $response, $token);

        $context->expects($this->once())
            ->method('setToken')
            ->with(null);

        $event->expects($this->once())
            ->method('setResponse')
            ->with($response);

        $listener->addHandler($handler);

        $listener->handle($event);
    }

    public function testHandleMatchedPathWithoutSuccessHandlerAndCsrfValidation()
    {
        $successHandler = $this->getSuccessHandler();

        list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler);

        list($event, $request) = $this->getGetResponseEvent();

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request, $options['logout_path'])
            ->will($this->returnValue(true));

        $successHandler->expects($this->once())
            ->method('onLogoutSuccess')
            ->with($request)
            ->will($this->returnValue($response = new Response()));

        $context->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue($token = $this->getToken()));

        $handler = $this->getHandler();
        $handler->expects($this->once())
            ->method('logout')
            ->with($request, $response, $token);

        $context->expects($this->once())
            ->method('setToken')
            ->with(null);

        $event->expects($this->once())
            ->method('setResponse')
            ->with($response);

        $listener->addHandler($handler);

        $listener->handle($event);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testSuccessHandlerReturnsNonResponse()
    {
        $successHandler = $this->getSuccessHandler();

        list($listener, $context, $httpUtils, $options) = $this->getListener($successHandler);

        list($event, $request) = $this->getGetResponseEvent();

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request, $options['logout_path'])
            ->will($this->returnValue(true));

        $successHandler->expects($this->once())
            ->method('onLogoutSuccess')
            ->with($request)
            ->will($this->returnValue(null));

        $listener->handle($event);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\LogoutException
     */
    public function testCsrfValidationFails()
    {
        $tokenManager = $this->getTokenManager();

        list($listener, $context, $httpUtils, $options) = $this->getListener(null, $tokenManager);

        list($event, $request) = $this->getGetResponseEvent();

        $request->query->set('_csrf_token', 'token');

        $httpUtils->expects($this->once())
            ->method('checkRequestPath')
            ->with($request, $options['logout_path'])
            ->will($this->returnValue(true));

        $tokenManager->expects($this->once())
            ->method('isTokenValid')
            ->will($this->returnValue(false));

        $listener->handle($event);
    }

    private function getTokenManager()
    {
        return $this->getMock('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface');
    }

    private function getContext()
    {
        return $this->getMockBuilder('Symfony\Component\Security\Core\SecurityContext')
            ->disableOriginalConstructor()
            ->getMock();
    }

    private function getGetResponseEvent()
    {
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();

        $event->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request = new Request()));

        return array($event, $request);
    }

    private function getHandler()
    {
        return $this->getMock('Symfony\Component\Security\Http\Logout\LogoutHandlerInterface');
    }

    private function getHttpUtils()
    {
        return $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')
            ->disableOriginalConstructor()
            ->getMock();
    }

    private function getListener($successHandler = null, $tokenManager = null)
    {
        $listener = new LogoutListener(
            $context = $this->getContext(),
            $httpUtils = $this->getHttpUtils(),
            $successHandler ?: $this->getSuccessHandler(),
            $options = array(
                'csrf_parameter' => '_csrf_token',
                'intention'      => 'logout',
                'logout_path'    => '/logout',
                'target_url'     => '/',
            ),
            $tokenManager
        );

        return array($listener, $context, $httpUtils, $options);
    }

    private function getSuccessHandler()
    {
        return $this->getMock('Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface');
    }

    private function getToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }
}
PK11[���@&@&RSecurity/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\Security\Http\Firewall\SwitchUserListener;

class SwitchUserListenerTest extends \PHPUnit_Framework_TestCase
{
    private $securityContext;

    private $userProvider;

    private $userChecker;

    private $accessDecisionManager;

    private $request;

    private $event;

    protected function setUp()
    {
        $this->securityContext = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $this->userProvider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
        $this->userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        $this->accessDecisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
        $this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $this->request->query = $this->getMock('Symfony\Component\HttpFoundation\ParameterBag');
        $this->request->server = $this->getMock('Symfony\Component\HttpFoundation\ServerBag');
        $this->event = $this->getEvent($this->request);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage $providerKey must not be empty
     */
    public function testProviderKeyIsRequired()
    {
        new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
    }

    public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
    {
        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue(null));

        $this->event->expects($this->never())->method('setResponse');
        $this->securityContext->expects($this->never())->method('setToken');

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
     */
    public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound()
    {
        $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));

        $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('_exit'));

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    public function testExitUserUpdatesToken()
    {
        $originalToken = $this->getToken();
        $role = $this->getMockBuilder('Symfony\Component\Security\Core\Role\SwitchUserRole')
            ->disableOriginalConstructor()
            ->getMock();
        $role->expects($this->any())->method('getSource')->will($this->returnValue($originalToken));

        $this->securityContext->expects($this->any())
            ->method('getToken')
            ->will($this->returnValue($this->getToken(array($role))));

        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('_exit'));
        $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
        $this->request->query->expects($this->once())->method('remove','_switch_user');
        $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array()));
        $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', '');

        $this->securityContext->expects($this->once())
            ->method('setToken')->with($originalToken);
        $this->event->expects($this->once())
            ->method('setResponse')->with($this->isInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse'));

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
     */
    public function testSwitchUserIsDissallowed()
    {
        $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));

        $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));

        $this->accessDecisionManager->expects($this->once())
            ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
            ->will($this->returnValue(false));

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    public function testSwitchUser()
    {
        $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->any())->method('getRoles')->will($this->returnValue(array()));

        $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));
        $this->request->query->expects($this->once())->method('remove','_switch_user');
        $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array()));

        $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
        $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', '');

        $this->accessDecisionManager->expects($this->once())
            ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
            ->will($this->returnValue(true));

        $this->userProvider->expects($this->once())
            ->method('loadUserByUsername')->with('kuba')
            ->will($this->returnValue($user));
        $this->userChecker->expects($this->once())
            ->method('checkPostAuth')->with($user);
        $this->securityContext->expects($this->once())
            ->method('setToken')->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'));

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    public function testSwitchUserKeepsOtherQueryStringParameters()
    {
        $token = $this->getToken(array($this->getMock('Symfony\Component\Security\Core\Role\RoleInterface')));
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->any())->method('getRoles')->will($this->returnValue(array()));

        $this->securityContext->expects($this->any())->method('getToken')->will($this->returnValue($token));
        $this->request->expects($this->any())->method('get')->with('_switch_user')->will($this->returnValue('kuba'));
        $this->request->query->expects($this->once())->method('remove','_switch_user');
        $this->request->query->expects($this->any())->method('all')->will($this->returnValue(array('page'=>3,'section'=>2)));
        $this->request->expects($this->any())->method('getUri')->will($this->returnValue('/'));
        $this->request->server->expects($this->once())->method('set')->with('QUERY_STRING', 'page=3&section=2');

        $this->accessDecisionManager->expects($this->once())
            ->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
            ->will($this->returnValue(true));

        $this->userProvider->expects($this->once())
            ->method('loadUserByUsername')->with('kuba')
            ->will($this->returnValue($user));
        $this->userChecker->expects($this->once())
            ->method('checkPostAuth')->with($user);
        $this->securityContext->expects($this->once())
            ->method('setToken')->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'));

        $listener = new SwitchUserListener($this->securityContext, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
        $listener->handle($this->event);
    }

    private function getEvent($request)
    {
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();

        $event->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request));

        return $event;
    }

    private function getToken(array $roles = array())
    {
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token->expects($this->any())
            ->method('getRoles')
            ->will($this->returnValue($roles));

        return $token;
    }
}
PK11[�LMMZSecurity/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Firewall;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Firewall\X509AuthenticationListener;

class X509AuthenticationListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider dataProviderGetPreAuthenticatedData
     */
    public function testGetPreAuthenticatedData($user, $credentials)
    {
        $serverVars = array();
        if ('' !== $user) {
            $serverVars['SSL_CLIENT_S_DN_Email'] = $user;
        }
        if ('' !== $credentials) {
            $serverVars['SSL_CLIENT_S_DN'] = $credentials;
        }

        $request = new Request(array(), array(), array(), array(), array(), $serverVars);

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');

        $listener = new X509AuthenticationListener(
            $context,
            $authenticationManager,
            'TheProviderKey'
        );

        $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
        $method->setAccessible(true);

        $result = $method->invokeArgs($listener, array($request));
        $this->assertSame($result, array($user, $credentials));
    }

    public static function dataProviderGetPreAuthenticatedData()
    {
        return array(
            'validValues' => array('TheUser', 'TheCredentials'),
            'noCredentials' => array('TheUser', ''),
        );
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testGetPreAuthenticatedDataNoUser()
    {
        $request = new Request(array(), array(), array(), array(), array(), array());

        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');

        $listener = new X509AuthenticationListener(
            $context,
            $authenticationManager,
            'TheProviderKey'
        );

        $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
        $method->setAccessible(true);

        $result = $method->invokeArgs($listener, array($request));
    }

    public function testGetPreAuthenticatedDataWithDifferentKeys()
    {
        $userCredentials = array('TheUser', 'TheCredentials');

        $request = new Request(array(), array(), array(), array(), array(), array(
            'TheUserKey' => 'TheUser',
            'TheCredentialsKey' => 'TheCredentials'
        ));
        $context = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');

        $authenticationManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');

        $listener = new X509AuthenticationListener(
            $context,
            $authenticationManager,
            'TheProviderKey',
            'TheUserKey',
            'TheCredentialsKey'
        );

        $method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
        $method->setAccessible(true);

        $result = $method->invokeArgs($listener, array($request));
        $this->assertSame($result, $userCredentials);
    }
}
PK11[x��W��@Security/Symfony/Component/Security/Http/Tests/AccessMapTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests;

use Symfony\Component\Security\Http\AccessMap;

class AccessMapTest extends \PHPUnit_Framework_TestCase
{
    public function testReturnsFirstMatchedPattern()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $requestMatcher1 = $this->getRequestMatcher($request, false);
        $requestMatcher2 = $this->getRequestMatcher($request, true);

        $map = new AccessMap();
        $map->add($requestMatcher1, array('ROLE_ADMIN'), 'http');
        $map->add($requestMatcher2, array('ROLE_USER'), 'https');

        $this->assertSame(array(array('ROLE_USER'), 'https'), $map->getPatterns($request));
    }

    public function testReturnsEmptyPatternIfNoneMatched()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $requestMatcher = $this->getRequestMatcher($request, false);

        $map = new AccessMap();
        $map->add($requestMatcher, array('ROLE_USER'), 'https');

        $this->assertSame(array(null, null), $map->getPatterns($request));
    }

    private function getRequestMatcher($request, $matches)
    {
        $requestMatcher = $this->getMock('Symfony\Component\HttpFoundation\RequestMatcherInterface');
        $requestMatcher->expects($this->once())
            ->method('matches')->with($request)
            ->will($this->returnValue($matches));

        return $requestMatcher;
    }
}
PK11[���F8F8hSecurity/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\RememberMe;

use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;

use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Exception\CookieTheftException;
use Symfony\Component\Security\Core\Util\SecureRandom;

class PersistentTokenBasedRememberMeServicesTest extends \PHPUnit_Framework_TestCase
{
    public function testAutoLoginReturnsNullWhenNoCookie()
    {
        $service = $this->getService(null, array('name' => 'foo'));

        $this->assertNull($service->autoLogin(new Request()));
    }

    public function testAutoLoginThrowsExceptionOnInvalidCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
        $request = new Request();
        $request->request->set('foo', 'true');
        $request->cookies->set('foo', 'foo');

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLoginThrowsExceptionOnNonExistentToken()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
        $request = new Request();
        $request->request->set('foo', 'true');
        $request->cookies->set('foo', $this->encodeCookie(array(
            $series = 'fooseries',
            $tokenValue = 'foovalue',
        )));

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('loadTokenBySeries')
            ->will($this->throwException(new TokenNotFoundException('Token not found.')))
        ;
        $service->setTokenProvider($tokenProvider);

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLoginReturnsNullOnNonExistentUser()
    {
        $userProvider = $this->getProvider();
        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false));
        $request = new Request();
        $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('loadTokenBySeries')
            ->will($this->returnValue(new PersistentToken('fooclass', 'fooname', 'fooseries', 'foovalue', new \DateTime())))
        ;
        $service->setTokenProvider($tokenProvider);

        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->will($this->throwException(new UsernameNotFoundException('user not found')))
        ;

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
    }

    public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePersistentBackend()
    {
        $userProvider = $this->getProvider();
        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true));
        $request = new Request();
        $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $service->setTokenProvider($tokenProvider);

        $tokenProvider
            ->expects($this->once())
            ->method('loadTokenBySeries')
            ->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'anotherFooValue', new \DateTime())))
        ;

        $tokenProvider
            ->expects($this->once())
            ->method('deleteTokenBySeries')
            ->with($this->equalTo('fooseries'))
            ->will($this->returnValue(null))
        ;

        try {
            $service->autoLogin($request);
            $this->fail('Expected CookieTheftException was not thrown.');
        } catch (CookieTheftException $theft) { }

        $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
    }

    public function testAutoLoginDoesNotAcceptAnExpiredCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('loadTokenBySeries')
            ->with($this->equalTo('fooseries'))
            ->will($this->returnValue(new PersistentToken('fooclass', 'username', 'fooseries', 'foovalue', new \DateTime('yesterday'))))
        ;
        $service->setTokenProvider($tokenProvider);

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
    }

    public function testAutoLogin()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue(array('ROLE_FOO')))
        ;

        $userProvider = $this->getProvider();
        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foouser'))
            ->will($this->returnValue($user))
        ;

        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('loadTokenBySeries')
            ->with($this->equalTo('fooseries'))
            ->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'foovalue', new \DateTime())))
        ;
        $service->setTokenProvider($tokenProvider);

        $returnedToken = $service->autoLogin($request);

        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $returnedToken);
        $this->assertSame($user, $returnedToken->getUser());
        $this->assertEquals('fookey', $returnedToken->getKey());
        $this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
    }

    public function testLogout()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo'));
        $request = new Request();
        $request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('deleteTokenBySeries')
            ->with($this->equalTo('fooseries'))
            ->will($this->returnValue(null))
        ;
        $service->setTokenProvider($tokenProvider);

        $service->logout($request, $response, $token);

        $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
        $this->assertTrue($cookie->isCleared());
        $this->assertEquals('/foo', $cookie->getPath());
        $this->assertEquals('foodomain.foo', $cookie->getDomain());
    }

    public function testLogoutSimplyIgnoresNonSetRequestCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->never())
            ->method('deleteTokenBySeries')
        ;
        $service->setTokenProvider($tokenProvider);

        $service->logout($request, $response, $token);

        $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
        $this->assertTrue($cookie->isCleared());
        $this->assertEquals('/', $cookie->getPath());
        $this->assertNull($cookie->getDomain());
    }

    public function testLogoutSimplyIgnoresInvalidCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $request->cookies->set('foo', 'somefoovalue');
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->never())
            ->method('deleteTokenBySeries')
        ;
        $service->setTokenProvider($tokenProvider);

        $service->logout($request, $response, $token);

        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testLoginFail()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();

        $this->assertFalse($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
        $service->loginFail($request);
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInterfaceImplementation()
    {
        $service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
        $request = new Request();
        $response = new Response();

        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $account
            ->expects($this->once())
            ->method('getUsername')
            ->will($this->returnValue('foo'))
        ;
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->any())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        $tokenProvider = $this->getMock('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface');
        $tokenProvider
            ->expects($this->once())
            ->method('createNewToken')
        ;
        $service->setTokenProvider($tokenProvider);

        $cookies = $response->headers->getCookies();
        $this->assertCount(0, $cookies);

        $service->loginSuccess($request, $response, $token);

        $cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $cookie  = $cookies['myfoodomain.foo']['/foo/path']['foo'];
        $this->assertFalse($cookie->isCleared());
        $this->assertTrue($cookie->isSecure());
        $this->assertTrue($cookie->isHttpOnly());
        $this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
        $this->assertEquals('myfoodomain.foo', $cookie->getDomain());
        $this->assertEquals('/foo/path', $cookie->getPath());
    }

    protected function encodeCookie(array $parts)
    {
        $service = $this->getService();
        $r = new \ReflectionMethod($service, 'encodeCookie');
        $r->setAccessible(true);

        return $r->invoke($service, $parts);
    }

    protected function getService($userProvider = null, $options = array(), $logger = null)
    {
        if (null === $userProvider) {
            $userProvider = $this->getProvider();
        }

        return new PersistentTokenBasedRememberMeServices(array($userProvider), 'fookey', 'fookey', $options, $logger, new SecureRandom(sys_get_temp_dir().'/_sf2.seed'));
    }

    protected function getProvider()
    {
        $provider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
        $provider
            ->expects($this->any())
            ->method('supportsClass')
            ->will($this->returnValue(true))
        ;

        return $provider;
    }
}
PK11[�䗥1#1#\Security/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\RememberMe;

use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AbstractRememberMeServicesTest extends \PHPUnit_Framework_TestCase
{
    public function testGetRememberMeParameter()
    {
        $service = $this->getService(null, array('remember_me_parameter' => 'foo'));

        $this->assertEquals('foo', $service->getRememberMeParameter());
    }

    public function testGetKey()
    {
        $service = $this->getService();
        $this->assertEquals('fookey', $service->getKey());
    }

    public function testAutoLoginReturnsNullWhenNoCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));

        $this->assertNull($service->autoLogin(new Request()));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testAutoLoginThrowsExceptionWhenImplementationDoesNotReturnUserInterface()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $request->cookies->set('foo', 'foo');

        $service
            ->expects($this->once())
            ->method('processAutoLoginCookie')
            ->will($this->returnValue(null))
        ;

        $service->autoLogin($request);
    }

    public function testAutoLogin()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $request->cookies->set('foo', 'foo');

        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue(array()))
        ;

        $service
            ->expects($this->once())
            ->method('processAutoLoginCookie')
            ->will($this->returnValue($user))
        ;

        $returnedToken = $service->autoLogin($request);

        $this->assertSame($user, $returnedToken->getUser());
        $this->assertSame('fookey', $returnedToken->getKey());
        $this->assertSame('fookey', $returnedToken->getProviderKey());
    }

    public function testLogout()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $service->logout($request, $response, $token);

        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testLoginFail()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();

        $service->loginFail($request);

        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainUserInterfaceImplementation()
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue('foo'))
        ;

        $service
            ->expects($this->never())
            ->method('onLoginSuccess')
        ;

        $this->assertFalse($request->request->has('foo'));

        $service->loginSuccess($request, $response, $token);
    }

    public function testLoginSuccessIsNotProcessedWhenRememberMeIsNotRequested()
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        $service
            ->expects($this->never())
            ->method('onLoginSuccess')
            ->will($this->returnValue(null))
        ;

        $this->assertFalse($request->request->has('foo'));

        $service->loginSuccess($request, $response, $token);
    }

    public function testLoginSuccessWhenRememberMeAlwaysIsTrue()
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        $service
            ->expects($this->once())
            ->method('onLoginSuccess')
            ->will($this->returnValue(null))
        ;

        $service->loginSuccess($request, $response, $token);
    }

    /**
     * @dataProvider getPositiveRememberMeParameterValues
     */
    public function testLoginSuccessWhenRememberMeParameterWithPathIsPositive($value)
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo[bar]', 'path' => null, 'domain' => null));

        $request = new Request();
        $request->request->set('foo', array('bar' => $value));
        $response = new Response();
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        $service
            ->expects($this->once())
            ->method('onLoginSuccess')
            ->will($this->returnValue(true))
        ;

        $service->loginSuccess($request, $response, $token);
    }

    /**
     * @dataProvider getPositiveRememberMeParameterValues
     */
    public function testLoginSuccessWhenRememberMeParameterIsPositive($value)
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));

        $request = new Request();
        $request->request->set('foo', $value);
        $response = new Response();
        $account = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue($account))
        ;

        $service
            ->expects($this->once())
            ->method('onLoginSuccess')
            ->will($this->returnValue(true))
        ;

        $service->loginSuccess($request, $response, $token);
    }

    public function getPositiveRememberMeParameterValues()
    {
        return array(
            array('true'),
            array('1'),
            array('on'),
            array('yes'),
        );
    }

    protected function getService($userProvider = null, $options = array(), $logger = null)
    {
        if (null === $userProvider) {
            $userProvider = $this->getProvider();
        }

        return $this->getMockForAbstractClass('Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices', array(
            array($userProvider), 'fookey', 'fookey', $options, $logger
        ));
    }

    protected function getProvider()
    {
        $provider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
        $provider
            ->expects($this->any())
            ->method('supportsClass')
            ->will($this->returnValue(true))
        ;

        return $provider;
    }
}
PK11[�gZ)Z)^Security/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\RememberMe;

use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;

use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices;

class TokenBasedRememberMeServicesTest extends \PHPUnit_Framework_TestCase
{
    public function testAutoLoginReturnsNullWhenNoCookie()
    {
        $service = $this->getService(null, array('name' => 'foo'));

        $this->assertNull($service->autoLogin(new Request()));
    }

    public function testAutoLoginThrowsExceptionOnInvalidCookie()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
        $request = new Request();
        $request->request->set('foo', 'true');
        $request->cookies->set('foo', 'foo');

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLoginThrowsExceptionOnNonExistentUser()
    {
        $userProvider = $this->getProvider();
        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time()+3600, 'foopass'));

        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->will($this->throwException(new UsernameNotFoundException('user not found')))
        ;

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLoginDoesNotAcceptCookieWithInvalidHash()
    {
        $userProvider = $this->getProvider();
        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash'));

        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getPassword')
            ->will($this->returnValue('foopass'))
        ;

        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foouser'))
            ->will($this->returnValue($user))
        ;

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLoginDoesNotAcceptAnExpiredCookie()
    {
        $userProvider = $this->getProvider();
        $service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass'));

        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getPassword')
            ->will($this->returnValue('foopass'))
        ;

        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foouser'))
            ->will($this->returnValue($user))
        ;

        $this->assertNull($service->autoLogin($request));
        $this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
    }

    public function testAutoLogin()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue(array('ROLE_FOO')))
        ;
        $user
            ->expects($this->once())
            ->method('getPassword')
            ->will($this->returnValue('foopass'))
        ;

        $userProvider = $this->getProvider();
        $userProvider
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foouser'))
            ->will($this->returnValue($user))
        ;

        $service = $this->getService($userProvider, array('name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600));
        $request = new Request();
        $request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time()+3600, 'foopass'));

        $returnedToken = $service->autoLogin($request);

        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $returnedToken);
        $this->assertSame($user, $returnedToken->getUser());
        $this->assertEquals('fookey', $returnedToken->getKey());
    }

    public function testLogout()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $service->logout($request, $response, $token);

        $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
        $this->assertTrue($cookie->isCleared());
        $this->assertEquals('/', $cookie->getPath());
        $this->assertNull($cookie->getDomain());
    }

    public function testLoginFail()
    {
        $service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo'));
        $request = new Request();
        $response = new Response();

        $service->loginFail($request, $response);

        $cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
        $this->assertTrue($cookie->isCleared());
        $this->assertEquals('/foo', $cookie->getPath());
        $this->assertEquals('foodomain.foo', $cookie->getDomain());
    }

    public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImplementation()
    {
        $service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
        $request = new Request();
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue('foo'))
        ;

        $cookies = $response->headers->getCookies();
        $this->assertCount(0, $cookies);

        $service->loginSuccess($request, $response, $token);

        $cookies = $response->headers->getCookies();
        $this->assertCount(0, $cookies);
    }

    public function testLoginSuccess()
    {
        $service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
        $request = new Request();
        $response = new Response();

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getPassword')
            ->will($this->returnValue('foopass'))
        ;
        $user
            ->expects($this->once())
            ->method('getUsername')
            ->will($this->returnValue('foouser'))
        ;
        $token
            ->expects($this->atLeastOnce())
            ->method('getUser')
            ->will($this->returnValue($user))
        ;

        $cookies = $response->headers->getCookies();
        $this->assertCount(0, $cookies);

        $service->loginSuccess($request, $response, $token);

        $cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $cookie  = $cookies['myfoodomain.foo']['/foo/path']['foo'];
        $this->assertFalse($cookie->isCleared());
        $this->assertTrue($cookie->isSecure());
        $this->assertTrue($cookie->isHttpOnly());
        $this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
        $this->assertEquals('myfoodomain.foo', $cookie->getDomain());
        $this->assertEquals('/foo/path', $cookie->getPath());
    }

    protected function getCookie($class, $username, $expires, $password)
    {
        $service = $this->getService();
        $r = new \ReflectionMethod($service, 'generateCookieValue');
        $r->setAccessible(true);

        return $r->invoke($service, $class, $username, $expires, $password);
    }

    protected function encodeCookie(array $parts)
    {
        $service = $this->getService();
        $r = new \ReflectionMethod($service, 'encodeCookie');
        $r->setAccessible(true);

        return $r->invoke($service, $parts);
    }

    protected function getService($userProvider = null, $options = array(), $logger = null)
    {
        if (null === $userProvider) {
            $userProvider = $this->getProvider();
        }

        $service = new TokenBasedRememberMeServices(array($userProvider), 'fookey', 'fookey', $options, $logger);

        return $service;
    }

    protected function getProvider()
    {
        $provider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
        $provider
            ->expects($this->any())
            ->method('supportsClass')
            ->will($this->returnValue(true))
        ;

        return $provider;
    }
}
PK11[��ʅ
�
RSecurity/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\RememberMe;

use Symfony\Component\Security\Http\RememberMe\ResponseListener;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\KernelEvents;

class ResponseListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testRememberMeCookieIsSentWithResponse()
    {
        $cookie = new Cookie('rememberme');

        $request = $this->getRequest(array(
            RememberMeServicesInterface::COOKIE_ATTR_NAME => $cookie
        ));

        $response = $this->getResponse();
        $response->headers->expects($this->once())->method('setCookie')->with($cookie);

        $listener = new ResponseListener();
        $listener->onKernelResponse($this->getEvent($request, $response));
    }

    public function testRememberMeCookieIsNotSendWithResponse()
    {
        $request = $this->getRequest();

        $response = $this->getResponse();
        $response->headers->expects($this->never())->method('setCookie');

        $listener = new ResponseListener();
        $listener->onKernelResponse($this->getEvent($request, $response));
    }

    public function testItSubscribesToTheOnKernelResponseEvent()
    {
        $listener = new ResponseListener();

        $this->assertSame(array(KernelEvents::RESPONSE => 'onKernelResponse'), ResponseListener::getSubscribedEvents());
    }

    private function getRequest(array $attributes = array())
    {
        $request = new Request();

        foreach ($attributes as $name => $value) {
            $request->attributes->set($name, $value);
        }

        return $request;
    }

    private function getResponse()
    {
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');
        $response->headers = $this->getMock('Symfony\Component\HttpFoundation\ResponseHeaderBag');

        return $response;
    }

    private function getEvent($request, $response)
    {
        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();

        $event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
        $event->expects($this->any())->method('getResponse')->will($this->returnValue($response));

        return $event;
    }
}
PK11[Y�Ң	�	\Security/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Session;

use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;

class SessionAuthenticationStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testSessionIsNotChanged()
    {
        $request = $this->getRequest();
        $request->expects($this->never())->method('getSession');

        $strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE);
        $strategy->onAuthentication($request, $this->getToken());
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Invalid session authentication strategy "foo"
     */
    public function testUnsupportedStrategy()
    {
        $request = $this->getRequest();
        $request->expects($this->never())->method('getSession');

        $strategy = new SessionAuthenticationStrategy('foo');
        $strategy->onAuthentication($request, $this->getToken());
    }

    public function testSessionIsMigrated()
    {
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
        $session->expects($this->once())->method('migrate');

        $strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE);
        $strategy->onAuthentication($this->getRequest($session), $this->getToken());
    }

    public function testSessionIsInvalidated()
    {
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
        $session->expects($this->once())->method('invalidate');

        $strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::INVALIDATE);
        $strategy->onAuthentication($this->getRequest($session), $this->getToken());
    }

    private function getRequest($session = null)
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');

        if (null !== $session) {
            $request->expects($this->any())->method('getSession')->will($this->returnValue($session));
        }

        return $request;
    }

    private function getToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }
}
PK11[�
{{YSecurity/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Logout;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;

class DefaultLogoutSuccessHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testLogout()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');

        $httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $httpUtils->expects($this->once())
            ->method('createRedirectResponse')
            ->with($request, '/dashboard')
            ->will($this->returnValue($response));

        $handler = new DefaultLogoutSuccessHandler($httpUtils, '/dashboard');
        $result = $handler->onLogoutSuccess($request);

        $this->assertSame($response, $result);
    }
}
PK11[]�ͷ��RSecurity/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Logout;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\SessionLogoutHandler;

class SessionLogoutHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testLogout()
    {
        $handler = new SessionLogoutHandler();

        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $response = new Response();
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\Session', array(), array(), '', false);

        $request
            ->expects($this->once())
            ->method('getSession')
            ->will($this->returnValue($session))
        ;

        $session
            ->expects($this->once())
            ->method('invalidate')
        ;

        $handler->logout($request, $response, $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
    }
}
PK11[k��YSecurity/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Logout;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Logout\CookieClearingLogoutHandler;

class CookieClearingLogoutHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testLogout()
    {
        $request = new Request();
        $response = new Response();
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        $handler = new CookieClearingLogoutHandler(array('foo' => array('path' => '/foo', 'domain' => 'foo.foo'), 'foo2' => array('path' => null, 'domain' => null)));

        $cookies = $response->headers->getCookies();
        $this->assertCount(0, $cookies);

        $handler->logout($request, $response, $token);

        $cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertCount(2, $cookies);

        $cookie = $cookies['foo.foo']['/foo']['foo'];
        $this->assertEquals('foo', $cookie->getName());
        $this->assertEquals('/foo', $cookie->getPath());
        $this->assertEquals('foo.foo', $cookie->getDomain());
        $this->assertTrue($cookie->isCleared());

        $cookie = $cookies['']['/']['foo2'];
        $this->assertStringStartsWith('foo2', $cookie->getName());
        $this->assertEquals('/', $cookie->getPath());
        $this->assertNull($cookie->getDomain());
        $this->assertTrue($cookie->isCleared());
    }
}
PK11[$a��iSecurity/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Authentication;

use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class DefaultAuthenticationFailureHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $httpKernel = null;

    private $httpUtils = null;

    private $logger = null;

    private $request = null;

    private $session = null;

    private $exception = null;

    protected function setUp()
    {
        $this->httpKernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $this->httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $this->logger = $this->getMock('Psr\Log\LoggerInterface');

        $this->session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
        $this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $this->request->expects($this->any())->method('getSession')->will($this->returnValue($this->session));
        $this->exception = $this->getMock('Symfony\Component\Security\Core\Exception\AuthenticationException');
    }

    public function testForward()
    {
        $options = array('failure_forward' => true);

        $subRequest = $this->getRequest();
        $subRequest->attributes->expects($this->once())
            ->method('set')->with(SecurityContextInterface::AUTHENTICATION_ERROR, $this->exception);
        $this->httpUtils->expects($this->once())
            ->method('createRequest')->with($this->request, '/login')
            ->will($this->returnValue($subRequest));

        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');
        $this->httpKernel->expects($this->once())
            ->method('handle')->with($subRequest, HttpKernelInterface::SUB_REQUEST)
            ->will($this->returnValue($response));

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
        $result = $handler->onAuthenticationFailure($this->request, $this->exception);

        $this->assertSame($response, $result);
    }

    public function testRedirect()
    {
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');
        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')->with($this->request, '/login')
            ->will($this->returnValue($response));

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
        $result = $handler->onAuthenticationFailure($this->request, $this->exception);

        $this->assertSame($response, $result);
    }

    public function testExceptionIsPersistedInSession()
    {
        $this->session->expects($this->once())
            ->method('set')->with(SecurityContextInterface::AUTHENTICATION_ERROR, $this->exception);

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testExceptionIsPassedInRequestOnForward()
    {
        $options = array('failure_forward' => true);

        $subRequest = $this->getRequest();
        $subRequest->attributes->expects($this->once())
            ->method('set')->with(SecurityContextInterface::AUTHENTICATION_ERROR, $this->exception);

        $this->httpUtils->expects($this->once())
            ->method('createRequest')->with($this->request, '/login')
            ->will($this->returnValue($subRequest));

        $this->session->expects($this->never())->method('set');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testRedirectIsLogged()
    {
        $this->logger->expects($this->once())->method('debug')->with('Redirecting to /login');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testForwardIsLogged()
    {
        $options = array('failure_forward' => true);

        $this->httpUtils->expects($this->once())
            ->method('createRequest')->with($this->request, '/login')
            ->will($this->returnValue($this->getRequest()));

        $this->logger->expects($this->once())->method('debug')->with('Forwarding to /login');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testFailurePathCanBeOverwritten()
    {
        $options = array('failure_path' => '/auth/login');

        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')->with($this->request, '/auth/login');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testFailurePathCanBeOverwrittenWithRequest()
    {
        $this->request->expects($this->once())
            ->method('get')->with('_failure_path', null, true)
            ->will($this->returnValue('/auth/login'));

        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')->with($this->request, '/auth/login');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    public function testFailurePathParameterCanBeOverwritten()
    {
        $options = array('failure_path_parameter' => '_my_failure_path');

        $this->request->expects($this->once())
            ->method('get')->with('_my_failure_path', null, true)
            ->will($this->returnValue('/auth/login'));

        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')->with($this->request, '/auth/login');

        $handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
        $handler->onAuthenticationFailure($this->request, $this->exception);
    }

    private function getRequest()
    {
        $request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $request->attributes = $this->getMock('Symfony\Component\HttpFoundation\ParameterBag');

        return $request;
    }
}
PK11[/w!w!aSecurity/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests;

use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimpleAuthenticationHandler;

class SimpleAuthenticationHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $successHandler;

    private $failureHandler;

    private $request;

    private $token;

    private $authenticationException;

    private $response;

    public function setUp()
    {
        $this->successHandler = $this->getMock('Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface');
        $this->failureHandler = $this->getMock('Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface');

        $this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $this->token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $this->authenticationException = $this->getMock('Symfony\Component\Security\Core\Exception\AuthenticationException');

        $this->response = $this->getMock('Symfony\Component\HttpFoundation\Response');
    }

    public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfSimpleIsNotASuccessHandler()
    {
        $authenticator = $this->getMock('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface');

        $this->successHandler->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->with($this->request, $this->token)
            ->will($this->returnValue($this->response));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($this->response, $result);
    }

    public function testOnAuthenticationSuccessCallsSimpleAuthenticator()
    {
        $this->successHandler->expects($this->never())
            ->method('onAuthenticationSuccess');

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->with($this->request, $this->token)
            ->will($this->returnValue($this->response));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($this->response, $result);
    }

    /**
     * @expectedException        \UnexpectedValueException
     * @expectedExceptionMessage onAuthenticationSuccess method must return null to use the default success handler, or a Response object
     */
    public function testOnAuthenticationSuccessThrowsAnExceptionIfNonResponseIsReturned()
    {
        $this->successHandler->expects($this->never())
            ->method('onAuthenticationSuccess');

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->with($this->request, $this->token)
            ->will($this->returnValue(new \stdClass()));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $handler->onAuthenticationSuccess($this->request, $this->token);
    }

    public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfNullIsReturned()
    {
        $this->successHandler->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->with($this->request, $this->token)
            ->will($this->returnValue($this->response));

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationSuccess')
            ->with($this->request, $this->token)
            ->will($this->returnValue(null));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($this->response, $result);
    }

    public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfSimpleIsNotAFailureHandler()
    {
        $authenticator = $this->getMock('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface');

        $this->failureHandler->expects($this->once())
            ->method('onAuthenticationFailure')
            ->with($this->request, $this->authenticationException)
            ->will($this->returnValue($this->response));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);

        $this->assertSame($this->response, $result);
    }

    public function testOnAuthenticationFailureCallsSimpleAuthenticator()
    {
        $this->failureHandler->expects($this->never())
            ->method('onAuthenticationFailure');

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationFailure')
            ->with($this->request, $this->authenticationException)
            ->will($this->returnValue($this->response));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);

        $this->assertSame($this->response, $result);
    }

    /**
     * @expectedException        \UnexpectedValueException
     * @expectedExceptionMessage onAuthenticationFailure method must return null to use the default failure handler, or a Response object
     */
    public function testOnAuthenticationFailureThrowsAnExceptionIfNonResponseIsReturned()
    {
        $this->failureHandler->expects($this->never())
            ->method('onAuthenticationFailure');

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationFailure')
            ->with($this->request, $this->authenticationException)
            ->will($this->returnValue(new \stdClass()));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $handler->onAuthenticationFailure($this->request, $this->authenticationException);
    }

    public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfNullIsReturned()
    {
        $this->failureHandler->expects($this->once())
            ->method('onAuthenticationFailure')
            ->with($this->request, $this->authenticationException)
            ->will($this->returnValue($this->response));

        $authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
        $authenticator->expects($this->once())
            ->method('onAuthenticationFailure')
            ->with($this->request, $this->authenticationException)
            ->will($this->returnValue(null));

        $handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
        $result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);

        $this->assertSame($this->response, $result);
    }
}

interface TestSuccessHandlerInterface extends AuthenticationSuccessHandlerInterface, SimpleAuthenticatorInterface
{
}

interface TestFailureHandlerInterface extends AuthenticationFailureHandlerInterface, SimpleAuthenticatorInterface
{
}
PK11[id]z��iSecurity/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Http\Tests\Authentication;

use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;

class DefaultAuthenticationSuccessHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $httpUtils = null;

    private $request = null;

    private $token = null;

    protected function setUp()
    {
        $this->httpUtils = $this->getMock('Symfony\Component\Security\Http\HttpUtils');
        $this->request = $this->getMock('Symfony\Component\HttpFoundation\Request');
        $this->request->headers = $this->getMock('Symfony\Component\HttpFoundation\HeaderBag');
        $this->token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }

    public function testRequestIsRedirected()
    {
        $response = $this->expectRedirectResponse('/');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, array());
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testDefaultTargetPathCanBeForced()
    {
        $options = array(
            'always_use_default_target_path' => true,
            'default_target_path' => '/dashboard'
        );

        $response = $this->expectRedirectResponse('/dashboard');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, $options);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testTargetPathIsPassedWithRequest()
    {
        $this->request->expects($this->once())
            ->method('get')->with('_target_path')
            ->will($this->returnValue('/dashboard'));

        $response = $this->expectRedirectResponse('/dashboard');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, array());
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testTargetPathParameterIsCustomised()
    {
        $options = array('target_path_parameter' => '_my_target_path');

        $this->request->expects($this->once())
            ->method('get')->with('_my_target_path')
            ->will($this->returnValue('/dashboard'));

        $response = $this->expectRedirectResponse('/dashboard');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, $options);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testTargetPathIsTakenFromTheSession()
    {
        $session = $this->getMock('Symfony\Component\HttpFoundation\Session\SessionInterface');
        $session->expects($this->once())
            ->method('get')->with('_security.admin.target_path')
            ->will($this->returnValue('/admin/dashboard'));
        $session->expects($this->once())
            ->method('remove')->with('_security.admin.target_path');

        $this->request->expects($this->any())
            ->method('getSession')
            ->will($this->returnValue($session));

        $response = $this->expectRedirectResponse('/admin/dashboard');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, array());
        $handler->setProviderKey('admin');

        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testTargetPathIsPassedAsReferer()
    {
        $options = array('use_referer' => true);

        $this->request->headers->expects($this->once())
            ->method('get')->with('Referer')
            ->will($this->returnValue('/dashboard'));

        $response = $this->expectRedirectResponse('/dashboard');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, $options);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testRefererHasToBeDifferentThatLoginUrl()
    {
        $options = array('use_referer' => true);

        $this->request->headers->expects($this->any())
            ->method('get')->with('Referer')
            ->will($this->returnValue('/login'));

        $this->httpUtils->expects($this->once())
            ->method('generateUri')->with($this->request, '/login')
            ->will($this->returnValue('/login'));

        $response = $this->expectRedirectResponse('/');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, $options);
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    public function testRefererTargetPathIsIgnoredByDefault()
    {
        $this->request->headers->expects($this->never())->method('get');

        $response = $this->expectRedirectResponse('/');

        $handler = new DefaultAuthenticationSuccessHandler($this->httpUtils, array());
        $result = $handler->onAuthenticationSuccess($this->request, $this->token);

        $this->assertSame($response, $result);
    }

    private function expectRedirectResponse($path)
    {
        $response = $this->getMock('Symfony\Component\HttpFoundation\Response');

        $this->httpUtils->expects($this->once())
            ->method('createRedirectResponse')
            ->with($this->request, $path)
            ->will($this->returnValue($response));

        return $response;
    }
}
PK11[?k,.<<9Security/Symfony/Component/Security/Http/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Security Component HTTP Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK11[�|G

]Security/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Csrf\Tests\TokenStorage;

use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 *
 * @runTestsInSeparateProcesses
 */
class NativeSessionTokenStorageTest extends \PHPUnit_Framework_TestCase
{
    const SESSION_NAMESPACE = 'foobar';

    /**
     * @var NativeSessionTokenStorage
     */
    private $storage;

    public static function setUpBeforeClass()
    {
        ini_set('session.save_handler', 'files');
        ini_set('session.save_path', sys_get_temp_dir());

        parent::setUpBeforeClass();
    }

    protected function setUp()
    {
        $_SESSION = array();

        $this->storage = new NativeSessionTokenStorage(self::SESSION_NAMESPACE);
    }

    public function testStoreTokenInClosedSession()
    {
        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame(array(self::SESSION_NAMESPACE => array('token_id' => 'TOKEN')), $_SESSION);
    }

    public function testStoreTokenInClosedSessionWithExistingSessionId()
    {
        if (version_compare(PHP_VERSION, '5.4', '<')) {
            $this->markTestSkipped('This test requires PHP 5.4 or later.');
        }

        session_id('foobar');

        $this->assertSame(PHP_SESSION_NONE, session_status());

        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame(PHP_SESSION_ACTIVE, session_status());
        $this->assertSame(array(self::SESSION_NAMESPACE => array('token_id' => 'TOKEN')), $_SESSION);
    }

    public function testStoreTokenInActiveSession()
    {
        session_start();

        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame(array(self::SESSION_NAMESPACE => array('token_id' => 'TOKEN')), $_SESSION);
    }

    /**
     * @depends testStoreTokenInClosedSession
     */
    public function testCheckToken()
    {
        $this->assertFalse($this->storage->hasToken('token_id'));

        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertTrue($this->storage->hasToken('token_id'));
    }

    /**
     * @depends testStoreTokenInClosedSession
     */
    public function testGetExistingToken()
    {
        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame('TOKEN', $this->storage->getToken('token_id'));
    }

    /**
     * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException
     */
    public function testGetNonExistingToken()
    {
        $this->storage->getToken('token_id');
    }

    /**
     * @depends testCheckToken
     */
    public function testRemoveNonExistingToken()
    {
        $this->assertNull($this->storage->removeToken('token_id'));
        $this->assertFalse($this->storage->hasToken('token_id'));
    }

    /**
     * @depends testCheckToken
     */
    public function testRemoveExistingToken()
    {
        $this->storage->setToken('token_id', 'TOKEN');

        $this->assertSame('TOKEN', $this->storage->removeToken('token_id'));
        $this->assertFalse($this->storage->hasToken('token_id'));
    }
}
PK11[���WWWSecurity/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Csrf\Tests\TokenStorage;

use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class SessionTokenStorageTest extends \PHPUnit_Framework_TestCase
{
    const SESSION_NAMESPACE = 'foobar';

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $session;

    /**
     * @var SessionTokenStorage
     */
    private $storage;

    protected function setUp()
    {
        if (!interface_exists('Symfony\Component\HttpFoundation\Session\SessionInterface')) {
            $this->markTestSkipped('The "HttpFoundation" component is not available');
        }

        $this->session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')
            ->disableOriginalConstructor()
            ->getMock();
        $this->storage = new SessionTokenStorage($this->session, self::SESSION_NAMESPACE);
    }

    public function testStoreTokenInClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('set')
            ->with(self::SESSION_NAMESPACE.'/token_id', 'TOKEN');

        $this->storage->setToken('token_id', 'TOKEN');
    }

    public function testStoreTokenInActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('set')
            ->with(self::SESSION_NAMESPACE.'/token_id', 'TOKEN');

        $this->storage->setToken('token_id', 'TOKEN');
    }

    public function testCheckTokenInClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('RESULT'));

        $this->assertSame('RESULT', $this->storage->hasToken('token_id'));
    }

    public function testCheckTokenInActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('RESULT'));

        $this->assertSame('RESULT', $this->storage->hasToken('token_id'));
    }

    public function testGetExistingTokenFromClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(true));

        $this->session->expects($this->once())
            ->method('get')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('RESULT'));

        $this->assertSame('RESULT', $this->storage->getToken('token_id'));
    }

    public function testGetExistingTokenFromActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(true));

        $this->session->expects($this->once())
            ->method('get')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('RESULT'));

        $this->assertSame('RESULT', $this->storage->getToken('token_id'));
    }

    /**
     * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException
     */
    public function testGetNonExistingTokenFromClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(false));

        $this->storage->getToken('token_id');
    }

    /**
     * @expectedException \Symfony\Component\Security\Csrf\Exception\TokenNotFoundException
     */
    public function testGetNonExistingTokenFromActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('has')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(false));

        $this->storage->getToken('token_id');
    }

    public function testRemoveNonExistingTokenFromClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('remove')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(null));

        $this->assertNull($this->storage->removeToken('token_id'));
    }

    public function testRemoveNonExistingTokenFromActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('remove')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue(null));

        $this->assertNull($this->storage->removeToken('token_id'));
    }

    public function testRemoveExistingTokenFromClosedSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $this->session->expects($this->once())
            ->method('start');

        $this->session->expects($this->once())
            ->method('remove')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('TOKEN'));

        $this->assertSame('TOKEN', $this->storage->removeToken('token_id'));
    }

    public function testRemoveExistingTokenFromActiveSession()
    {
        $this->session->expects($this->any())
            ->method('isStarted')
            ->will($this->returnValue(true));

        $this->session->expects($this->never())
            ->method('start');

        $this->session->expects($this->once())
            ->method('remove')
            ->with(self::SESSION_NAMESPACE.'/token_id')
            ->will($this->returnValue('TOKEN'));

        $this->assertSame('TOKEN', $this->storage->removeToken('token_id'));
    }
}
PK11[�-�kkGSecurity/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Csrf\Tests;

use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManager;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CsrfTokenManagerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $generator;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $storage;

    /**
     * @var CsrfTokenManager
     */
    private $manager;

    protected function setUp()
    {
        $this->generator = $this->getMock('Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface');
        $this->storage = $this->getMock('Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface');
        $this->manager = new CsrfTokenManager($this->generator, $this->storage);
    }

    protected function tearDown()
    {
        $this->generator = null;
        $this->storage = null;
        $this->manager = null;
    }

    public function testGetNonExistingToken()
    {
        $this->storage->expects($this->once())
            ->method('hasToken')
            ->with('token_id')
            ->will($this->returnValue(false));

        $this->generator->expects($this->once())
            ->method('generateToken')
            ->will($this->returnValue('TOKEN'));

        $this->storage->expects($this->once())
            ->method('setToken')
            ->with('token_id', 'TOKEN');

        $token = $this->manager->getToken('token_id');

        $this->assertInstanceOf('Symfony\Component\Security\Csrf\CsrfToken', $token);
        $this->assertSame('token_id', $token->getId());
        $this->assertSame('TOKEN', $token->getValue());
    }

    public function testUseExistingTokenIfAvailable()
    {
        $this->storage->expects($this->once())
            ->method('hasToken')
            ->with('token_id')
            ->will($this->returnValue(true));

        $this->storage->expects($this->once())
            ->method('getToken')
            ->with('token_id')
            ->will($this->returnValue('TOKEN'));

        $token = $this->manager->getToken('token_id');

        $this->assertInstanceOf('Symfony\Component\Security\Csrf\CsrfToken', $token);
        $this->assertSame('token_id', $token->getId());
        $this->assertSame('TOKEN', $token->getValue());
    }

    public function testRefreshTokenAlwaysReturnsNewToken()
    {
        $this->storage->expects($this->never())
            ->method('hasToken');

        $this->generator->expects($this->once())
            ->method('generateToken')
            ->will($this->returnValue('TOKEN'));

        $this->storage->expects($this->once())
            ->method('setToken')
            ->with('token_id', 'TOKEN');

        $token = $this->manager->refreshToken('token_id');

        $this->assertInstanceOf('Symfony\Component\Security\Csrf\CsrfToken', $token);
        $this->assertSame('token_id', $token->getId());
        $this->assertSame('TOKEN', $token->getValue());
    }

    public function testMatchingTokenIsValid()
    {
        $this->storage->expects($this->once())
            ->method('hasToken')
            ->with('token_id')
            ->will($this->returnValue(true));

        $this->storage->expects($this->once())
            ->method('getToken')
            ->with('token_id')
            ->will($this->returnValue('TOKEN'));

        $this->assertTrue($this->manager->isTokenValid(new CsrfToken('token_id', 'TOKEN')));
    }

    public function testNonMatchingTokenIsNotValid()
    {
        $this->storage->expects($this->once())
            ->method('hasToken')
            ->with('token_id')
            ->will($this->returnValue(true));

        $this->storage->expects($this->once())
            ->method('getToken')
            ->with('token_id')
            ->will($this->returnValue('TOKEN'));

        $this->assertFalse($this->manager->isTokenValid(new CsrfToken('token_id', 'FOOBAR')));
    }

    public function testNonExistingTokenIsNotValid()
    {
        $this->storage->expects($this->once())
            ->method('hasToken')
            ->with('token_id')
            ->will($this->returnValue(false));

        $this->storage->expects($this->never())
            ->method('getToken');

        $this->assertFalse($this->manager->isTokenValid(new CsrfToken('token_id', 'FOOBAR')));
    }

    public function testRemoveToken()
    {
        $this->storage->expects($this->once())
            ->method('removeToken')
            ->with('token_id')
            ->will($this->returnValue('REMOVED_TOKEN'));

        $this->assertSame('REMOVED_TOKEN', $this->manager->removeToken('token_id'));
    }
}
PK11[�3�z(([Security/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Csrf\Tests\TokenGenerator;

use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UriSafeTokenGeneratorTest extends \PHPUnit_Framework_TestCase
{
    const ENTROPY = 1000;

    /**
     * A non alpha-numeric byte string
     * @var string
     */
    private static $bytes;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $random;

    /**
     * @var UriSafeTokenGenerator
     */
    private $generator;

    public static function setUpBeforeClass()
    {
        self::$bytes = base64_decode('aMf+Tct/RLn2WQ==');
    }

    protected function setUp()
    {
        $this->random = $this->getMock('Symfony\Component\Security\Core\Util\SecureRandomInterface');
        $this->generator = new UriSafeTokenGenerator($this->random, self::ENTROPY);
    }

    protected function tearDown()
    {
        $this->random = null;
        $this->generator = null;
    }

    public function testGenerateToken()
    {
        $this->random->expects($this->once())
            ->method('nextBytes')
            ->with(self::ENTROPY/8)
            ->will($this->returnValue(self::$bytes));

        $token = $this->generator->generateToken();

        $this->assertTrue(ctype_print($token), 'is printable');
        $this->assertStringNotMatchesFormat('%S+%S', $token, 'is URI safe');
        $this->assertStringNotMatchesFormat('%S/%S', $token, 'is URI safe');
        $this->assertStringNotMatchesFormat('%S=%S', $token, 'is URI safe');
    }
}
PK11[��*�<<9Security/Symfony/Component/Security/Csrf/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Security Component CSRF Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK11[ׄHAnnFSecurity/Symfony/Component/Security/Core/Tests/SecurityContextTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests;

use Symfony\Component\Security\Core\SecurityContext;

class SecurityContextTest extends \PHPUnit_Framework_TestCase
{
    public function testVoteAuthenticatesTokenIfNecessary()
    {
        $authManager = $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface');
        $decisionManager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');

        $context = new SecurityContext($authManager, $decisionManager);
        $context->setToken($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));

        $authManager
            ->expects($this->once())
            ->method('authenticate')
            ->with($this->equalTo($token))
            ->will($this->returnValue($newToken = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')))
        ;

        $decisionManager
            ->expects($this->once())
            ->method('decide')
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($context->isGranted('foo'));
        $this->assertSame($newToken, $context->getToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
     */
    public function testVoteWithoutAuthenticationToken()
    {
        $context = new SecurityContext(
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
            $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')
        );

        $context->isGranted('ROLE_FOO');
    }

    public function testIsGranted()
    {
        $manager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
        $manager->expects($this->once())->method('decide')->will($this->returnValue(false));
        $context = new SecurityContext($this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'), $manager);
        $context->setToken($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $token
            ->expects($this->once())
            ->method('isAuthenticated')
            ->will($this->returnValue(true))
        ;
        $this->assertFalse($context->isGranted('ROLE_FOO'));

        $manager = $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface');
        $manager->expects($this->once())->method('decide')->will($this->returnValue(true));
        $context = new SecurityContext($this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'), $manager);
        $context->setToken($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $token
            ->expects($this->once())
            ->method('isAuthenticated')
            ->will($this->returnValue(true))
        ;
        $this->assertTrue($context->isGranted('ROLE_FOO'));
    }

    public function testGetSetToken()
    {
        $context = new SecurityContext(
            $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface'),
            $this->getMock('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')
        );
        $this->assertNull($context->getToken());

        $context->setToken($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $this->assertSame($token, $context->getToken());
    }
}
PK11[xF�@Security/Symfony/Component/Security/Core/Tests/Role/RoleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Role;

use Symfony\Component\Security\Core\Role\Role;

class RoleTest extends \PHPUnit_Framework_TestCase
{
    public function testGetRole()
    {
        $role = new Role('FOO');

        $this->assertEquals('FOO', $role->getRole());
    }
}
PK11[t�S��ISecurity/Symfony/Component/Security/Core/Tests/Role/RoleHierarchyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Role;

use Symfony\Component\Security\Core\Role\RoleHierarchy;
use Symfony\Component\Security\Core\Role\Role;

class RoleHierarchyTest extends \PHPUnit_Framework_TestCase
{
    public function testGetReachableRoles()
    {
        $role = new RoleHierarchy(array(
            'ROLE_ADMIN' => array('ROLE_USER'),
            'ROLE_SUPER_ADMIN' => array('ROLE_ADMIN', 'ROLE_FOO'),
        ));

        $this->assertEquals(array(new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_USER'))));
        $this->assertEquals(array(new Role('ROLE_FOO')), $role->getReachableRoles(array(new Role('ROLE_FOO'))));
        $this->assertEquals(array(new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_ADMIN'))));
        $this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_FOO'), new Role('ROLE_ADMIN'))));
        $this->assertEquals(array(new Role('ROLE_SUPER_ADMIN'), new Role('ROLE_ADMIN'), new Role('ROLE_FOO'), new Role('ROLE_USER')), $role->getReachableRoles(array(new Role('ROLE_SUPER_ADMIN'))));
    }
}
PK11[��{{JSecurity/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Role;

use Symfony\Component\Security\Core\Role\SwitchUserRole;

class SwitchUserRoleTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSource()
    {
        $role = new SwitchUserRole('FOO', $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));

        $this->assertSame($token, $role->getSource());
    }

    public function testGetRole()
    {
        $role = new SwitchUserRole('FOO', $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));

        $this->assertEquals('FOO', $role->getRole());
    }
}
PK11[r��nnTSecurity/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\Pbkdf2PasswordEncoder;

class Pbkdf2PasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
    public function testIsPasswordValid()
    {
        $encoder = new Pbkdf2PasswordEncoder('sha256', false, 1, 40);

        $this->assertTrue($encoder->isPasswordValid('c1232f10f62715fda06ae7c0a2037ca19b33cf103b727ba56d870c11f290a2ab106974c75607c8a3', 'password', ''));
    }

    public function testEncodePassword()
    {
        $encoder = new Pbkdf2PasswordEncoder('sha256', false, 1, 40);
        $this->assertSame('c1232f10f62715fda06ae7c0a2037ca19b33cf103b727ba56d870c11f290a2ab106974c75607c8a3', $encoder->encodePassword('password', ''));

        $encoder = new Pbkdf2PasswordEncoder('sha256', true, 1, 40);
        $this->assertSame('wSMvEPYnFf2gaufAogN8oZszzxA7cnulbYcMEfKQoqsQaXTHVgfIow==', $encoder->encodePassword('password', ''));

        $encoder = new Pbkdf2PasswordEncoder('sha256', false, 2, 40);
        $this->assertSame('8bc2f9167a81cdcfad1235cd9047f1136271c1f978fcfcb35e22dbeafa4634f6fd2214218ed63ebb', $encoder->encodePassword('password', ''));
    }

    /**
     * @expectedException \LogicException
     */
    public function testEncodePasswordAlgorithmDoesNotExist()
    {
        $encoder = new Pbkdf2PasswordEncoder('foobar');
        $encoder->encodePassword('password', '');
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testEncodePasswordLength()
    {
        $encoder = new Pbkdf2PasswordEncoder('foobar');

        $encoder->encodePassword(str_repeat('a', 5000), 'salt');
    }

    public function testCheckPasswordLength()
    {
        $encoder = new Pbkdf2PasswordEncoder('foobar');

        $this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
    }
}
PK11[6���WSecurity/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;

class PlaintextPasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
    public function testIsPasswordValid()
    {
        $encoder = new PlaintextPasswordEncoder();

        $this->assertTrue($encoder->isPasswordValid('foo', 'foo', ''));
        $this->assertFalse($encoder->isPasswordValid('bar', 'foo', ''));
        $this->assertFalse($encoder->isPasswordValid('FOO', 'foo', ''));

        $encoder = new PlaintextPasswordEncoder(true);

        $this->assertTrue($encoder->isPasswordValid('foo', 'foo', ''));
        $this->assertFalse($encoder->isPasswordValid('bar', 'foo', ''));
        $this->assertTrue($encoder->isPasswordValid('FOO', 'foo', ''));
    }

    public function testEncodePassword()
    {
        $encoder = new PlaintextPasswordEncoder();

        $this->assertSame('foo', $encoder->encodePassword('foo', ''));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testEncodePasswordLength()
    {
        $encoder = new PlaintextPasswordEncoder();

        $encoder->encodePassword(str_repeat('a', 5000), 'salt');
    }

    public function testCheckPasswordLength()
    {
        $encoder = new PlaintextPasswordEncoder();

        $this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
    }
}
PK11[L�'��RSecurity/Symfony/Component/Security/Core/Tests/Encoder/BasePasswordEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;

class PasswordEncoder extends BasePasswordEncoder
{
    public function encodePassword($raw, $salt)
    {
    }

    public function isPasswordValid($encoded, $raw, $salt)
    {
    }
}

class BasePasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
    public function testComparePassword()
    {
        $this->assertTrue($this->invokeComparePasswords('password', 'password'));
        $this->assertFalse($this->invokeComparePasswords('password', 'foo'));
    }

    public function testDemergePasswordAndSalt()
    {
        $this->assertEquals(array('password', 'salt'), $this->invokeDemergePasswordAndSalt('password{salt}'));
        $this->assertEquals(array('password', ''), $this->invokeDemergePasswordAndSalt('password'));
        $this->assertEquals(array('', ''), $this->invokeDemergePasswordAndSalt(''));
    }

    public function testMergePasswordAndSalt()
    {
        $this->assertEquals('password{salt}', $this->invokeMergePasswordAndSalt('password', 'salt'));
        $this->assertEquals('password', $this->invokeMergePasswordAndSalt('password', ''));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testMergePasswordAndSaltWithException()
    {
        $this->invokeMergePasswordAndSalt('password', '{foo}');
    }

    public function testIsPasswordTooLong()
    {
        $this->assertTrue($this->invokeIsPasswordTooLong(str_repeat('a', 10000)));
        $this->assertFalse($this->invokeIsPasswordTooLong(str_repeat('a', 10)));
    }

    protected function invokeDemergePasswordAndSalt($password)
    {
        $encoder = new PasswordEncoder();
        $r = new \ReflectionObject($encoder);
        $m = $r->getMethod('demergePasswordAndSalt');
        $m->setAccessible(true);

        return $m->invoke($encoder, $password);
    }

    protected function invokeMergePasswordAndSalt($password, $salt)
    {
        $encoder = new PasswordEncoder();
        $r = new \ReflectionObject($encoder);
        $m = $r->getMethod('mergePasswordAndSalt');
        $m->setAccessible(true);

        return $m->invoke($encoder, $password, $salt);
    }

    protected function invokeComparePasswords($p1, $p2)
    {
        $encoder = new PasswordEncoder();
        $r = new \ReflectionObject($encoder);
        $m = $r->getMethod('comparePasswords');
        $m->setAccessible(true);

        return $m->invoke($encoder, $p1, $p2);
    }

    protected function invokeIsPasswordTooLong($p)
    {
        $encoder = new PasswordEncoder();
        $r = new \ReflectionObject($encoder);
        $m = $r->getMethod('isPasswordTooLong');
        $m->setAccessible(true);

        return $m->invoke($encoder, $p);
    }
}
PK21[%�s�MSecurity/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;

class EncoderFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testGetEncoderWithMessageDigestEncoder()
    {
        $factory = new EncoderFactory(array('Symfony\Component\Security\Core\User\UserInterface' => array(
            'class' => 'Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder',
            'arguments' => array('sha512', true, 5),
        )));

        $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\UserInterface'));
        $expectedEncoder = new MessageDigestPasswordEncoder('sha512', true, 5);

        $this->assertEquals($expectedEncoder->encodePassword('foo', 'moo'), $encoder->encodePassword('foo', 'moo'));
    }

    public function testGetEncoderWithService()
    {
        $factory = new EncoderFactory(array(
            'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
        ));

        $encoder = $factory->getEncoder($this->getMock('Symfony\Component\Security\Core\User\UserInterface'));
        $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
        $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));

        $encoder = $factory->getEncoder(new User('user', 'pass'));
        $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
        $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
    }

    public function testGetEncoderWithClassName()
    {
        $factory = new EncoderFactory(array(
            'Symfony\Component\Security\Core\User\UserInterface' => new MessageDigestPasswordEncoder('sha1'),
        ));

        $encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
        $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
        $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
    }

    public function testGetEncoderConfiguredForConcreteClassWithService()
    {
        $factory = new EncoderFactory(array(
            'Symfony\Component\Security\Core\User\User' => new MessageDigestPasswordEncoder('sha1'),
        ));

        $encoder = $factory->getEncoder(new User('user', 'pass'));
        $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
        $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
    }

    public function testGetEncoderConfiguredForConcreteClassWithClassName()
    {
        $factory = new EncoderFactory(array(
            'Symfony\Component\Security\Core\Tests\Encoder\SomeUser' => new MessageDigestPasswordEncoder('sha1'),
        ));

        $encoder = $factory->getEncoder('Symfony\Component\Security\Core\Tests\Encoder\SomeChildUser');
        $expectedEncoder = new MessageDigestPasswordEncoder('sha1');
        $this->assertEquals($expectedEncoder->encodePassword('foo', ''), $encoder->encodePassword('foo', ''));
    }
}

class SomeUser implements UserInterface
{
    public function getRoles() {}
    public function getPassword() {}
    public function getSalt() {}
    public function getUsername() {}
    public function eraseCredentials() {}
}

class SomeChildUser extends SomeUser
{
}
PK21[e5���[Security/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

class MessageDigestPasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
    public function testIsPasswordValid()
    {
        $encoder = new MessageDigestPasswordEncoder('sha256', false, 1);

        $this->assertTrue($encoder->isPasswordValid(hash('sha256', 'password'), 'password', ''));
    }

    public function testEncodePassword()
    {
        $encoder = new MessageDigestPasswordEncoder('sha256', false, 1);
        $this->assertSame(hash('sha256', 'password'), $encoder->encodePassword('password', ''));

        $encoder = new MessageDigestPasswordEncoder('sha256', true, 1);
        $this->assertSame(base64_encode(hash('sha256', 'password', true)), $encoder->encodePassword('password', ''));

        $encoder = new MessageDigestPasswordEncoder('sha256', false, 2);
        $this->assertSame(hash('sha256', hash('sha256', 'password', true).'password'), $encoder->encodePassword('password', ''));
    }

    /**
     * @expectedException \LogicException
     */
    public function testEncodePasswordAlgorithmDoesNotExist()
    {
        $encoder = new MessageDigestPasswordEncoder('foobar');
        $encoder->encodePassword('password', '');
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testEncodePasswordLength()
    {
        $encoder = new MessageDigestPasswordEncoder();

        $encoder->encodePassword(str_repeat('a', 5000), 'salt');
    }

    public function testCheckPasswordLength()
    {
        $encoder = new MessageDigestPasswordEncoder();

        $this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
    }
}
PK21[!�?��	�	TSecurity/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder;

/**
 * @author Elnur Abdurrakhimov <elnur@elnur.pro>
 */
class BCryptPasswordEncoderTest extends \PHPUnit_Framework_TestCase
{
    const PASSWORD = 'password';
    const BYTES = '0123456789abcdef';
    const VALID_COST = '04';

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testCostBelowRange()
    {
        new BCryptPasswordEncoder(3);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testCostAboveRange()
    {
        new BCryptPasswordEncoder(32);
    }

    public function testCostInRange()
    {
        for ($cost = 4; $cost <= 31; $cost++) {
            new BCryptPasswordEncoder($cost);
        }
    }

    public function testResultLength()
    {
        $this->skipIfPhpVersionIsNotSupported();

        $encoder = new BCryptPasswordEncoder(self::VALID_COST);
        $result = $encoder->encodePassword(self::PASSWORD, null);
        $this->assertEquals(60, strlen($result));
    }

    public function testValidation()
    {
        $this->skipIfPhpVersionIsNotSupported();

        $encoder = new BCryptPasswordEncoder(self::VALID_COST);
        $result = $encoder->encodePassword(self::PASSWORD, null);
        $this->assertTrue($encoder->isPasswordValid($result, self::PASSWORD, null));
        $this->assertFalse($encoder->isPasswordValid($result, 'anotherPassword', null));
    }

    private function skipIfPhpVersionIsNotSupported()
    {
        if (version_compare(phpversion(), '5.3.7', '<')) {
            $this->markTestSkipped('Requires PHP >= 5.3.7');
        }
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testEncodePasswordLength()
    {
        $encoder = new BCryptPasswordEncoder(self::VALID_COST);

        $encoder->encodePassword(str_repeat('a', 5000), 'salt');
    }

    public function testCheckPasswordLength()
    {
        $encoder = new BCryptPasswordEncoder(self::VALID_COST);

        $this->assertFalse($encoder->isPasswordValid('encoded', str_repeat('a', 5000), 'salt'));
    }
}
PK21[�����bSecurity/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Validator\Constraints;

use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;

class UserPasswordValidatorTest extends \PHPUnit_Framework_TestCase
{
    const PASSWORD_VALID   = true;
    const PASSWORD_INVALID = false;

    protected $context;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
    }

    protected function tearDown()
    {
        $this->context = null;
    }

    public function testPasswordIsValid()
    {
        $user = $this->createUser();
        $securityContext = $this->createSecurityContext($user);

        $encoder = $this->createPasswordEncoder(static::PASSWORD_VALID);
        $encoderFactory = $this->createEncoderFactory($encoder);

        $validator = new UserPasswordValidator($securityContext, $encoderFactory);
        $validator->initialize($this->context);

        $this
            ->context
            ->expects($this->never())
            ->method('addViolation')
        ;

        $validator->validate('secret', new UserPassword());
    }

    public function testPasswordIsNotValid()
    {
        $user = $this->createUser();
        $securityContext = $this->createSecurityContext($user);

        $encoder = $this->createPasswordEncoder(static::PASSWORD_INVALID);
        $encoderFactory = $this->createEncoderFactory($encoder);

        $validator = new UserPasswordValidator($securityContext, $encoderFactory);
        $validator->initialize($this->context);

        $this
            ->context
            ->expects($this->once())
            ->method('addViolation')
        ;

        $validator->validate('secret', new UserPassword());
    }

    public function testUserIsNotValid()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        $user = $this->getMock('Foo\Bar\User');
        $encoderFactory = $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface');
        $securityContext = $this->createSecurityContext($user);

        $validator = new UserPasswordValidator($securityContext, $encoderFactory);
        $validator->initialize($this->context);
        $validator->validate('secret', new UserPassword());
    }

    protected function createUser()
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');

        $mock
            ->expects($this->once())
            ->method('getPassword')
            ->will($this->returnValue('s3Cr3t'))
        ;

        $mock
            ->expects($this->once())
            ->method('getSalt')
            ->will($this->returnValue('^S4lt$'))
        ;

        return $mock;
    }

    protected function createPasswordEncoder($isPasswordValid = true)
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface');

        $mock
            ->expects($this->once())
            ->method('isPasswordValid')
            ->will($this->returnValue($isPasswordValid))
        ;

        return $mock;
    }

    protected function createEncoderFactory($encoder = null)
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface');

        $mock
            ->expects($this->once())
            ->method('getEncoder')
            ->will($this->returnValue($encoder))
        ;

        return $mock;
    }

    protected function createSecurityContext($user = null)
    {
        $token = $this->createAuthenticationToken($user);

        $mock = $this->getMock('Symfony\Component\Security\Core\SecurityContextInterface');
        $mock
            ->expects($this->once())
            ->method('getToken')
            ->will($this->returnValue($token))
        ;

        return $mock;
    }

    protected function createAuthenticationToken($user = null)
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $mock
            ->expects($this->once())
            ->method('getUser')
            ->will($this->returnValue($user))
        ;

        return $mock;
    }
}
PK21[�KN��HSecurity/Symfony/Component/Security/Core/Tests/Util/SecureRandomTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Util;

use Symfony\Component\Security\Core\Util\SecureRandom;

class SecureRandomTest extends \PHPUnit_Framework_TestCase
{
    /**
     * T1: Monobit test
     *
     * @dataProvider getSecureRandoms
     */
    public function testMonobit($secureRandom)
    {
        $nbOnBits = substr_count($this->getBitSequence($secureRandom, 20000), '1');
        $this->assertTrue($nbOnBits > 9654 && $nbOnBits < 10346, 'Monobit test failed, number of turned on bits: '.$nbOnBits);
    }

    /**
     * T2: Chi-square test with 15 degrees of freedom (chi-Quadrat-Anpassungstest)
     *
     * @dataProvider getSecureRandoms
     */
    public function testPoker($secureRandom)
    {
        $b = $this->getBitSequence($secureRandom, 20000);
        $c = array();
        for ($i = 0; $i <= 15; $i++) {
            $c[$i] = 0;
        }

        for ($j = 1; $j <= 5000; $j++) {
            $k = 4 * $j - 1;
            $c[8 * $b[$k - 3] + 4 * $b[$k - 2] + 2 * $b[$k - 1] + $b[$k]] += 1;
        }

        $f = 0;
        for ($i = 0; $i <= 15; $i++) {
            $f += $c[$i] * $c[$i];
        }

        $Y = 16/5000 * $f - 5000;

        $this->assertTrue($Y > 1.03 && $Y < 57.4, 'Poker test failed, Y = '.$Y);
    }

    /**
     * Run test
     *
     * @dataProvider getSecureRandoms
     */
    public function testRun($secureRandom)
    {
        $b = $this->getBitSequence($secureRandom, 20000);

        $runs = array();
        for ($i = 1; $i <= 6; $i++) {
            $runs[$i] = 0;
        }

        $addRun = function ($run) use (&$runs) {
            if ($run > 6) {
                $run = 6;
            }

            $runs[$run] += 1;
        };

        $currentRun = 0;
        $lastBit = null;
        for ($i = 0; $i < 20000; $i++) {
            if ($lastBit === $b[$i]) {
                $currentRun += 1;
            } else {
                if ($currentRun > 0) {
                    $addRun($currentRun);
                }

                $lastBit = $b[$i];
                $currentRun = 0;
            }
        }
        if ($currentRun > 0) {
            $addRun($currentRun);
        }

        $this->assertTrue($runs[1] > 2267 && $runs[1] < 2733, 'Runs of length 1 outside of defined interval: '.$runs[1]);
        $this->assertTrue($runs[2] > 1079 && $runs[2] < 1421, 'Runs of length 2 outside of defined interval: '.$runs[2]);
        $this->assertTrue($runs[3] > 502 && $runs[3] < 748, 'Runs of length 3 outside of defined interval: '.$runs[3]);
        $this->assertTrue($runs[4] > 233 && $runs[4] < 402, 'Runs of length 4 outside of defined interval: '.$runs[4]);
        $this->assertTrue($runs[5] > 90 && $runs[5] < 223, 'Runs of length 5 outside of defined interval: '.$runs[5]);
        $this->assertTrue($runs[6] > 90 && $runs[6] < 233, 'Runs of length 6 outside of defined interval: '.$runs[6]);
    }

    /**
     * Long-run test
     *
     * @dataProvider getSecureRandoms
     */
    public function testLongRun($secureRandom)
    {
        $b = $this->getBitSequence($secureRandom, 20000);

        $longestRun = $currentRun = 0;
        $lastBit = null;
        for ($i = 0; $i < 20000; $i++) {
            if ($lastBit === $b[$i]) {
                $currentRun += 1;
            } else {
                if ($currentRun > $longestRun) {
                    $longestRun = $currentRun;
                }
                $lastBit = $b[$i];
                $currentRun = 0;
            }
        }
        if ($currentRun > $longestRun) {
            $longestRun = $currentRun;
        }

        $this->assertTrue($longestRun < 34, 'Failed longest run test: '.$longestRun);
    }

    /**
     * Serial Correlation (Autokorrelationstest)
     *
     * @dataProvider getSecureRandoms
     */
    public function testSerialCorrelation($secureRandom)
    {
        $shift = rand(1, 5000);
        $b = $this->getBitSequence($secureRandom, 20000);

        $Z = 0;
        for ($i = 0; $i < 5000; $i++) {
            $Z += $b[$i] === $b[$i + $shift] ? 1 : 0;
        }

        $this->assertTrue($Z > 2326 && $Z < 2674, 'Failed serial correlation test: '.$Z);
    }

    public function getSecureRandoms()
    {
        $secureRandoms = array();

        // only add if openssl is indeed present
        $secureRandom = new SecureRandom();
        if ($this->hasOpenSsl($secureRandom)) {
            $secureRandoms[] = array($secureRandom);
        }

        // no-openssl with custom seed provider
        $secureRandom = new SecureRandom(sys_get_temp_dir().'/_sf2.seed');
        $this->disableOpenSsl($secureRandom);
        $secureRandoms[] = array($secureRandom);

        return $secureRandoms;
    }

    protected function disableOpenSsl($secureRandom)
    {
        $ref = new \ReflectionProperty($secureRandom, 'useOpenSsl');
        $ref->setAccessible(true);
        $ref->setValue($secureRandom, false);
        $ref->setAccessible(false);
    }

    protected function hasOpenSsl($secureRandom)
    {
        $ref = new \ReflectionProperty($secureRandom, 'useOpenSsl');
        $ref->setAccessible(true);

        $ret = $ref->getValue($secureRandom);

        $ref->setAccessible(false);

        return $ret;
    }

    private function getBitSequence($secureRandom, $length)
    {
        $bitSequence = '';
        for ($i = 0; $i < $length; $i += 40) {
            $value = unpack('H*', $secureRandom->nextBytes(5));
            $value = str_pad(base_convert($value[1], 16, 2), 40, '0', STR_PAD_LEFT);
            $bitSequence .= $value;
        }

        return substr($bitSequence, 0, $length);
    }
}
PK21[n�;�SSGSecurity/Symfony/Component/Security/Core/Tests/Util/StringUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Util;

use Symfony\Component\Security\Core\Util\StringUtils;

class StringUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function testEquals()
    {
        $this->assertTrue(StringUtils::equals('password', 'password'));
        $this->assertFalse(StringUtils::equals('password', 'foo'));
    }
}
PK21[�����FSecurity/Symfony/Component/Security/Core/Tests/Util/ClassUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Util
{
    use Symfony\Component\Security\Core\Util\ClassUtils;

    class ClassUtilsTest extends \PHPUnit_Framework_TestCase
    {
        public static function dataGetClass()
        {
            return array(
                array('stdClass', 'stdClass'),
                array('Symfony\Component\Security\Core\Util\ClassUtils', 'Symfony\Component\Security\Core\Util\ClassUtils'),
                array('MyProject\Proxies\__CG__\stdClass', 'stdClass'),
                array('MyProject\Proxies\__CG__\OtherProject\Proxies\__CG__\stdClass', 'stdClass'),
                array('MyProject\Proxies\__CG__\Symfony\Component\Security\Core\Tests\Util\ChildObject', 'Symfony\Component\Security\Core\Tests\Util\ChildObject'),
                array(new TestObject(), 'Symfony\Component\Security\Core\Tests\Util\TestObject'),
                array(new \Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Core\Tests\Util\TestObject(), 'Symfony\Component\Security\Core\Tests\Util\TestObject'),
            );
        }

        /**
         * @dataProvider dataGetClass
         */
        public function testGetRealClass($object, $expectedClassName)
        {
            $this->assertEquals($expectedClassName, ClassUtils::getRealClass($object));
        }
    }

    class TestObject
    {
    }
}

namespace Acme\DemoBundle\Proxy\__CG__\Symfony\Component\Security\Core\Tests\Util
{
    class TestObject extends \Symfony\Component\Security\Core\Tests\Util\TestObject
    {
    }
}
PK21[I-���ZSecurity/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization;

use Symfony\Component\Security\Core\Authorization\AccessDecisionManager;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

class AccessDecisionManagerTest extends \PHPUnit_Framework_TestCase
{
    public function testSupportsClass()
    {
        $manager = new AccessDecisionManager(array(
            $this->getVoterSupportsClass(true),
            $this->getVoterSupportsClass(false),
        ));
        $this->assertTrue($manager->supportsClass('FooClass'));

        $manager = new AccessDecisionManager(array(
            $this->getVoterSupportsClass(false),
            $this->getVoterSupportsClass(false),
        ));
        $this->assertFalse($manager->supportsClass('FooClass'));
    }

    public function testSupportsAttribute()
    {
        $manager = new AccessDecisionManager(array(
            $this->getVoterSupportsAttribute(true),
            $this->getVoterSupportsAttribute(false),
        ));
        $this->assertTrue($manager->supportsAttribute('foo'));

        $manager = new AccessDecisionManager(array(
            $this->getVoterSupportsAttribute(false),
            $this->getVoterSupportsAttribute(false),
        ));
        $this->assertFalse($manager->supportsAttribute('foo'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetVotersEmpty()
    {
        $manager = new AccessDecisionManager(array());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetUnsupportedStrategy()
    {
        new AccessDecisionManager(array($this->getVoter(VoterInterface::ACCESS_GRANTED)), 'fooBar');
    }

    /**
     * @dataProvider getStrategyTests
     */
    public function testStrategies($strategy, $voters, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions, $expected)
    {
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $manager = new AccessDecisionManager($voters, $strategy, $allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions);

        $this->assertSame($expected, $manager->decide($token, array('ROLE_FOO')));
    }

    public function getStrategyTests()
    {
        return array(
            // affirmative
            array('affirmative', $this->getVoters(1, 0, 0), false, true, true),
            array('affirmative', $this->getVoters(1, 2, 0), false, true, true),
            array('affirmative', $this->getVoters(0, 1, 0), false, true, false),
            array('affirmative', $this->getVoters(0, 0, 1), false, true, false),
            array('affirmative', $this->getVoters(0, 0, 1), true, true, true),

            // consensus
            array('consensus', $this->getVoters(1, 0, 0), false, true, true),
            array('consensus', $this->getVoters(1, 2, 0), false, true, false),
            array('consensus', $this->getVoters(2, 1, 0), false, true, true),

            array('consensus', $this->getVoters(0, 0, 1), false, true, false),

            array('consensus', $this->getVoters(0, 0, 1), true, true, true),

            array('consensus', $this->getVoters(2, 2, 0), false, true, true),
            array('consensus', $this->getVoters(2, 2, 1), false, true, true),

            array('consensus', $this->getVoters(2, 2, 0), false, false, false),
            array('consensus', $this->getVoters(2, 2, 1), false, false, false),

            // unanimous
            array('unanimous', $this->getVoters(1, 0, 0), false, true, true),
            array('unanimous', $this->getVoters(1, 0, 1), false, true, true),
            array('unanimous', $this->getVoters(1, 1, 0), false, true, false),

            array('unanimous', $this->getVoters(0, 0, 2), false, true, false),
            array('unanimous', $this->getVoters(0, 0, 2), true, true, true),
        );
    }

    protected function getVoters($grants, $denies, $abstains)
    {
        $voters = array();
        for ($i = 0; $i < $grants; $i++) {
            $voters[] = $this->getVoter(VoterInterface::ACCESS_GRANTED);
        }
        for ($i = 0; $i < $denies; $i++) {
            $voters[] = $this->getVoter(VoterInterface::ACCESS_DENIED);
        }
        for ($i = 0; $i < $abstains; $i++) {
            $voters[] = $this->getVoter(VoterInterface::ACCESS_ABSTAIN);
        }

        return $voters;
    }

    protected function getVoter($vote)
    {
        $voter = $this->getMock('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface');
        $voter->expects($this->any())
              ->method('vote')
              ->will($this->returnValue($vote));
        ;

        return $voter;
    }

    protected function getVoterSupportsClass($ret)
    {
        $voter = $this->getMock('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface');
        $voter->expects($this->any())
              ->method('supportsClass')
              ->will($this->returnValue($ret));
        ;

        return $voter;
    }

    protected function getVoterSupportsAttribute($ret)
    {
        $voter = $this->getMock('Symfony\Component\Security\Core\Authorization\Voter\VoterInterface');
        $voter->expects($this->any())
              ->method('supportsAttribute')
              ->will($this->returnValue($ret));
        ;

        return $voter;
    }
}
PK21[�bdw�
�
WSecurity/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization;

use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\User\User;

class ExpressionLanguageTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     */
    public function testIsAuthenticated($token, $expression, $result, array $roles = array())
    {
        $anonymousTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken';
        $rememberMeTokenClass = 'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken';
        $expressionLanguage = new ExpressionLanguage();
        $trustResolver = new AuthenticationTrustResolver($anonymousTokenClass, $rememberMeTokenClass);

        $context = array();
        $context['trust_resolver'] = $trustResolver;
        $context['token'] = $token;
        $context['roles'] = $roles;

        $this->assertEquals($result, $expressionLanguage->evaluate($expression, $context));
    }

    public function provider()
    {
        $roles = array('ROLE_USER', 'ROLE_ADMIN');
        $user = new User('username', 'password', $roles);

        $noToken = null;
        $anonymousToken = new AnonymousToken('firewall', 'anon.');
        $rememberMeToken = new RememberMeToken($user, 'providerkey', 'firewall');
        $usernamePasswordToken = new UsernamePasswordToken('username', 'password', 'providerkey', $roles);

        return array(
            array($noToken, 'is_anonymous()', false),
            array($noToken, 'is_authenticated()', false),
            array($noToken, 'is_fully_authenticated()', false),
            array($noToken, 'is_remember_me()', false),
            array($noToken, "has_role('ROLE_USER')", false),

            array($anonymousToken, 'is_anonymous()', true),
            array($anonymousToken, 'is_authenticated()', false),
            array($anonymousToken, 'is_fully_authenticated()', false),
            array($anonymousToken, 'is_remember_me()', false),
            array($anonymousToken, "has_role('ROLE_USER')", false),

            array($rememberMeToken, 'is_anonymous()', false),
            array($rememberMeToken, 'is_authenticated()', true),
            array($rememberMeToken, 'is_fully_authenticated()', false),
            array($rememberMeToken, 'is_remember_me()', true),
            array($rememberMeToken, "has_role('ROLE_FOO')", false, $roles),
            array($rememberMeToken, "has_role('ROLE_USER')", true, $roles),

            array($usernamePasswordToken, 'is_anonymous()', false),
            array($usernamePasswordToken, 'is_authenticated()', true),
            array($usernamePasswordToken, 'is_fully_authenticated()', true),
            array($usernamePasswordToken, 'is_remember_me()', false),
            array($usernamePasswordToken, "has_role('ROLE_FOO')", false, $roles),
            array($usernamePasswordToken, "has_role('ROLE_USER')", true, $roles),
        );
    }
}
PK21[�Ƕ'�
�
ZSecurity/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;

class ExpressionVoterTest extends \PHPUnit_Framework_TestCase
{
    public function testSupportsAttribute()
    {
        $expression = $this->createExpression();
        $expressionLanguage = $this->getMock('Symfony\Component\Security\Core\Authorization\ExpressionLanguage');
        $voter = new ExpressionVoter($expressionLanguage, $this->createTrustResolver(), $this->createRoleHierarchy());

        $this->assertTrue($voter->supportsAttribute($expression));
    }

    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected, $tokenExpectsGetRoles = true, $expressionLanguageExpectsEvaluate = true)
    {
        $voter = new ExpressionVoter($this->createExpressionLanguage($expressionLanguageExpectsEvaluate), $this->createTrustResolver());

        $this->assertSame($expected, $voter->vote($this->getToken($roles, $tokenExpectsGetRoles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array(
            array(array(), array(), VoterInterface::ACCESS_ABSTAIN, false, false),
            array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN, false, false),

            array(array(), array($this->createExpression()), VoterInterface::ACCESS_DENIED, true, false),

            array(array('ROLE_FOO'), array($this->createExpression(), $this->createExpression()), VoterInterface::ACCESS_GRANTED),
            array(array('ROLE_BAR', 'ROLE_FOO'), array($this->createExpression()), VoterInterface::ACCESS_GRANTED),
        );
    }

    protected function getToken(array $roles, $tokenExpectsGetRoles = true)
    {
        foreach ($roles as $i => $role) {
            $roles[$i] = new Role($role);
        }
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');

        if ($tokenExpectsGetRoles) {
            $token->expects($this->once())
                ->method('getRoles')
                ->will($this->returnValue($roles));
        }

        return $token;
    }

    protected function createExpressionLanguage($expressionLanguageExpectsEvaluate = true)
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\Authorization\ExpressionLanguage');

        if ($expressionLanguageExpectsEvaluate) {
            $mock->expects($this->once())
                ->method('evaluate')
                ->will($this->returnValue(true));
        }

        return $mock;
    }

    protected function createTrustResolver()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface');
    }

    protected function createRoleHierarchy()
    {
        return $this->getMock('Symfony\Component\Security\Core\Role\RoleHierarchyInterface');
    }

    protected function createExpression()
    {
        return $this->getMockBuilder('Symfony\Component\ExpressionLanguage\Expression')
            ->disableOriginalConstructor()
            ->getMock();
    }
}
PK21[jq�o��TSecurity/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\Role;

class RoleVoterTest extends \PHPUnit_Framework_TestCase
{
    public function testSupportsClass()
    {
        $voter = new RoleVoter();

        $this->assertTrue($voter->supportsClass('Foo'));
    }

    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleVoter();

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array(
            array(array(), array(), VoterInterface::ACCESS_ABSTAIN),
            array(array(), array('FOO'), VoterInterface::ACCESS_ABSTAIN),
            array(array(), array('ROLE_FOO'), VoterInterface::ACCESS_DENIED),
            array(array('ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
            array(array('ROLE_FOO'), array('FOO', 'ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
            array(array('ROLE_BAR', 'ROLE_FOO'), array('ROLE_FOO'), VoterInterface::ACCESS_GRANTED),
        );
    }

    protected function getToken(array $roles)
    {
        foreach ($roles as $i => $role) {
            $roles[$i] = new Role($role);
        }
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $token->expects($this->once())
              ->method('getRoles')
              ->will($this->returnValue($roles));
        ;

        return $token;
    }
}
PK21[�R�MM]Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleHierarchyVoterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authorization\Voter\RoleHierarchyVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchy;

class RoleHierarchyVoterTest extends RoleVoterTest
{
    /**
     * @dataProvider getVoteTests
     */
    public function testVote($roles, $attributes, $expected)
    {
        $voter = new RoleHierarchyVoter(new RoleHierarchy(array('ROLE_FOO' => array('ROLE_FOOBAR'))));

        $this->assertSame($expected, $voter->vote($this->getToken($roles), null, $attributes));
    }

    public function getVoteTests()
    {
        return array_merge(parent::getVoteTests(), array(
            array(array('ROLE_FOO'), array('ROLE_FOOBAR'), VoterInterface::ACCESS_GRANTED),
        ));
    }
}
PK21[��� ,
,
]Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authorization\Voter;

use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;

class AuthenticatedVoterTest extends \PHPUnit_Framework_TestCase
{
    public function testSupportsClass()
    {
        $voter = new AuthenticatedVoter($this->getResolver());
        $this->assertTrue($voter->supportsClass('stdClass'));
    }

    /**
     * @dataProvider getVoteTests
     */
    public function testVote($authenticated, $attributes, $expected)
    {
        $voter = new AuthenticatedVoter($this->getResolver());

        $this->assertSame($expected, $voter->vote($this->getToken($authenticated), null, $attributes));
    }

    public function getVoteTests()
    {
        return array(
            array('fully', array(), VoterInterface::ACCESS_ABSTAIN),
            array('fully', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
            array('remembered', array(), VoterInterface::ACCESS_ABSTAIN),
            array('remembered', array('FOO'), VoterInterface::ACCESS_ABSTAIN),
            array('anonymously', array(), VoterInterface::ACCESS_ABSTAIN),
            array('anonymously', array('FOO'), VoterInterface::ACCESS_ABSTAIN),

            array('fully', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
            array('remembered', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),
            array('anonymously', array('IS_AUTHENTICATED_ANONYMOUSLY'), VoterInterface::ACCESS_GRANTED),

            array('fully', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
            array('remembered', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_GRANTED),
            array('anonymously', array('IS_AUTHENTICATED_REMEMBERED'), VoterInterface::ACCESS_DENIED),

            array('fully', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_GRANTED),
            array('remembered', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
            array('anonymously', array('IS_AUTHENTICATED_FULLY'), VoterInterface::ACCESS_DENIED),
        );
    }

    protected function getResolver()
    {
        return new AuthenticationTrustResolver(
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken',
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'
        );
    }

    protected function getToken($authenticated)
    {
        if ('fully' === $authenticated) {
            return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        } elseif ('remembered' === $authenticated) {
            return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('setPersistent'), array(), '', false);
        } else {
            return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken', null, array('', ''));
        }
    }
}
PK21[LS�(��@Security/Symfony/Component/Security/Core/Tests/User/UserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\User;

use Symfony\Component\Security\Core\User\User;

class UserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\Security\Core\User\User::__construct
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorException()
    {
        new User('', 'superpass');
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::__construct
     * @covers Symfony\Component\Security\Core\User\User::getRoles
     */
    public function testGetRoles()
    {
        $user = new User('fabien', 'superpass');
        $this->assertEquals(array(), $user->getRoles());

        $user = new User('fabien', 'superpass', array('ROLE_ADMIN'));
        $this->assertEquals(array('ROLE_ADMIN'), $user->getRoles());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::__construct
     * @covers Symfony\Component\Security\Core\User\User::getPassword
     */
    public function testGetPassword()
    {
        $user = new User('fabien', 'superpass');
        $this->assertEquals('superpass', $user->getPassword());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::__construct
     * @covers Symfony\Component\Security\Core\User\User::getUsername
     */
    public function testGetUsername()
    {
        $user = new User('fabien', 'superpass');
        $this->assertEquals('fabien', $user->getUsername());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::getSalt
     */
    public function testGetSalt()
    {
        $user = new User('fabien', 'superpass');
        $this->assertEquals('', $user->getSalt());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::isAccountNonExpired
     */
    public function testIsAccountNonExpired()
    {
        $user = new User('fabien', 'superpass');
        $this->assertTrue($user->isAccountNonExpired());

        $user = new User('fabien', 'superpass', array(), true, false);
        $this->assertFalse($user->isAccountNonExpired());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::isCredentialsNonExpired
     */
    public function testIsCredentialsNonExpired()
    {
        $user = new User('fabien', 'superpass');
        $this->assertTrue($user->isCredentialsNonExpired());

        $user = new User('fabien', 'superpass', array(), true, true, false);
        $this->assertFalse($user->isCredentialsNonExpired());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::isAccountNonLocked
     */
    public function testIsAccountNonLocked()
    {
        $user = new User('fabien', 'superpass');
        $this->assertTrue($user->isAccountNonLocked());

        $user = new User('fabien', 'superpass', array(), true, true, true, false);
        $this->assertFalse($user->isAccountNonLocked());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::isEnabled
     */
    public function testIsEnabled()
    {
        $user = new User('fabien', 'superpass');
        $this->assertTrue($user->isEnabled());

        $user = new User('fabien', 'superpass', array(), false);
        $this->assertFalse($user->isEnabled());
    }

    /**
     * @covers Symfony\Component\Security\Core\User\User::eraseCredentials
     */
    public function testEraseCredentials()
    {
        $user = new User('fabien', 'superpass');
        $user->eraseCredentials();
        $this->assertEquals('superpass', $user->getPassword());
    }
}
PK21[��qMSecurity/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\User;

use Symfony\Component\Security\Core\Exception\UnsupportedUserException;

use Symfony\Component\Security\Core\User\ChainUserProvider;

use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;

class ChainUserProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadUserByUsername()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foo'))
            ->will($this->throwException(new UsernameNotFoundException('not found')))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue($account = $this->getAccount()))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $this->assertSame($account, $provider->loadUserByUsername('foo'));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
     */
    public function testLoadUserByUsernameThrowsUsernameNotFoundException()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foo'))
            ->will($this->throwException(new UsernameNotFoundException('not found')))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('loadUserByUsername')
            ->with($this->equalTo('foo'))
            ->will($this->throwException(new UsernameNotFoundException('not found')))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $provider->loadUserByUsername('foo');
    }

    public function testRefreshUser()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->throwException(new UnsupportedUserException('unsupported')))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->returnValue($account = $this->getAccount()))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $this->assertSame($account, $provider->refreshUser($this->getAccount()));
    }

    public function testRefreshUserAgain()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->throwException(new UsernameNotFoundException('not found')))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->returnValue($account = $this->getAccount()))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $this->assertSame($account, $provider->refreshUser($this->getAccount()));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\UnsupportedUserException
     */
    public function testRefreshUserThrowsUnsupportedUserException()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->throwException(new UnsupportedUserException('unsupported')))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('refreshUser')
            ->will($this->throwException(new UnsupportedUserException('unsupported')))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $provider->refreshUser($this->getAccount());
    }

    public function testSupportsClass()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('supportsClass')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue(false))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('supportsClass')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue(true))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $this->assertTrue($provider->supportsClass('foo'));
    }

    public function testSupportsClassWhenNotSupported()
    {
        $provider1 = $this->getProvider();
        $provider1
            ->expects($this->once())
            ->method('supportsClass')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue(false))
        ;

        $provider2 = $this->getProvider();
        $provider2
            ->expects($this->once())
            ->method('supportsClass')
            ->with($this->equalTo('foo'))
            ->will($this->returnValue(false))
        ;

        $provider = new ChainUserProvider(array($provider1, $provider2));
        $this->assertFalse($provider->supportsClass('foo'));
    }

    protected function getAccount()
    {
        return $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
    }

    protected function getProvider()
    {
        return $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
    }
}
PK21[�$��nSecurity/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\AnonymousAuthenticationProvider;

class AnonymousAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $provider = $this->getProvider('foo');

        $this->assertTrue($provider->supports($this->getSupportedToken('foo')));
        $this->assertFalse($provider->supports($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    public function testAuthenticateWhenTokenIsNotSupported()
    {
        $provider = $this->getProvider('foo');

        $this->assertNull($provider->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testAuthenticateWhenKeyIsNotValid()
    {
        $provider = $this->getProvider('foo');

        $this->assertNull($provider->authenticate($this->getSupportedToken('bar')));
    }

    public function testAuthenticate()
    {
        $provider = $this->getProvider('foo');
        $token = $this->getSupportedToken('foo');

        $this->assertSame($token, $provider->authenticate($token));
    }

    protected function getSupportedToken($key)
    {
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken', array('getKey'), array(), '', false);
        $token->expects($this->any())
              ->method('getKey')
              ->will($this->returnValue($key))
        ;

        return $token;
    }

    protected function getProvider($key)
    {
        return new AnonymousAuthenticationProvider($key);
    }
}
PK21[P��[.[.hSecurity/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;

use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;

use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;

class DaoAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
     */
    public function testRetrieveUserWhenProviderDoesNotReturnAnUserInterface()
    {
        $provider = $this->getProvider('fabien');
        $method = new \ReflectionMethod($provider, 'retrieveUser');
        $method->setAccessible(true);

        $method->invoke($provider, 'fabien', $this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
     */
    public function testRetrieveUserWhenUsernameIsNotFound()
    {
        $userProvider = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface');
        $userProvider->expects($this->once())
                     ->method('loadUserByUsername')
                     ->will($this->throwException($this->getMock('Symfony\\Component\\Security\\Core\\Exception\\UsernameNotFoundException', null, array(), '', false)))
        ;

        $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface'), 'key', $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface'));
        $method = new \ReflectionMethod($provider, 'retrieveUser');
        $method->setAccessible(true);

        $method->invoke($provider, 'fabien', $this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
     */
    public function testRetrieveUserWhenAnExceptionOccurs()
    {
        $userProvider = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface');
        $userProvider->expects($this->once())
                     ->method('loadUserByUsername')
                     ->will($this->throwException($this->getMock('RuntimeException', null, array(), '', false)))
        ;

        $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface'), 'key', $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface'));
        $method = new \ReflectionMethod($provider, 'retrieveUser');
        $method->setAccessible(true);

        $method->invoke($provider, 'fabien', $this->getSupportedToken());
    }

    public function testRetrieveUserReturnsUserFromTokenOnReauthentication()
    {
        $userProvider = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface');
        $userProvider->expects($this->never())
                     ->method('loadUserByUsername')
        ;

        $user = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');
        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getUser')
              ->will($this->returnValue($user))
        ;

        $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface'), 'key', $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface'));
        $reflection = new \ReflectionMethod($provider, 'retrieveUser');
        $reflection->setAccessible(true);
        $result = $reflection->invoke($provider, null, $token);

        $this->assertSame($user, $result);
    }

    public function testRetrieveUser()
    {
        $user = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');

        $userProvider = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface');
        $userProvider->expects($this->once())
                     ->method('loadUserByUsername')
                     ->will($this->returnValue($user))
        ;

        $provider = new DaoAuthenticationProvider($userProvider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface'), 'key', $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface'));
        $method = new \ReflectionMethod($provider, 'retrieveUser');
        $method->setAccessible(true);

        $this->assertSame($user, $method->invoke($provider, 'fabien', $this->getSupportedToken()));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testCheckAuthenticationWhenCredentialsAreEmpty()
    {
        $encoder = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface');
        $encoder
            ->expects($this->never())
            ->method('isPasswordValid')
        ;

        $provider = $this->getProvider(null, null, $encoder);
        $method = new \ReflectionMethod($provider, 'checkAuthentication');
        $method->setAccessible(true);

        $token = $this->getSupportedToken();
        $token
            ->expects($this->once())
            ->method('getCredentials')
            ->will($this->returnValue(''))
        ;

        $method->invoke(
            $provider,
            $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface'),
            $token
        );
    }

    public function testCheckAuthenticationWhenCredentialsAre0()
    {
        $encoder = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface');
        $encoder
            ->expects($this->once())
            ->method('isPasswordValid')
            ->will($this->returnValue(true))
        ;

        $provider = $this->getProvider(null, null, $encoder);
        $method = new \ReflectionMethod($provider, 'checkAuthentication');
        $method->setAccessible(true);

        $token = $this->getSupportedToken();
        $token
            ->expects($this->once())
            ->method('getCredentials')
            ->will($this->returnValue('0'))
        ;

        $method->invoke(
            $provider,
            $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface'),
            $token
        );
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testCheckAuthenticationWhenCredentialsAreNotValid()
    {
        $encoder = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface');
        $encoder->expects($this->once())
                ->method('isPasswordValid')
                ->will($this->returnValue(false))
        ;

        $provider = $this->getProvider(null, null, $encoder);
        $method = new \ReflectionMethod($provider, 'checkAuthentication');
        $method->setAccessible(true);

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getCredentials')
              ->will($this->returnValue('foo'))
        ;

        $method->invoke($provider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface'), $token);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testCheckAuthenticationDoesNotReauthenticateWhenPasswordHasChanged()
    {
        $user = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');
        $user->expects($this->once())
             ->method('getPassword')
             ->will($this->returnValue('foo'))
        ;

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getUser')
              ->will($this->returnValue($user));

        $dbUser = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');
        $dbUser->expects($this->once())
               ->method('getPassword')
               ->will($this->returnValue('newFoo'))
        ;

        $provider = $this->getProvider();
        $reflection = new \ReflectionMethod($provider, 'checkAuthentication');
        $reflection->setAccessible(true);
        $reflection->invoke($provider, $dbUser, $token);
    }

    public function testCheckAuthenticationWhenTokenNeedsReauthenticationWorksWithoutOriginalCredentials()
    {
        $user = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');
        $user->expects($this->once())
             ->method('getPassword')
             ->will($this->returnValue('foo'))
        ;

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getUser')
              ->will($this->returnValue($user));

        $dbUser = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface');
        $dbUser->expects($this->once())
               ->method('getPassword')
               ->will($this->returnValue('foo'))
        ;

        $provider = $this->getProvider();
        $reflection = new \ReflectionMethod($provider, 'checkAuthentication');
        $reflection->setAccessible(true);
        $reflection->invoke($provider, $dbUser, $token);
    }

    public function testCheckAuthentication()
    {
        $encoder = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\PasswordEncoderInterface');
        $encoder->expects($this->once())
                ->method('isPasswordValid')
                ->will($this->returnValue(true))
        ;

        $provider = $this->getProvider(null, null, $encoder);
        $method = new \ReflectionMethod($provider, 'checkAuthentication');
        $method->setAccessible(true);

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getCredentials')
              ->will($this->returnValue('foo'))
        ;

        $method->invoke($provider, $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserInterface'), $token);
    }

    protected function getSupportedToken()
    {
        $mock = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken', array('getCredentials', 'getUser', 'getProviderKey'), array(), '', false);
        $mock
            ->expects($this->any())
            ->method('getProviderKey')
            ->will($this->returnValue('key'))
        ;

        return $mock;
    }

    protected function getProvider($user = null, $userChecker = null, $passwordEncoder = null)
    {
        $userProvider = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface');
        if (null !== $user) {
            $userProvider->expects($this->once())
                         ->method('loadUserByUsername')
                         ->will($this->returnValue($user))
            ;
        }

        if (null === $userChecker) {
            $userChecker = $this->getMock('Symfony\\Component\\Security\\Core\\User\\UserCheckerInterface');
        }

        if (null === $passwordEncoder) {
            $passwordEncoder = new PlaintextPasswordEncoder();
        }

        $encoderFactory = $this->getMock('Symfony\\Component\\Security\\Core\\Encoder\\EncoderFactoryInterface');
        $encoderFactory
            ->expects($this->any())
            ->method('getEncoder')
            ->will($this->returnValue($passwordEncoder))
        ;

        return new DaoAuthenticationProvider($userProvider, $userChecker, 'key', $encoderFactory);
    }
}
PK21[ו�Gi&i&iSecurity/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

class UserAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $provider = $this->getProvider();

        $this->assertTrue($provider->supports($this->getSupportedToken()));
        $this->assertFalse($provider->supports($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    public function testAuthenticateWhenTokenIsNotSupported()
    {
        $provider = $this->getProvider();

        $this->assertNull($provider->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\UsernameNotFoundException
     */
    public function testAuthenticateWhenUsernameIsNotFound()
    {
        $provider = $this->getProvider(false, false);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\UsernameNotFoundException', null, array(), '', false)))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testAuthenticateWhenUsernameIsNotFoundAndHideIsTrue()
    {
        $provider = $this->getProvider(false, true);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\UsernameNotFoundException', null, array(), '', false)))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationServiceException
     */
    public function testAuthenticateWhenProviderDoesNotReturnAnUserInterface()
    {
        $provider = $this->getProvider(false, true);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue(null))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\CredentialsExpiredException
     */
    public function testAuthenticateWhenPreChecksFails()
    {
        $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        $userChecker->expects($this->once())
                    ->method('checkPreAuth')
                    ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\CredentialsExpiredException', null, array(), '', false)))
        ;

        $provider = $this->getProvider($userChecker);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface')))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
     */
    public function testAuthenticateWhenPostChecksFails()
    {
        $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        $userChecker->expects($this->once())
                    ->method('checkPostAuth')
                    ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\AccountExpiredException', null, array(), '', false)))
        ;

        $provider = $this->getProvider($userChecker);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface')))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     * @expectedExceptionMessage Bad credentials
     */
    public function testAuthenticateWhenPostCheckAuthenticationFails()
    {
        $provider = $this->getProvider();
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface')))
        ;
        $provider->expects($this->once())
                 ->method('checkAuthentication')
                 ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\BadCredentialsException', null, array(), '', false)))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     * @expectedExceptionMessage Foo
     */
    public function testAuthenticateWhenPostCheckAuthenticationFailsWithHideFalse()
    {
        $provider = $this->getProvider(false, false);
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($this->getMock('Symfony\Component\Security\Core\User\UserInterface')))
        ;
        $provider->expects($this->once())
                 ->method('checkAuthentication')
                 ->will($this->throwException(new BadCredentialsException('Foo')))
        ;

        $provider->authenticate($this->getSupportedToken());
    }

    public function testAuthenticate()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->once())
             ->method('getRoles')
             ->will($this->returnValue(array('ROLE_FOO')))
        ;

        $provider = $this->getProvider();
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($user))
        ;

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getCredentials')
              ->will($this->returnValue('foo'))
        ;

        $token->expects($this->once())
              ->method('getRoles')
              ->will($this->returnValue(array()))
        ;

        $authToken = $provider->authenticate($token);

        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
        $this->assertSame($user, $authToken->getUser());
        $this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
        $this->assertEquals('foo', $authToken->getCredentials());
        $this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
    }

    public function testAuthenticateWithPreservingRoleSwitchUserRole()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->once())
             ->method('getRoles')
             ->will($this->returnValue(array('ROLE_FOO')))
        ;

        $provider = $this->getProvider();
        $provider->expects($this->once())
                 ->method('retrieveUser')
                 ->will($this->returnValue($user))
        ;

        $token = $this->getSupportedToken();
        $token->expects($this->once())
              ->method('getCredentials')
              ->will($this->returnValue('foo'))
        ;

        $switchUserRole = new SwitchUserRole('foo', $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $token->expects($this->once())
              ->method('getRoles')
              ->will($this->returnValue(array($switchUserRole)))
        ;

        $authToken = $provider->authenticate($token);

        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $authToken);
        $this->assertSame($user, $authToken->getUser());
        $this->assertContains(new Role('ROLE_FOO'), $authToken->getRoles(), '', false, false);
        $this->assertContains($switchUserRole, $authToken->getRoles());
        $this->assertEquals('foo', $authToken->getCredentials());
        $this->assertEquals(array('foo' => 'bar'), $authToken->getAttributes(), '->authenticate() copies token attributes');
    }

    protected function getSupportedToken()
    {
        $mock = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', array('getCredentials', 'getProviderKey', 'getRoles'), array(), '', false);
        $mock
            ->expects($this->any())
            ->method('getProviderKey')
            ->will($this->returnValue('key'))
        ;

        $mock->setAttributes(array('foo' => 'bar'));

        return $mock;
    }

    protected function getProvider($userChecker = false, $hide = true)
    {
        if (false === $userChecker) {
            $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        }

        return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider', array($userChecker, 'key', $hide));
    }
}
PK21[�75ttoSecurity/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\RememberMeAuthenticationProvider;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Role\Role;

class RememberMeAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $provider = $this->getProvider();

        $this->assertTrue($provider->supports($this->getSupportedToken()));
        $this->assertFalse($provider->supports($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    public function testAuthenticateWhenTokenIsNotSupported()
    {
        $provider = $this->getProvider();

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
        $this->assertNull($provider->authenticate($token));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testAuthenticateWhenKeysDoNotMatch()
    {
        $provider = $this->getProvider(null, 'key1');
        $token = $this->getSupportedToken(null, 'key2');

        $provider->authenticate($token);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\AccountExpiredException
     */
    public function testAuthenticateWhenPostChecksFails()
    {
        $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        $userChecker->expects($this->once())
                    ->method('checkPostAuth')
                    ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\AccountExpiredException', null, array(), '', false)))
        ;

        $provider = $this->getProvider($userChecker);

        $provider->authenticate($this->getSupportedToken());
    }

    public function testAuthenticate()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->exactly(2))
             ->method('getRoles')
             ->will($this->returnValue(array('ROLE_FOO')))
        ;

        $provider = $this->getProvider();

        $token = $this->getSupportedToken($user);
        $authToken = $provider->authenticate($token);

        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $authToken);
        $this->assertSame($user, $authToken->getUser());
        $this->assertEquals(array(new Role('ROLE_FOO')), $authToken->getRoles());
        $this->assertEquals('', $authToken->getCredentials());
    }

    protected function getSupportedToken($user = null, $key = 'test')
    {
        if (null === $user) {
            $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
            $user
                ->expects($this->any())
                ->method('getRoles')
                ->will($this->returnValue(array()))
            ;
        }

        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('getProviderKey'), array($user, 'foo', $key));
        $token
            ->expects($this->once())
            ->method('getProviderKey')
            ->will($this->returnValue('foo'))
        ;

        return $token;
    }

    protected function getProvider($userChecker = null, $key = 'test')
    {
        if (null === $userChecker) {
            $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        }

        return new RememberMeAuthenticationProvider($userChecker, $key, 'foo');
    }
}
PK21[���ZZuSecurity/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Provider;

use Symfony\Component\Security\Core\Authentication\Provider\PreAuthenticatedAuthenticationProvider;

class PreAuthenticatedAuthenticationProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testSupports()
    {
        $provider = $this->getProvider();

        $this->assertTrue($provider->supports($this->getSupportedToken()));
        $this->assertFalse($provider->supports($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));

        $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken')
                    ->disableOriginalConstructor()
                    ->getMock()
        ;
        $token
            ->expects($this->once())
            ->method('getProviderKey')
            ->will($this->returnValue('foo'))
        ;
        $this->assertFalse($provider->supports($token));
    }

    public function testAuthenticateWhenTokenIsNotSupported()
    {
        $provider = $this->getProvider();

        $this->assertNull($provider->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')));
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
     */
    public function testAuthenticateWhenNoUserIsSet()
    {
        $provider = $this->getProvider();
        $provider->authenticate($this->getSupportedToken(''));
    }

    public function testAuthenticate()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user
            ->expects($this->once())
            ->method('getRoles')
            ->will($this->returnValue(array()))
        ;
        $provider = $this->getProvider($user);

        $token = $provider->authenticate($this->getSupportedToken('fabien', 'pass'));
        $this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken', $token);
        $this->assertEquals('pass', $token->getCredentials());
        $this->assertEquals('key', $token->getProviderKey());
        $this->assertEquals(array(), $token->getRoles());
        $this->assertEquals(array('foo' => 'bar'), $token->getAttributes(), '->authenticate() copies token attributes');
        $this->assertSame($user, $token->getUser());
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\LockedException
     */
    public function testAuthenticateWhenUserCheckerThrowsException()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');

        $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        $userChecker->expects($this->once())
                    ->method('checkPostAuth')
                    ->will($this->throwException($this->getMock('Symfony\Component\Security\Core\Exception\LockedException', null, array(), '', false)))
        ;

        $provider = $this->getProvider($user, $userChecker);

        $provider->authenticate($this->getSupportedToken('fabien'));
    }

    protected function getSupportedToken($user = false, $credentials = false)
    {
        $token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken', array('getUser', 'getCredentials', 'getProviderKey'), array(), '', false);
        if (false !== $user) {
            $token->expects($this->once())
                  ->method('getUser')
                  ->will($this->returnValue($user))
            ;
        }
        if (false !== $credentials) {
            $token->expects($this->once())
                  ->method('getCredentials')
                  ->will($this->returnValue($credentials))
            ;
        }

        $token
            ->expects($this->any())
            ->method('getProviderKey')
            ->will($this->returnValue('key'))
        ;

        $token->setAttributes(array('foo' => 'bar'));

        return $token;
    }

    protected function getProvider($user = null, $userChecker = null)
    {
        $userProvider = $this->getMock('Symfony\Component\Security\Core\User\UserProviderInterface');
        if (null !== $user) {
            $userProvider->expects($this->once())
                         ->method('loadUserByUsername')
                         ->will($this->returnValue($user))
            ;
        }

        if (null === $userChecker) {
            $userChecker = $this->getMock('Symfony\Component\Security\Core\User\UserCheckerInterface');
        }

        return new PreAuthenticatedAuthenticationProvider($userProvider, $userChecker, 'key');
    }
}
PK21[�����cSecurity/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication;

use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

class AuthenticationProviderManagerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testAuthenticateWithoutProviders()
    {
        new AuthenticationProviderManager(array());
    }

    public function testAuthenticateWhenNoProviderSupportsToken()
    {
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(false),
        ));

        try {
            $manager->authenticate($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
            $this->fail();
        } catch (ProviderNotFoundException $e) {
            $this->assertSame($token, $e->getToken());
        }
    }

    public function testAuthenticateWhenProviderReturnsAccountStatusException()
    {
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AccountStatusException'),
        ));

        try {
            $manager->authenticate($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
            $this->fail();
        } catch (AccountStatusException $e) {
            $this->assertSame($token, $e->getToken());
        }
    }

    public function testAuthenticateWhenProviderReturnsAuthenticationException()
    {
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
        ));

        try {
            $manager->authenticate($token = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
            $this->fail();
        } catch (AuthenticationException $e) {
            $this->assertSame($token, $e->getToken());
        }
    }

    public function testAuthenticateWhenOneReturnsAuthenticationExceptionButNotAll()
    {
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, null, 'Symfony\Component\Security\Core\Exception\AuthenticationException'),
            $this->getAuthenticationProvider(true, $expected = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')),
        ));

        $token = $manager->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $this->assertSame($expected, $token);
    }

    public function testAuthenticateReturnsTokenOfTheFirstMatchingProvider()
    {
        $second = $this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface');
        $second
            ->expects($this->never())
            ->method('supports')
        ;
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, $expected = $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')),
            $second,
        ));

        $token = $manager->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $this->assertSame($expected, $token);
    }

    public function testEraseCredentialFlag()
    {
        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
        ));

        $token = $manager->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $this->assertEquals('', $token->getCredentials());

        $manager = new AuthenticationProviderManager(array(
            $this->getAuthenticationProvider(true, $token = new UsernamePasswordToken('foo', 'bar', 'key')),
        ), false);

        $token = $manager->authenticate($this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface'));
        $this->assertEquals('bar', $token->getCredentials());
    }

    protected function getAuthenticationProvider($supports, $token = null, $exception = null)
    {
        $provider = $this->getMock('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface');
        $provider->expects($this->once())
                 ->method('supports')
                 ->will($this->returnValue($supports))
        ;

        if (null !== $token) {
            $provider->expects($this->once())
                     ->method('authenticate')
                     ->will($this->returnValue($token))
            ;
        } elseif (null !== $exception) {
            $provider->expects($this->once())
                     ->method('authenticate')
                     ->will($this->throwException($this->getMock($exception, null, array(), '', false)))
            ;
        }

        return $provider;
    }
}
PK21[ ����fSecurity/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\RememberMe;

use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Authentication\RememberMe\InMemoryTokenProvider;

class InMemoryTokenProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testCreateNewToken()
    {
        $provider = new InMemoryTokenProvider();

        $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
        $provider->createNewToken($token);

        $this->assertSame($provider->loadTokenBySeries('foo'), $token);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
     */
    public function testLoadTokenBySeriesThrowsNotFoundException()
    {
        $provider = new InMemoryTokenProvider();
        $provider->loadTokenBySeries('foo');
    }

    public function testUpdateToken()
    {
        $provider = new InMemoryTokenProvider();

        $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
        $provider->createNewToken($token);
        $provider->updateToken('foo', 'newFoo', $lastUsed = new \DateTime());
        $token = $provider->loadTokenBySeries('foo');

        $this->assertEquals('newFoo', $token->getTokenValue());
        $this->assertSame($token->getLastUsed(), $lastUsed);
    }

    /**
     * @expectedException \Symfony\Component\Security\Core\Exception\TokenNotFoundException
     */
    public function testDeleteToken()
    {
        $provider = new InMemoryTokenProvider();

        $token = new PersistentToken('foo', 'foo', 'foo', 'foo', new \DateTime());
        $provider->createNewToken($token);
        $provider->deleteTokenBySeries('foo');
        $provider->loadTokenBySeries('foo');
    }
}
PK31[B�����`Security/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/PersistentTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\RememberMe;

use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;

class PersistentTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $lastUsed = new \DateTime();
        $token = new PersistentToken('fooclass', 'fooname', 'fooseries', 'footokenvalue', $lastUsed);

        $this->assertEquals('fooclass', $token->getClass());
        $this->assertEquals('fooname', $token->getUsername());
        $this->assertEquals('fooseries', $token->getSeries());
        $this->assertEquals('footokenvalue', $token->getTokenValue());
        $this->assertSame($lastUsed, $token->getLastUsed());
    }
}
PK31[I?��

aSecurity/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication;

use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;

class AuthenticationTrustResolverTest extends \PHPUnit_Framework_TestCase
{
    public function testIsAnonymous()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isAnonymous(null));
        $this->assertFalse($resolver->isAnonymous($this->getToken()));
        $this->assertFalse($resolver->isAnonymous($this->getRememberMeToken()));
        $this->assertTrue($resolver->isAnonymous($this->getAnonymousToken()));
    }

    public function testIsRememberMe()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isRememberMe(null));
        $this->assertFalse($resolver->isRememberMe($this->getToken()));
        $this->assertFalse($resolver->isRememberMe($this->getAnonymousToken()));
        $this->assertTrue($resolver->isRememberMe($this->getRememberMeToken()));
    }

    public function testisFullFledged()
    {
        $resolver = $this->getResolver();

        $this->assertFalse($resolver->isFullFledged(null));
        $this->assertFalse($resolver->isFullFledged($this->getAnonymousToken()));
        $this->assertFalse($resolver->isFullFledged($this->getRememberMeToken()));
        $this->assertTrue($resolver->isFullFledged($this->getToken()));
    }

    protected function getToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\TokenInterface');
    }

    protected function getAnonymousToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\AnonymousToken', null, array('', ''));
    }

    protected function getRememberMeToken()
    {
        return $this->getMock('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', array('setPersistent'), array(), '', false);
    }

    protected function getResolver()
    {
        return new AuthenticationTrustResolver(
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\AnonymousToken',
            'Symfony\\Component\\Security\\Core\\Authentication\\Token\\RememberMeToken'
        );
    }
}
PK31[�B3��$�$YSecurity/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\SwitchUserRole;

class TestUser
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function __toString()
    {
        return $this->name;
    }
}

class ConcreteToken extends AbstractToken
{
    private $credentials = 'credentials_value';

    public function __construct($user, array $roles = array())
    {
        parent::__construct($roles);

        $this->setUser($user);
    }

    public function serialize()
    {
        return serialize(array($this->credentials, parent::serialize()));
    }

    public function unserialize($serialized)
    {
        list($this->credentials, $parentStr) = unserialize($serialized);
        parent::unserialize($parentStr);
    }

    public function getCredentials() {}
}

class AbstractTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testGetUsername()
    {
        $token = $this->getToken(array('ROLE_FOO'));
        $token->setUser('fabien');
        $this->assertEquals('fabien', $token->getUsername());

        $token->setUser(new TestUser('fabien'));
        $this->assertEquals('fabien', $token->getUsername());

        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->once())->method('getUsername')->will($this->returnValue('fabien'));
        $token->setUser($user);
        $this->assertEquals('fabien', $token->getUsername());
    }

    public function testEraseCredentials()
    {
        $token = $this->getToken(array('ROLE_FOO'));

        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $user->expects($this->once())->method('eraseCredentials');
        $token->setUser($user);

        $token->eraseCredentials();
    }

    /**
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::serialize
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::unserialize
     */
    public function testSerialize()
    {
        $token = $this->getToken(array('ROLE_FOO'));
        $token->setAttributes(array('foo' => 'bar'));

        $uToken = unserialize(serialize($token));

        $this->assertEquals($token->getRoles(), $uToken->getRoles());
        $this->assertEquals($token->getAttributes(), $uToken->getAttributes());
    }

    public function testSerializeParent()
    {
        $user = new TestUser('fabien');
        $token = new ConcreteToken($user, array('ROLE_FOO'));

        $parentToken = new ConcreteToken($user, array(new SwitchUserRole('ROLE_PREVIOUS', $token)));
        $uToken = unserialize(serialize($parentToken));

        $this->assertEquals(
            current($parentToken->getRoles())->getSource()->getUser(),
            current($uToken->getRoles())->getSource()->getUser()
        );
    }

    /**
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::__construct
     */
    public function testConstructor()
    {
        $token = $this->getToken(array('ROLE_FOO'));
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());

        $token = $this->getToken(array(new Role('ROLE_FOO')));
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());

        $token = $this->getToken(array(new Role('ROLE_FOO'), 'ROLE_BAR'));
        $this->assertEquals(array(new Role('ROLE_FOO'), new Role('ROLE_BAR')), $token->getRoles());
    }

    /**
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::isAuthenticated
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::setAuthenticated
     */
    public function testAuthenticatedFlag()
    {
        $token = $this->getToken();
        $this->assertFalse($token->isAuthenticated());

        $token->setAuthenticated(true);
        $this->assertTrue($token->isAuthenticated());

        $token->setAuthenticated(false);
        $this->assertFalse($token->isAuthenticated());
    }

    /**
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::getAttributes
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::setAttributes
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::hasAttribute
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::getAttribute
     * @covers Symfony\Component\Security\Core\Authentication\Token\AbstractToken::setAttribute
     */
    public function testAttributes()
    {
        $attributes = array('foo' => 'bar');
        $token = $this->getToken();
        $token->setAttributes($attributes);

        $this->assertEquals($attributes, $token->getAttributes(), '->getAttributes() returns the token attributes');
        $this->assertEquals('bar', $token->getAttribute('foo'), '->getAttribute() returns the value of an attribute');
        $token->setAttribute('foo', 'foo');
        $this->assertEquals('foo', $token->getAttribute('foo'), '->setAttribute() changes the value of an attribute');
        $this->assertTrue($token->hasAttribute('foo'), '->hasAttribute() returns true if the attribute is defined');
        $this->assertFalse($token->hasAttribute('oof'), '->hasAttribute() returns false if the attribute is not defined');

        try {
            $token->getAttribute('foobar');
            $this->fail('->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
            $this->assertEquals('This token has no "foobar" attribute.', $e->getMessage(), '->getAttribute() throws an \InvalidArgumentException exception when the attribute does not exist');
        }
    }

    /**
     * @dataProvider getUsers
     */
    public function testSetUser($user)
    {
        $token = $this->getToken();
        $token->setUser($user);
        $this->assertSame($user, $token->getUser());
    }

    public function getUsers()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $advancedUser = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');

        return array(
            array($advancedUser),
            array($user),
            array(new TestUser('foo')),
            array('foo'),
        );
    }

    /**
     * @dataProvider getUserChanges
     */
    public function testSetUserSetsAuthenticatedToFalseWhenUserChanges($firstUser, $secondUser)
    {
        $token = $this->getToken();
        $token->setAuthenticated(true);
        $this->assertTrue($token->isAuthenticated());

        $token->setUser($firstUser);
        $this->assertTrue($token->isAuthenticated());

        $token->setUser($secondUser);
        $this->assertFalse($token->isAuthenticated());
    }

    public function getUserChanges()
    {
        $user = $this->getMock('Symfony\Component\Security\Core\User\UserInterface');
        $advancedUser = $this->getMock('Symfony\Component\Security\Core\User\AdvancedUserInterface');

        return array(
            array(
                'foo', 'bar',
            ),
            array(
                'foo', new TestUser('bar'),
            ),
            array(
                'foo', $user,
            ),
            array(
                'foo', $advancedUser
            ),
            array(
                $user, 'foo'
            ),
            array(
                $advancedUser, 'foo'
            ),
            array(
                $user, new TestUser('foo'),
            ),
            array(
                $advancedUser, new TestUser('foo'),
            ),
            array(
                new TestUser('foo'), new TestUser('bar'),
            ),
            array(
                new TestUser('foo'), 'bar',
            ),
            array(
                new TestUser('foo'), $user,
            ),
            array(
                new TestUser('foo'), $advancedUser,
            ),
            array(
                $user, $advancedUser
            ),
            array(
                $advancedUser, $user
            ),
        );
    }

    /**
     * @dataProvider getUsers
     */
    public function testSetUserDoesNotSetAuthenticatedToFalseWhenUserDoesNotChange($user)
    {
        $token = $this->getToken();
        $token->setAuthenticated(true);
        $this->assertTrue($token->isAuthenticated());

        $token->setUser($user);
        $this->assertTrue($token->isAuthenticated());

        $token->setUser($user);
        $this->assertTrue($token->isAuthenticated());
    }

    protected function getToken(array $roles = array())
    {
        return $this->getMockForAbstractClass('Symfony\Component\Security\Core\Authentication\Token\AbstractToken', array($roles));
    }
}
PK31[�j��KKaSecurity/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\Role;

class UsernamePasswordTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $this->assertFalse($token->isAuthenticated());

        $token = new UsernamePasswordToken('foo', 'bar', 'key', array('ROLE_FOO'));
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
        $this->assertTrue($token->isAuthenticated());
        $this->assertEquals('key', $token->getProviderKey());
    }

    /**
     * @expectedException \LogicException
     */
    public function testSetAuthenticatedToTrue()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->setAuthenticated(true);
    }

    public function testSetAuthenticatedToFalse()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->setAuthenticated(false);
        $this->assertFalse($token->isAuthenticated());
    }

    public function testEraseCredentials()
    {
        $token = new UsernamePasswordToken('foo', 'bar', 'key');
        $token->eraseCredentials();
        $this->assertEquals('', $token->getCredentials());
    }

    public function testToString()
    {
        $token = new UsernamePasswordToken('foo', '', 'foo', array('A', 'B'));
        $this->assertEquals('UsernamePasswordToken(user="foo", authenticated=true, roles="A, B")', (string) $token);
    }
}
PK31[d���aSecurity/Symfony/Component/Security/Core/Tests/Authentication/Token/PreAuthenticatedTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Role\Role;

class PreAuthenticatedTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $token = new PreAuthenticatedToken('foo', 'bar', 'key');
        $this->assertFalse($token->isAuthenticated());

        $token = new PreAuthenticatedToken('foo', 'bar', 'key', array('ROLE_FOO'));
        $this->assertTrue($token->isAuthenticated());
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
        $this->assertEquals('key', $token->getProviderKey());
    }

    public function testGetCredentials()
    {
        $token = new PreAuthenticatedToken('foo', 'bar', 'key');
        $this->assertEquals('bar', $token->getCredentials());
    }

    public function testGetUser()
    {
        $token = new PreAuthenticatedToken('foo', 'bar', 'key');
        $this->assertEquals('foo', $token->getUser());
    }

    public function testEraseCredentials()
    {
        $token = new PreAuthenticatedToken('foo', 'bar', 'key');
        $token->eraseCredentials();
        $this->assertEquals('', $token->getCredentials());
    }
}
PK31[��ۛ��ZSecurity/Symfony/Component/Security/Core/Tests/Authentication/Token/AnonymousTokenTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Tests\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Role\Role;

class AnonymousTokenTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $token = new AnonymousToken('foo', 'bar');
        $this->assertTrue($token->isAuthenticated());

        $token = new AnonymousToken('foo', 'bar', array('ROLE_FOO'));
        $this->assertEquals(array(new Role('ROLE_FOO')), $token->getRoles());
    }

    public function testGetKey()
    {
        $token = new AnonymousToken('foo', 'bar');
        $this->assertEquals('foo', $token->getKey());
    }

    public function testGetCredentials()
    {
        $token = new AnonymousToken('foo', 'bar');
        $this->assertEquals('', $token->getCredentials());
    }

    public function testGetUser()
    {
        $token = new AnonymousToken('foo', 'bar');
        $this->assertEquals('bar', $token->getUser());
    }
}
PK31[]�P�<<9Security/Symfony/Component/Security/Core/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Security Component Core Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK31[���n��GValidator/Symfony/Component/Validator/Tests/ConstraintViolationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\ConstraintViolation;

class ConstraintViolationTest extends \PHPUnit_Framework_TestCase
{
    public function testToStringHandlesArrays()
    {
        $violation = new ConstraintViolation(
            'Array',
            '{{ value }}',
            array('{{ value }}' => array(1, 2, 3)),
            'Root',
            'property.path',
            null
        );

        $expected = <<<EOF
Root.property.path:
    Array
EOF;

        $this->assertSame($expected, (string) $violation);
    }

    public function testToStringHandlesArrayRoots()
    {
        $violation = new ConstraintViolation(
            '42 cannot be used here',
            'this is the message template',
            array(),
            array('some_value' =>  42),
            'some_value',
            null
        );

        $expected = <<<EOF
Array.some_value:
    42 cannot be used here
EOF;

        $this->assertSame($expected, (string) $violation);
    }
}
PK31[zJ.4�
�
KValidator/Symfony/Component/Validator/Tests/ConstraintViolationListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;

class ConstraintViolationListTest extends \PHPUnit_Framework_TestCase
{
    protected $list;

    protected function setUp()
    {
        $this->list = new ConstraintViolationList();
    }

    protected function tearDown()
    {
        $this->list = null;
    }

    public function testInit()
    {
        $this->assertCount(0, $this->list);
    }

    public function testInitWithViolations()
    {
        $violation = $this->getViolation('Error');
        $this->list = new ConstraintViolationList(array($violation));

        $this->assertCount(1, $this->list);
        $this->assertSame($violation, $this->list[0]);
    }

    public function testAdd()
    {
        $violation = $this->getViolation('Error');
        $this->list->add($violation);

        $this->assertCount(1, $this->list);
        $this->assertSame($violation, $this->list[0]);
    }

    public function testAddAll()
    {
        $violations = array(
            10 => $this->getViolation('Error 1'),
            20 => $this->getViolation('Error 2'),
            30 => $this->getViolation('Error 3'),
        );
        $otherList = new ConstraintViolationList($violations);
        $this->list->addAll($otherList);

        $this->assertCount(3, $this->list);

        $this->assertSame($violations[10], $this->list[0]);
        $this->assertSame($violations[20], $this->list[1]);
        $this->assertSame($violations[30], $this->list[2]);
    }

    public function testIterator()
    {
        $violations = array(
            10 => $this->getViolation('Error 1'),
            20 => $this->getViolation('Error 2'),
            30 => $this->getViolation('Error 3'),
        );

        $this->list = new ConstraintViolationList($violations);

        // indices are reset upon adding -> array_values()
        $this->assertSame(array_values($violations), iterator_to_array($this->list));
    }

    public function testArrayAccess()
    {
        $violation = $this->getViolation('Error');
        $this->list[] = $violation;

        $this->assertSame($violation, $this->list[0]);
        $this->assertTrue(isset($this->list[0]));

        unset($this->list[0]);

        $this->assertFalse(isset($this->list[0]));

        $this->list[10] = $violation;

        $this->assertSame($violation, $this->list[10]);
        $this->assertTrue(isset($this->list[10]));
    }

    public function testToString()
    {
        $this->list = new ConstraintViolationList(array(
            $this->getViolation('Error 1', 'Root'),
            $this->getViolation('Error 2', 'Root', 'foo.bar'),
            $this->getViolation('Error 3', 'Root', '[baz]'),
            $this->getViolation('Error 4', '', 'foo.bar'),
            $this->getViolation('Error 5', '', '[baz]'),
        ));

        $expected = <<<EOF
Root:
    Error 1
Root.foo.bar:
    Error 2
Root[baz]:
    Error 3
foo.bar:
    Error 4
[baz]:
    Error 5

EOF;

        $this->assertEquals($expected, (string) $this->list);
    }

    protected function getViolation($message, $root = null, $propertyPath = null)
    {
        return new ConstraintViolation($message, $message, array(), $root, $propertyPath, null);
    }
}
PK31[�p��ggSValidator/Symfony/Component/Validator/Tests/Fixtures/FailingConstraintValidator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class FailingConstraintValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        $this->context->addViolation($constraint->message, array());

        return;
    }
}
PK31[5*�DValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintB.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

/** @Annotation */
class ConstraintB extends Constraint
{
    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK31[]�qqDValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintC.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

/** @Annotation */
class ConstraintC extends Constraint
{
    public $option1;

    public function getRequiredOptions()
    {
        return array('option1');
    }

    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK31[���&��DValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintA.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

/** @Annotation */
class ConstraintA extends Constraint
{
    public $property1;
    public $property2;

    public function getDefaultOption()
    {
        return 'property2';
    }

    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK31[ߛ��[[?Validator/Symfony/Component/Validator/Tests/Fixtures/Entity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;

/**
 * @Symfony\Component\Validator\Tests\Fixtures\ConstraintA
 * @Assert\GroupSequence({"Foo", "Entity"})
 * @Assert\Callback({"Symfony\Component\Validator\Tests\Fixtures\CallbackClass", "callback"})
 */
class Entity extends EntityParent implements EntityInterface
{
    /**
     * @Assert\NotNull
     * @Assert\Range(min=3)
     * @Assert\All({@Assert\NotNull, @Assert\Range(min=3)}),
     * @Assert\All(constraints={@Assert\NotNull, @Assert\Range(min=3)})
     * @Assert\Collection(fields={
     *   "foo" = {@Assert\NotNull, @Assert\Range(min=3)},
     *   "bar" = @Assert\Range(min=5)
     * })
     * @Assert\Choice(choices={"A", "B"}, message="Must be one of %choices%")
     */
    protected $firstName;
    protected $lastName;
    public $reference;
    private $internal;
    public $data = 'Overridden data';

    public function __construct($internal = null)
    {
        $this->internal = $internal;
    }

    public function getInternal()
    {
        return $this->internal.' from getter';
    }

    /**
     * @Assert\NotNull
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    public function getData()
    {
        return 'Overridden data';
    }

    /**
     * @Assert\Callback
     */
    public function validateMe(ExecutionContextInterface $context)
    {
    }

    /**
     * @Assert\Callback
     */
    public static function validateMeStatic($object, ExecutionContextInterface $context)
    {
    }
}
PK31[p�Tq��UValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintWithValueAsDefault.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

/** @Annotation */
class ConstraintWithValueAsDefault extends Constraint
{
    public $property;
    public $value;

    public function getDefaultOption()
    {
        return 'value';
    }

    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK31[@��w��LValidator/Symfony/Component/Validator/Tests/Fixtures/FakeMetadataFactory.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Exception\NoSuchMetadataException;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class FakeMetadataFactory implements MetadataFactoryInterface
{
    protected $metadatas = array();

    public function getMetadataFor($class)
    {
        if (is_object($class)) {
            $class = get_class($class);
        }

        if (!is_string($class)) {
            throw new NoSuchMetadataException(sprintf('No metadata for type %s', gettype($class)));
        }

        if (!isset($this->metadatas[$class])) {
            throw new NoSuchMetadataException(sprintf('No metadata for "%s"', $class));
        }

        return $this->metadatas[$class];
    }

    public function hasMetadataFor($class)
    {
        if (is_object($class)) {
            $class = get_class($class);
        }

        if (!is_string($class)) {
            return false;
        }

        return isset($this->metadatas[$class]);
    }

    public function addMetadata(ClassMetadata $metadata)
    {
        $this->metadatas[$metadata->getClassName()] = $metadata;
    }
}
PK31[��a�CCHValidator/Symfony/Component/Validator/Tests/Fixtures/EntityInterface.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

interface EntityInterface
{
}
PK31[?>��MValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintAValidator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\ExecutionContextInterface;

class ConstraintAValidator extends ConstraintValidator
{
    public static $passedContext;

    public function initialize(ExecutionContextInterface $context)
    {
        parent::initialize($context);

        self::$passedContext = $context;
    }

    public function validate($value, Constraint $constraint)
    {
        if ('VALID' != $value) {
            $this->context->addViolation('message', array('param' => 'value'));

            return;
        }

        return;
    }
}
PK31[^t��HValidator/Symfony/Component/Validator/Tests/Fixtures/ClassConstraint.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

class ClassConstraint extends Constraint
{
    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}
PK41[��88EValidator/Symfony/Component/Validator/Tests/Fixtures/EntityParent.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraints\NotNull;

class EntityParent
{
    protected $firstName;
    private $internal;
    private $data = 'Data';

    /**
     * @NotNull
     */
    protected $other;

    public function getData()
    {
        return 'Data';
    }
}
PK41[�h��TValidator/Symfony/Component/Validator/Tests/Fixtures/GroupSequenceProviderEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;

/**
 * @Assert\GroupSequenceProvider
 */
class GroupSequenceProviderEntity implements GroupSequenceProviderInterface
{
    public $firstName;
    public $lastName;

    protected $groups = array();

    public function setGroups($groups)
    {
        $this->groups = $groups;
    }

    public function getGroupSequence()
    {
        return $this->groups;
    }
}
PK41[�5>��LValidator/Symfony/Component/Validator/Tests/Fixtures/ConstraintWithValue.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

/** @Annotation */
class ConstraintWithValue extends Constraint
{
    public $property;
    public $value;

    public function getDefaultOption()
    {
        return 'property';
    }

    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK41[=�2JValidator/Symfony/Component/Validator/Tests/Fixtures/FailingConstraint.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

class FailingConstraint extends Constraint
{
    public $message = 'Failed';

    public function getTargets()
    {
        return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
    }
}
PK41[O��l99BValidator/Symfony/Component/Validator/Tests/Fixtures/Reference.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

class Reference
{
}
PK41[2�	���JValidator/Symfony/Component/Validator/Tests/Fixtures/InvalidConstraint.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

class InvalidConstraint extends Constraint
{
}
PK41[j�/���DValidator/Symfony/Component/Validator/Tests/Fixtures/FilesLoader.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Mapping\Loader\FilesLoader as BaseFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;

abstract class FilesLoader extends BaseFilesLoader
{
    protected $timesCalled = 0;
    protected $loader;

    public function __construct(array $paths, LoaderInterface $loader)
    {
        $this->loader = $loader;
        parent::__construct($paths);
    }

    protected function getFileLoaderInstance($file)
    {
        $this->timesCalled++;

        return $this->loader;
    }

    public function getTimesCalled()
    {
        return $this->timesCalled;
    }
}
PK41[Y��/FValidator/Symfony/Component/Validator/Tests/Fixtures/CallbackClass.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\ExecutionContextInterface;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CallbackClass
{
    public static function callback($object, ExecutionContextInterface $context)
    {
    }
}
PK41[���JJSValidator/Symfony/Component/Validator/Tests/Fixtures/InvalidConstraintValidator.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

class InvalidConstraintValidator
{
}
PK41[G#i��KValidator/Symfony/Component/Validator/Tests/Fixtures/PropertyConstraint.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Fixtures;

use Symfony\Component\Validator\Constraint;

class PropertyConstraint extends Constraint
{
    public function getTargets()
    {
        return self::PROPERTY_CONSTRAINT;
    }
}
PK41[�Ε_))DValidator/Symfony/Component/Validator/Tests/ValidatorBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\ValidatorBuilder;
use Symfony\Component\Validator\ValidatorBuilderInterface;

class ValidatorBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ValidatorBuilderInterface
     */
    protected $builder;

    protected function setUp()
    {
        $this->builder = new ValidatorBuilder();
    }

    protected function tearDown()
    {
        $this->builder = null;
    }

    public function testAddObjectInitializer()
    {
        $this->assertSame($this->builder, $this->builder->addObjectInitializer(
            $this->getMock('Symfony\Component\Validator\ObjectInitializerInterface')
        ));
    }

    public function testAddObjectInitializers()
    {
        $this->assertSame($this->builder, $this->builder->addObjectInitializers(array()));
    }

    public function testAddXmlMapping()
    {
        $this->assertSame($this->builder, $this->builder->addXmlMapping('mapping'));
    }

    public function testAddXmlMappings()
    {
        $this->assertSame($this->builder, $this->builder->addXmlMappings(array()));
    }

    public function testAddYamlMapping()
    {
        $this->assertSame($this->builder, $this->builder->addYamlMapping('mapping'));
    }

    public function testAddYamlMappings()
    {
        $this->assertSame($this->builder, $this->builder->addYamlMappings(array()));
    }

    public function testAddMethodMapping()
    {
        $this->assertSame($this->builder, $this->builder->addMethodMapping('mapping'));
    }

    public function testAddMethodMappings()
    {
        $this->assertSame($this->builder, $this->builder->addMethodMappings(array()));
    }

    public function testEnableAnnotationMapping()
    {
        $this->assertSame($this->builder, $this->builder->enableAnnotationMapping());
    }

    public function testDisableAnnotationMapping()
    {
        $this->assertSame($this->builder, $this->builder->disableAnnotationMapping());
    }

    public function testSetMetadataCache()
    {
        $this->assertSame($this->builder, $this->builder->setMetadataCache(
            $this->getMock('Symfony\Component\Validator\Mapping\Cache\CacheInterface'))
        );
    }

    public function testSetConstraintValidatorFactory()
    {
        $this->assertSame($this->builder, $this->builder->setConstraintValidatorFactory(
            $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface'))
        );
    }

    public function testSetTranslator()
    {
        $this->assertSame($this->builder, $this->builder->setTranslator(
            $this->getMock('Symfony\Component\Translation\TranslatorInterface'))
        );
    }

    public function testSetTranslationDomain()
    {
        $this->assertSame($this->builder, $this->builder->setTranslationDomain('TRANS_DOMAIN'));
    }
}
PK41[��>���IValidator/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Exception\GroupDefinitionException;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Tests\Fixtures\PropertyConstraint;

class ClassMetadataTest extends \PHPUnit_Framework_TestCase
{
    const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
    const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';
    const PROVIDERCLASS = 'Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity';

    protected $metadata;

    protected function setUp()
    {
        $this->metadata = new ClassMetadata(self::CLASSNAME);
    }

    protected function tearDown()
    {
        $this->metadata = null;
    }

    public function testAddConstraintDoesNotAcceptValid()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        $this->metadata->addConstraint(new Valid());
    }

    public function testAddConstraintRequiresClassConstraints()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        $this->metadata->addConstraint(new PropertyConstraint());
    }

    public function testAddPropertyConstraints()
    {
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());
        $this->metadata->addPropertyConstraint('lastName', new ConstraintB());

        $this->assertEquals(array('firstName', 'lastName'), $this->metadata->getConstrainedProperties());
    }

    public function testMergeConstraintsMergesClassConstraints()
    {
        $parent = new ClassMetadata(self::PARENTCLASS);
        $parent->addConstraint(new ConstraintA());

        $this->metadata->mergeConstraints($parent);
        $this->metadata->addConstraint(new ConstraintA());

        $constraints = array(
            new ConstraintA(array('groups' => array(
                'Default',
                'EntityParent',
                'Entity',
            ))),
            new ConstraintA(array('groups' => array(
                'Default',
                'Entity',
            ))),
        );

        $this->assertEquals($constraints, $this->metadata->getConstraints());
    }

    public function testMergeConstraintsMergesMemberConstraints()
    {
        $parent = new ClassMetadata(self::PARENTCLASS);
        $parent->addPropertyConstraint('firstName', new ConstraintA());

        $this->metadata->mergeConstraints($parent);
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());

        $constraints = array(
            new ConstraintA(array('groups' => array(
                'Default',
                'EntityParent',
                'Entity',
            ))),
            new ConstraintA(array('groups' => array(
                'Default',
                'Entity',
            ))),
        );

        $members = $this->metadata->getMemberMetadatas('firstName');

        $this->assertCount(1, $members);
        $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName());
        $this->assertEquals($constraints, $members[0]->getConstraints());
    }

    public function testMemberMetadatas()
    {
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());

        $this->assertTrue($this->metadata->hasMemberMetadatas('firstName'));
        $this->assertFalse($this->metadata->hasMemberMetadatas('non_existant_field'));
    }

    public function testMergeConstraintsKeepsPrivateMembersSeparate()
    {
        $parent = new ClassMetadata(self::PARENTCLASS);
        $parent->addPropertyConstraint('internal', new ConstraintA());

        $this->metadata->mergeConstraints($parent);
        $this->metadata->addPropertyConstraint('internal', new ConstraintA());

        $parentConstraints = array(
            new ConstraintA(array('groups' => array(
                'Default',
                'EntityParent',
                'Entity',
            ))),
        );
        $constraints = array(
            new ConstraintA(array('groups' => array(
                'Default',
                'Entity',
            ))),
        );

        $members = $this->metadata->getMemberMetadatas('internal');

        $this->assertCount(2, $members);
        $this->assertEquals(self::PARENTCLASS, $members[0]->getClassName());
        $this->assertEquals($parentConstraints, $members[0]->getConstraints());
        $this->assertEquals(self::CLASSNAME, $members[1]->getClassName());
        $this->assertEquals($constraints, $members[1]->getConstraints());
    }

    public function testGetReflectionClass()
    {
        $reflClass = new \ReflectionClass(self::CLASSNAME);

        $this->assertEquals($reflClass, $this->metadata->getReflectionClass());
    }

    public function testSerialize()
    {
        $this->metadata->addConstraint(new ConstraintA(array('property1' => 'A')));
        $this->metadata->addConstraint(new ConstraintB(array('groups' => 'TestGroup')));
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());
        $this->metadata->addGetterConstraint('lastName', new ConstraintB());

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testGroupSequencesWorkIfContainingDefaultGroup()
    {
        $this->metadata->setGroupSequence(array('Foo', $this->metadata->getDefaultGroup()));
    }

    public function testGroupSequencesFailIfNotContainingDefaultGroup()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\GroupDefinitionException');

        $this->metadata->setGroupSequence(array('Foo', 'Bar'));
    }

    public function testGroupSequencesFailIfContainingDefault()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\GroupDefinitionException');

        $this->metadata->setGroupSequence(array('Foo', $this->metadata->getDefaultGroup(), Constraint::DEFAULT_GROUP));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
     */
    public function testGroupSequenceFailsIfGroupSequenceProviderIsSet()
    {
        $metadata = new ClassMetadata(self::PROVIDERCLASS);
        $metadata->setGroupSequenceProvider(true);
        $metadata->setGroupSequence(array('GroupSequenceProviderEntity', 'Foo'));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
     */
    public function testGroupSequenceProviderFailsIfGroupSequenceIsSet()
    {
        $metadata = new ClassMetadata(self::PROVIDERCLASS);
        $metadata->setGroupSequence(array('GroupSequenceProviderEntity', 'Foo'));
        $metadata->setGroupSequenceProvider(true);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
     */
    public function testGroupSequenceProviderFailsIfDomainClassIsInvalid()
    {
        $metadata = new ClassMetadata('stdClass');
        $metadata->setGroupSequenceProvider(true);
    }

    public function testGroupSequenceProvider()
    {
        $metadata = new ClassMetadata(self::PROVIDERCLASS);
        $metadata->setGroupSequenceProvider(true);
        $this->assertTrue($metadata->isGroupSequenceProvider());
    }
}
PK41[F���PValidator/Symfony/Component/Validator/Tests/Mapping/ClassMetadataFactoryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Mapping\ClassMetadataFactory;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;

class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
    const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
    const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';

    public function testLoadClassMetadata()
    {
        $factory = new ClassMetadataFactory(new TestLoader());
        $metadata = $factory->getMetadataFor(self::PARENTCLASS);

        $constraints = array(
            new ConstraintA(array('groups' => array('Default', 'EntityParent'))),
        );

        $this->assertEquals($constraints, $metadata->getConstraints());
    }

    public function testMergeParentConstraints()
    {
        $factory = new ClassMetadataFactory(new TestLoader());
        $metadata = $factory->getMetadataFor(self::CLASSNAME);

        $constraints = array(
            new ConstraintA(array('groups' => array(
                'Default',
                'EntityParent',
                'Entity',
            ))),
            new ConstraintA(array('groups' => array(
                'Default',
                'EntityInterface',
                'Entity',
            ))),
            new ConstraintA(array('groups' => array(
                'Default',
                'Entity',
            ))),
        );

        $this->assertEquals($constraints, $metadata->getConstraints());
    }

    public function testWriteMetadataToCache()
    {
        $cache = $this->getMock('Symfony\Component\Validator\Mapping\Cache\CacheInterface');
        $factory = new ClassMetadataFactory(new TestLoader(), $cache);

        $tester = $this;
        $constraints = array(
            new ConstraintA(array('groups' => array('Default', 'EntityParent'))),
        );

        $cache->expects($this->never())
              ->method('has');
        $cache->expects($this->once())
              ->method('read')
              ->with($this->equalTo(self::PARENTCLASS))
              ->will($this->returnValue(false));
        $cache->expects($this->once())
              ->method('write')
              ->will($this->returnCallback(function ($metadata) use ($tester, $constraints) {
                  $tester->assertEquals($constraints, $metadata->getConstraints());
              }));

        $metadata = $factory->getMetadataFor(self::PARENTCLASS);

        $this->assertEquals(self::PARENTCLASS, $metadata->getClassName());
        $this->assertEquals($constraints, $metadata->getConstraints());
    }

    public function testReadMetadataFromCache()
    {
        $loader = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $cache = $this->getMock('Symfony\Component\Validator\Mapping\Cache\CacheInterface');
        $factory = new ClassMetadataFactory($loader, $cache);

        $tester = $this;
        $metadata = new ClassMetadata(self::PARENTCLASS);
        $metadata->addConstraint(new ConstraintA());

        $loader->expects($this->never())
               ->method('loadClassMetadata');

        $cache->expects($this->never())
              ->method('has');
        $cache->expects($this->once())
              ->method('read')
              ->will($this->returnValue($metadata));

        $this->assertEquals($metadata,$factory->getMetadataFor(self::PARENTCLASS));
    }
}

class TestLoader implements LoaderInterface
{
    public function loadClassMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(new ConstraintA());
    }
}
PK41[)����KValidator/Symfony/Component/Validator/Tests/Mapping/ElementMetadataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Mapping\ElementMetadata;

class ElementMetadataTest extends \PHPUnit_Framework_TestCase
{
    protected $metadata;

    protected function setUp()
    {
        $this->metadata = new TestElementMetadata();
    }

    protected function tearDown()
    {
        $this->metadata = null;
    }

    public function testAddConstraints()
    {
        $this->metadata->addConstraint($constraint1 = new ConstraintA());
        $this->metadata->addConstraint($constraint2 = new ConstraintA());

        $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints());
    }

    public function testMultipleConstraintsOfTheSameType()
    {
        $constraint1 = new ConstraintA(array('property1' => 'A'));
        $constraint2 = new ConstraintA(array('property1' => 'B'));

        $this->metadata->addConstraint($constraint1);
        $this->metadata->addConstraint($constraint2);

        $this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints());
    }

    public function testFindConstraintsByGroup()
    {
        $constraint1 = new ConstraintA(array('groups' => 'TestGroup'));
        $constraint2 = new ConstraintB();

        $this->metadata->addConstraint($constraint1);
        $this->metadata->addConstraint($constraint2);

        $this->assertEquals(array($constraint1), $this->metadata->findConstraints('TestGroup'));
    }

    public function testSerialize()
    {
        $this->metadata->addConstraint(new ConstraintA(array('property1' => 'A')));
        $this->metadata->addConstraint(new ConstraintB(array('groups' => 'TestGroup')));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }
}

class TestElementMetadata extends ElementMetadata {}
PK41[�D��JValidator/Symfony/Component/Validator/Tests/Mapping/MemberMetadataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Tests\Fixtures\ClassConstraint;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\MemberMetadata;

class MemberMetadataTest extends \PHPUnit_Framework_TestCase
{
    protected $metadata;

    protected function setUp()
    {
        $this->metadata = new TestMemberMetadata(
            'Symfony\Component\Validator\Tests\Fixtures\Entity',
            'getLastName',
            'lastName'
        );
    }

    protected function tearDown()
    {
        $this->metadata = null;
    }

    public function testAddValidSetsMemberToCascaded()
    {
        $result = $this->metadata->addConstraint(new Valid());

        $this->assertEquals(array(), $this->metadata->getConstraints());
        $this->assertEquals($result, $this->metadata);
        $this->assertTrue($this->metadata->isCascaded());
    }

    public function testAddOtherConstraintDoesNotSetMemberToCascaded()
    {
        $result = $this->metadata->addConstraint($constraint = new ConstraintA());

        $this->assertEquals(array($constraint), $this->metadata->getConstraints());
        $this->assertEquals($result, $this->metadata);
        $this->assertFalse($this->metadata->isCascaded());
    }

    public function testAddConstraintRequiresClassConstraints()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        $this->metadata->addConstraint(new ClassConstraint());
    }

    public function testSerialize()
    {
        $this->metadata->addConstraint(new ConstraintA(array('property1' => 'A')));
        $this->metadata->addConstraint(new ConstraintB(array('groups' => 'TestGroup')));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testSerializeCollectionCascaded()
    {
        $this->metadata->addConstraint(new Valid(array('traverse' => true, 'deep' => false)));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testSerializeCollectionCascadedDeeply()
    {
        $this->metadata->addConstraint(new Valid(array('traverse' => true, 'deep' => true)));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }

    public function testSerializeCollectionNotCascaded()
    {
        $this->metadata->addConstraint(new Valid(array('traverse' => false)));

        $metadata = unserialize(serialize($this->metadata));

        $this->assertEquals($this->metadata, $metadata);
    }
}

class TestMemberMetadata extends MemberMetadata
{
    public function getPropertyValue($object)
    {
    }

    protected function newReflectionMember($object)
    {
    }
}
PK41[W_Ϙ�JValidator/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Mapping\GetterMetadata;
use Symfony\Component\Validator\Tests\Fixtures\Entity;

class GetterMetadataTest extends \PHPUnit_Framework_TestCase
{
    const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';

    public function testInvalidPropertyName()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ValidatorException');

        new GetterMetadata(self::CLASSNAME, 'foobar');
    }

    public function testGetPropertyValueFromPublicGetter()
    {
        // private getters don't work yet because ReflectionMethod::setAccessible()
        // does not exist yet in a stable PHP release

        $entity = new Entity('foobar');
        $metadata = new GetterMetadata(self::CLASSNAME, 'internal');

        $this->assertEquals('foobar from getter', $metadata->getPropertyValue($entity));
    }

    public function testGetPropertyValueFromOverriddenPublicGetter()
    {
        $entity = new Entity();
        $metadata = new GetterMetadata(self::CLASSNAME, 'data');

        $this->assertEquals('Overridden data', $metadata->getPropertyValue($entity));
    }
}
PK41["��,�	�	JValidator/Symfony/Component/Validator/Tests/Mapping/Cache/ApcCacheTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Cache;

use Symfony\Component\Validator\Mapping\Cache\ApcCache;

class ApcCacheTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!extension_loaded('apc') || !ini_get('apc.enable_cli')) {
            $this->markTestSkipped('APC is not loaded.');
        }
    }

    public function testWrite()
    {
        $meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
            ->disableOriginalConstructor()
            ->setMethods(array('getClassName'))
            ->getMock();

        $meta->expects($this->once())
            ->method('getClassName')
            ->will($this->returnValue('bar'));

        $cache = new ApcCache('foo');
        $cache->write($meta);

        $this->assertInstanceOf('Symfony\\Component\\Validator\\Mapping\\ClassMetadata', apc_fetch('foobar'), '->write() stores metadata in APC');
    }

    public function testHas()
    {
        $meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
            ->disableOriginalConstructor()
            ->setMethods(array('getClassName'))
            ->getMock();

        $meta->expects($this->once())
            ->method('getClassName')
            ->will($this->returnValue('bar'));

        apc_delete('foobar');

        $cache = new ApcCache('foo');
        $this->assertFalse($cache->has('bar'), '->has() returns false when there is no entry');

        $cache->write($meta);
        $this->assertTrue($cache->has('bar'), '->has() returns true when the is an entry');
    }

    public function testRead()
    {
        $meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
            ->disableOriginalConstructor()
            ->setMethods(array('getClassName'))
            ->getMock();

        $meta->expects($this->once())
            ->method('getClassName')
            ->will($this->returnValue('bar'));

        $cache = new ApcCache('foo');
        $cache->write($meta);

        $this->assertInstanceOf('Symfony\\Component\\Validator\\Mapping\\ClassMetadata', $cache->read('bar'), '->read() returns metadata');
    }
}
PK51[os%�eeTValidator/Symfony/Component/Validator/Tests/Mapping/BlackholeMetadataFactoryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Mapping\BlackholeMetadataFactory;

class BlackholeMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     */
    public function testGetMetadataForThrowsALogicException()
    {
        $metadataFactory = new BlackholeMetadataFactory();
        $metadataFactory->getMetadataFor('foo');
    }

    public function testHasMetadataForReturnsFalse()
    {
        $metadataFactory = new BlackholeMetadataFactory();

        $this->assertFalse($metadataFactory->hasMetadataFor('foo'));
    }
}
PK51[u��gNValidator/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\LoaderChain;

class LoaderChainTest extends \PHPUnit_Framework_TestCase
{
    public function testAllLoadersAreCalled()
    {
        $metadata = new ClassMetadata('\stdClass');

        $loader1 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader1->expects($this->once())
                        ->method('loadClassMetadata')
                        ->with($this->equalTo($metadata));

        $loader2 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader2->expects($this->once())
                        ->method('loadClassMetadata')
                        ->with($this->equalTo($metadata));

        $chain = new LoaderChain(array(
            $loader1,
            $loader2,
        ));

        $chain->loadClassMetadata($metadata);
    }

    public function testReturnsTrueIfAnyLoaderReturnedTrue()
    {
        $metadata = new ClassMetadata('\stdClass');

        $loader1 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader1->expects($this->any())
                        ->method('loadClassMetadata')
                        ->will($this->returnValue(true));

        $loader2 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader2->expects($this->any())
                        ->method('loadClassMetadata')
                        ->will($this->returnValue(false));

        $chain = new LoaderChain(array(
            $loader1,
            $loader2,
        ));

        $this->assertTrue($chain->loadClassMetadata($metadata));
    }

    public function testReturnsFalseIfNoLoaderReturnedTrue()
    {
        $metadata = new ClassMetadata('\stdClass');

        $loader1 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader1->expects($this->any())
                        ->method('loadClassMetadata')
                        ->will($this->returnValue(false));

        $loader2 = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
        $loader2->expects($this->any())
                        ->method('loadClassMetadata')
                        ->will($this->returnValue(false));

        $chain = new LoaderChain(array(
            $loader1,
            $loader2,
        ));

        $this->assertFalse($chain->loadClassMetadata($metadata));
    }
}
PK51[�=����]Validator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping-non-strings.xmlnu�[���<?xml version="1.0" ?>

<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

  <namespace prefix="custom">Symfony\Component\Validator\Tests\Fixtures\</namespace>

  <class name="Symfony\Component\Validator\Tests\Fixtures\Entity">
    <property name="firstName">
      <!-- Constraint with a Boolean -->
      <constraint name="Regex">
          <option name="pattern">/^1/</option>
          <option name="match">false</option>
      </constraint>
    </property>
  </class>

</constraint-mapping>
PK51[�D�k��QValidator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping.xmlnu�[���<?xml version="1.0" ?>

<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">

  <namespace prefix="custom">Symfony\Component\Validator\Tests\Fixtures\</namespace>

  <class name="Symfony\Component\Validator\Tests\Fixtures\Entity">

    <group-sequence>
       <value>Foo</value>
       <value>Entity</value>
    </group-sequence>

    <!-- CLASS CONSTRAINTS -->

    <!-- Custom constraint -->
    <constraint name="Symfony\Component\Validator\Tests\Fixtures\ConstraintA" />

    <!-- Custom constraint with namespace abbreviation-->
    <constraint name="custom:ConstraintB" />

    <!-- Callbacks -->
    <constraint name="Callback">validateMe</constraint>

    <constraint name="Callback">validateMeStatic</constraint>

    <constraint name="Callback">
        <value>Symfony\Component\Validator\Tests\Fixtures\CallbackClass</value>
        <value>callback</value>
    </constraint>

    <!-- PROPERTY CONSTRAINTS -->

    <property name="firstName">

      <!-- Constraint without value -->
      <constraint name="NotNull" />

      <!-- Constraint with single value -->
      <constraint name="Range">
         <option name="min">3</option>
      </constraint>

      <!-- Constraint with multiple values -->
      <constraint name="Choice">
        <value>A</value>
        <value>B</value>
      </constraint>

      <!-- Constraint with child constraints -->
      <constraint name="All">
        <constraint name="NotNull" />
        <constraint name="Range">
           <option name="min">3</option>
        </constraint>

      </constraint>

      <!-- Option with child constraints -->
      <constraint name="All">
        <option name="constraints">
          <constraint name="NotNull" />
          <constraint name="Range">
             <option name="min">3</option>
          </constraint>
        </option>
      </constraint>

      <!-- Value with child constraints -->
      <constraint name="Collection">
        <option name="fields">
          <value key="foo">
            <constraint name="NotNull" />
            <constraint name="Range">
               <option name="min">3</option>
            </constraint>
          </value>
          <value key="bar">
            <constraint name="Range">
               <option name="min">5</option>
            </constraint>
          </value>
        </option>
      </constraint>

      <!-- Constraint with options -->
      <constraint name="Choice">
        <!-- Option with single value -->
        <option name="message"> Must be one of %choices% </option>
        <!-- Option with multiple values -->
        <option name="choices">
          <value>A</value>
          <value>B</value>
        </option>
      </constraint>
    </property>

    <!-- GETTER CONSTRAINTS -->

    <getter property="lastName">
      <constraint name="NotNull" />
    </getter>
  </class>

  <class name="Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity">

    <!-- GROUP SEQUENCE PROVIDER -->
    <group-sequence-provider />

  </class>
</constraint-mapping>
PK51[�-���QValidator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping.ymlnu�[���namespaces:
  custom: Symfony\Component\Validator\Tests\Fixtures\

Symfony\Component\Validator\Tests\Fixtures\Entity:
  group_sequence:
    - Foo
    - Entity

  constraints:
    # Custom constraint
    - Symfony\Component\Validator\Tests\Fixtures\ConstraintA: ~
    # Custom constraint with namespaces prefix
    - "custom:ConstraintB": ~
    # Callbacks
    - Callback: validateMe
    - Callback: validateMeStatic
    - Callback: [Symfony\Component\Validator\Tests\Fixtures\CallbackClass, callback]

  properties:
    firstName:
      # Constraint without value
      - NotNull: ~
      # Constraint with single value
      - Range:
          min: 3
      # Constraint with multiple values
      - Choice: [A, B]
      # Constraint with child constraints
      - All:
          - NotNull: ~
          - Range:
              min: 3
      # Option with child constraints
      - All:
          constraints:
            - NotNull: ~
            - Range:
                min: 3
      # Value with child constraints
      - Collection:
          fields:
            foo:
              - NotNull: ~
              - Range:
                  min: 3
            bar:
              - Range:
                  min: 5
      # Constraint with options
      - Choice: { choices: [A, B], message: Must be one of %choices% }
    dummy:

  getters:
    lastName:
      - NotNull: ~

Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity:
  group_sequence_provider: true
PK51[{�%uUValidator/Symfony/Component/Validator/Tests/Mapping/Loader/StaticMethodLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;

class StaticMethodLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadClassMetadataReturnsTrueIfSuccessful()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity');

        $this->assertTrue($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadataReturnsFalseIfNotSuccessful()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata('\stdClass');

        $this->assertFalse($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadata()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderEntity');

        $loader->loadClassMetadata($metadata);

        $this->assertEquals(StaticLoaderEntity::$invokedWith, $metadata);
    }

    public function testLoadClassMetadataDoesNotRepeatLoadWithParentClasses()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderDocument');
        $loader->loadClassMetadata($metadata);
        $this->assertCount(0, $metadata->getConstraints());

        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\BaseStaticLoaderDocument');
        $loader->loadClassMetadata($metadata);
        $this->assertCount(1, $metadata->getConstraints());
    }

    public function testLoadClassMetadataIgnoresInterfaces()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\StaticLoaderInterface');

        $loader->loadClassMetadata($metadata);

        $this->assertCount(0, $metadata->getConstraints());
    }

    public function testLoadClassMetadataInAbstractClasses()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        $metadata = new ClassMetadata(__NAMESPACE__.'\AbstractStaticLoader');

        $loader->loadClassMetadata($metadata);

        $this->assertCount(1, $metadata->getConstraints());
    }

    public function testLoadClassMetadataIgnoresAbstractMethods()
    {
        $loader = new StaticMethodLoader('loadMetadata');
        try {
            include __DIR__ . '/AbstractMethodStaticLoader.php';
            $this->fail('AbstractMethodStaticLoader should produce a strict standard error.');
        } catch (\Exception $e) {
        }

        $metadata = new ClassMetadata(__NAMESPACE__.'\AbstractMethodStaticLoader');
        $loader->loadClassMetadata($metadata);

        $this->assertCount(0, $metadata->getConstraints());
    }
}

interface StaticLoaderInterface
{
    public static function loadMetadata(ClassMetadata $metadata);
}

abstract class AbstractStaticLoader
{
    public static function loadMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(new ConstraintA());
    }
}

class StaticLoaderEntity
{
    public static $invokedWith = null;

    public static function loadMetadata(ClassMetadata $metadata)
    {
        self::$invokedWith = $metadata;
    }
}

class StaticLoaderDocument extends BaseStaticLoaderDocument
{
}

class BaseStaticLoaderDocument
{
    public static function loadMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(new ConstraintA());
    }
}
PK51[���mSValidator/Symfony/Component/Validator/Tests/Mapping/Loader/AnnotationLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;

class AnnotationLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadClassMetadataReturnsTrueIfSuccessful()
    {
        $reader = new AnnotationReader();
        $loader = new AnnotationLoader($reader);
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $this->assertTrue($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadataReturnsFalseIfNotSuccessful()
    {
        $loader = new AnnotationLoader(new AnnotationReader());
        $metadata = new ClassMetadata('\stdClass');

        $this->assertFalse($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadata()
    {
        $loader = new AnnotationLoader(new AnnotationReader());
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $expected->setGroupSequence(array('Foo', 'Entity'));
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new Callback(array('Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback')));
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(array('min' => 3)));
        $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Range(array('min' => 3)))));
        $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Range(array('min' => 3))))));
        $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array(
            'foo' => array(new NotNull(), new Range(array('min' => 3))),
            'bar' => new Range(array('min' => 5)),
        ))));
        $expected->addPropertyConstraint('firstName', new Choice(array(
            'message' => 'Must be one of %choices%',
            'choices' => array('A', 'B'),
        )));
        $expected->addGetterConstraint('lastName', new NotNull());

        // load reflection class so that the comparison passes
        $expected->getReflectionClass();

        $this->assertEquals($expected, $metadata);
    }

    /**
     * Test MetaData merge with parent annotation.
     */
    public function testLoadParentClassMetadata()
    {
        $loader = new AnnotationLoader(new AnnotationReader());

        // Load Parent MetaData
        $parent_metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\EntityParent');
        $loader->loadClassMetadata($parent_metadata);

        $expected_parent = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\EntityParent');
        $expected_parent->addPropertyConstraint('other', new NotNull());
        $expected_parent->getReflectionClass();

        $this->assertEquals($expected_parent, $parent_metadata);
    }
    /**
     * Test MetaData merge with parent annotation.
     */
    public function testLoadClassMetadataAndMerge()
    {
        $loader = new AnnotationLoader(new AnnotationReader());

        // Load Parent MetaData
        $parent_metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\EntityParent');
        $loader->loadClassMetadata($parent_metadata);

        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        // Merge parent metaData.
        $metadata->mergeConstraints($parent_metadata);

        $loader->loadClassMetadata($metadata);

        $expected_parent = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\EntityParent');
        $expected_parent->addPropertyConstraint('other', new NotNull());
        $expected_parent->getReflectionClass();

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $expected->mergeConstraints($expected_parent);

        $expected->setGroupSequence(array('Foo', 'Entity'));
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new Callback(array('Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback')));
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(array('min' => 3)));
        $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Range(array('min' => 3)))));
        $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Range(array('min' => 3))))));
        $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array(
            'foo' => array(new NotNull(), new Range(array('min' => 3))),
            'bar' => new Range(array('min' => 5)),
        ))));
        $expected->addPropertyConstraint('firstName', new Choice(array(
            'message' => 'Must be one of %choices%',
            'choices' => array('A', 'B'),
        )));
        $expected->addGetterConstraint('lastName', new NotNull());

        // load reflection class so that the comparison passes
        $expected->getReflectionClass();

        $this->assertEquals($expected, $metadata);
    }

    public function testLoadGroupSequenceProviderAnnotation()
    {
        $loader = new AnnotationLoader(new AnnotationReader());

        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');
        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');
        $expected->setGroupSequenceProvider(true);
        $expected->getReflectionClass();

        $this->assertEquals($expected, $metadata);
    }
}
PK51[��N��QValidator/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;

class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadClassMetadataReturnsFalseIfEmpty()
    {
        $loader = new YamlFileLoader(__DIR__.'/empty-mapping.yml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $this->assertFalse($loader->loadClassMetadata($metadata));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLoadClassMetadataThrowsExceptionIfNotAnArray()
    {
        $loader = new YamlFileLoader(__DIR__.'/nonvalid-mapping.yml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $loader->loadClassMetadata($metadata);
    }

    public function testLoadClassMetadataReturnsTrueIfSuccessful()
    {
        $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $this->assertTrue($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadataReturnsFalseIfNotSuccessful()
    {
        $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml');
        $metadata = new ClassMetadata('\stdClass');

        $this->assertFalse($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadata()
    {
        $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $expected->setGroupSequence(array('Foo', 'Entity'));
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(array('Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback')));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(array('min' => 3)));
        $expected->addPropertyConstraint('firstName', new Choice(array('A', 'B')));
        $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Range(array('min' => 3)))));
        $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Range(array('min' => 3))))));
        $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array(
            'foo' => array(new NotNull(), new Range(array('min' => 3))),
            'bar' => array(new Range(array('min' => 5))),
        ))));
        $expected->addPropertyConstraint('firstName', new Choice(array(
            'message' => 'Must be one of %choices%',
            'choices' => array('A', 'B'),
        )));
        $expected->addGetterConstraint('lastName', new NotNull());

        $this->assertEquals($expected, $metadata);
    }

    public function testLoadGroupSequenceProvider()
    {
        $loader = new YamlFileLoader(__DIR__.'/constraint-mapping.yml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');
        $expected->setGroupSequenceProvider(true);

        $this->assertEquals($expected, $metadata);
    }
}
PK51[N�;��JValidator/Symfony/Component/Validator/Tests/Mapping/Loader/withdoctype.xmlnu�[���<?xml version="1.0"?>
<!DOCTYPE foo>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
  <class name="Symfony\Component\Validator\Tests\Fixtures\Entity" />
</constraint-mapping>
PK51[LValidator/Symfony/Component/Validator/Tests/Mapping/Loader/empty-mapping.ymlnu�[���PK51[�Qi���PValidator/Symfony/Component/Validator/Tests/Mapping/Loader/XmlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\XmlFileLoader;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;

class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadClassMetadataReturnsTrueIfSuccessful()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $this->assertTrue($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadataReturnsFalseIfNotSuccessful()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata('\stdClass');

        $this->assertFalse($loader->loadClassMetadata($metadata));
    }

    public function testLoadClassMetadata()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $expected->setGroupSequence(array('Foo', 'Entity'));
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new ConstraintB());
        $expected->addConstraint(new Callback('validateMe'));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addConstraint(new Callback(array('Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback')));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(array('min' => 3)));
        $expected->addPropertyConstraint('firstName', new Choice(array('A', 'B')));
        $expected->addPropertyConstraint('firstName', new All(array(new NotNull(), new Range(array('min' => 3)))));
        $expected->addPropertyConstraint('firstName', new All(array('constraints' => array(new NotNull(), new Range(array('min' => 3))))));
        $expected->addPropertyConstraint('firstName', new Collection(array('fields' => array(
            'foo' => array(new NotNull(), new Range(array('min' => 3))),
            'bar' => array(new Range(array('min' => 5))),
        ))));
        $expected->addPropertyConstraint('firstName', new Choice(array(
            'message' => 'Must be one of %choices%',
            'choices' => array('A', 'B'),
        )));
        $expected->addGetterConstraint('lastName', new NotNull());

        $this->assertEquals($expected, $metadata);
    }

    public function testLoadClassMetadataWithNonStrings()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping-non-strings.xml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');
        $expected->addPropertyConstraint('firstName', new Regex(array('pattern' => '/^1/', 'match' => false)));

        $properties = $metadata->getPropertyMetadata('firstName');
        $constraints = $properties[0]->getConstraints();

        $this->assertFalse($constraints[0]->match);
    }

    public function testLoadGroupSequenceProvider()
    {
        $loader = new XmlFileLoader(__DIR__.'/constraint-mapping.xml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity');
        $expected->setGroupSequenceProvider(true);

        $this->assertEquals($expected, $metadata);
    }

    /**
     * @expectedException        \Symfony\Component\Validator\Exception\MappingException
     * @expectedExceptionMessage Document types are not allowed.
     */
    public function testDocTypeIsNotAllowed()
    {
        $loader = new XmlFileLoader(__DIR__.'/withdoctype.xml');
        $metadata = new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity');

        $loader->loadClassMetadata($metadata);
    }
}
PK51[�e2~OValidator/Symfony/Component/Validator/Tests/Mapping/Loader/nonvalid-mapping.ymlnu�[���foo
PK51[����YValidator/Symfony/Component/Validator/Tests/Mapping/Loader/AbstractMethodStaticLoader.phpnu�[���<?php

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Mapping\ClassMetadata;

abstract class AbstractMethodStaticLoader
{
    abstract public static function loadMetadata(ClassMetadata $metadata);
}
PK51[F���<<NValidator/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping\Loader;

use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class FilesLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testCallsGetFileLoaderInstanceForeachPath()
    {
        $loader = $this->getFilesLoader($this->getFileLoader());
        $this->assertEquals(4, $loader->getTimesCalled());
    }

    public function testCallsActualFileLoaderForMetadata()
    {
        $fileLoader = $this->getFileLoader();
        $fileLoader->expects($this->exactly(4))
            ->method('loadClassMetadata');
        $loader = $this->getFilesLoader($fileLoader);
        $loader->loadClassMetadata(new ClassMetadata('Symfony\Component\Validator\Tests\Fixtures\Entity'));
    }

    public function getFilesLoader(LoaderInterface $loader)
    {
        return $this->getMockForAbstractClass('Symfony\Component\Validator\Tests\Fixtures\FilesLoader', array(array(
            __DIR__.'/constraint-mapping.xml',
            __DIR__.'/constraint-mapping.yaml',
            __DIR__.'/constraint-mapping.test',
            __DIR__.'/constraint-mapping.txt',
        ), $loader));
    }

    public function getFileLoader()
    {
        return $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
    }
}
PK51[{�d���LValidator/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Mapping\PropertyMetadata;
use Symfony\Component\Validator\Tests\Fixtures\Entity;

class PropertyMetadataTest extends \PHPUnit_Framework_TestCase
{
    const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
    const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';

    public function testInvalidPropertyName()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ValidatorException');

        new PropertyMetadata(self::CLASSNAME, 'foobar');
    }

    public function testGetPropertyValueFromPrivateProperty()
    {
        $entity = new Entity('foobar');
        $metadata = new PropertyMetadata(self::CLASSNAME, 'internal');

        $this->assertEquals('foobar', $metadata->getPropertyValue($entity));
    }

    public function testGetPropertyValueFromOverriddenPrivateProperty()
    {
        $entity = new Entity('foobar');
        $metadata = new PropertyMetadata(self::PARENTCLASS, 'data');

        $this->assertTrue($metadata->isPublic($entity));
        $this->assertEquals('Overridden data', $metadata->getPropertyValue($entity));
    }
}
PK51[��~6�F�FEValidator/Symfony/Component/Validator/Tests/ValidationVisitorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Tests\Fixtures\Reference;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\Tests\Fixtures\FailingConstraint;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintAValidator;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\ValidationVisitor;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ValidationVisitorTest extends \PHPUnit_Framework_TestCase
{
    const CLASS_NAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';

    /**
     * @var ValidationVisitor
     */
    private $visitor;

    /**
     * @var FakeMetadataFactory
     */
    private $metadataFactory;

    /**
     * @var ClassMetadata
     */
    private $metadata;

    protected function setUp()
    {
        $this->metadataFactory = new FakeMetadataFactory();
        $this->visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());
        $this->metadata = new ClassMetadata(self::CLASS_NAME);
        $this->metadataFactory->addMetadata($this->metadata);
    }

    protected function tearDown()
    {
        $this->metadataFactory = null;
        $this->visitor = null;
        $this->metadata = null;
    }

    public function testValidatePassesCorrectClassAndProperty()
    {
        $this->metadata->addConstraint(new ConstraintA());

        $entity = new Entity();
        $this->visitor->validate($entity, 'Default', '');

        $context = ConstraintAValidator::$passedContext;

        $this->assertEquals('Symfony\Component\Validator\Tests\Fixtures\Entity', $context->getClassName());
        $this->assertNull($context->getPropertyName());
    }

    public function testValidateConstraints()
    {
        $this->metadata->addConstraint(new ConstraintA());

        $this->visitor->validate(new Entity(), 'Default', '');

        $this->assertCount(1, $this->visitor->getViolations());
    }

    public function testValidateTwiceValidatesConstraintsOnce()
    {
        $this->metadata->addConstraint(new ConstraintA());

        $entity = new Entity();

        $this->visitor->validate($entity, 'Default', '');
        $this->visitor->validate($entity, 'Default', '');

        $this->assertCount(1, $this->visitor->getViolations());
    }

    public function testValidateDifferentObjectsValidatesTwice()
    {
        $this->metadata->addConstraint(new ConstraintA());

        $this->visitor->validate(new Entity(), 'Default', '');
        $this->visitor->validate(new Entity(), 'Default', '');

        $this->assertCount(2, $this->visitor->getViolations());
    }

    public function testValidateTwiceInDifferentGroupsValidatesTwice()
    {
        $this->metadata->addConstraint(new ConstraintA());
        $this->metadata->addConstraint(new ConstraintA(array('groups' => 'Custom')));

        $entity = new Entity();

        $this->visitor->validate($entity, 'Default', '');
        $this->visitor->validate($entity, 'Custom', '');

        $this->assertCount(2, $this->visitor->getViolations());
    }

    public function testValidatePropertyConstraints()
    {
        $this->metadata->addPropertyConstraint('firstName', new ConstraintA());

        $this->visitor->validate(new Entity(), 'Default', '');

        $this->assertCount(1, $this->visitor->getViolations());
    }

    public function testValidateGetterConstraints()
    {
        $this->metadata->addGetterConstraint('lastName', new ConstraintA());

        $this->visitor->validate(new Entity(), 'Default', '');

        $this->assertCount(1, $this->visitor->getViolations());
    }

    public function testValidateInDefaultGroupTraversesGroupSequence()
    {
        $entity = new Entity();

        $this->metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
            'groups' => 'First',
        )));
        $this->metadata->addGetterConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Default',
        )));
        $this->metadata->setGroupSequence(array('First', $this->metadata->getDefaultGroup()));

        $this->visitor->validate($entity, 'Default', '');

        // After validation of group "First" failed, no more group was
        // validated
        $violations = new ConstraintViolationList(array(
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'firstName',
                ''
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateInGroupSequencePropagatesDefaultGroup()
    {
        $entity = new Entity();
        $entity->reference = new Reference();

        $this->metadata->addPropertyConstraint('reference', new Valid());
        $this->metadata->setGroupSequence(array($this->metadata->getDefaultGroup()));

        $referenceMetadata = new ClassMetadata(get_class($entity->reference));
        $referenceMetadata->addConstraint(new FailingConstraint(array(
                // this constraint is only evaluated if group "Default" is
                // propagated to the reference
                'groups' => 'Default',
            )));
        $this->metadataFactory->addMetadata($referenceMetadata);

        $this->visitor->validate($entity, 'Default', '');

        // The validation of the reference's FailingConstraint in group
        // "Default" was launched
        $violations = new ConstraintViolationList(array(
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference',
                $entity->reference
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateInOtherGroupTraversesNoGroupSequence()
    {
        $entity = new Entity();

        $this->metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
            'groups' => 'First',
        )));
        $this->metadata->addGetterConstraint('lastName', new FailingConstraint(array(
            'groups' => $this->metadata->getDefaultGroup(),
        )));
        $this->metadata->setGroupSequence(array('First', $this->metadata->getDefaultGroup()));

        $this->visitor->validate($entity, $this->metadata->getDefaultGroup(), '');

        // Only group "Second" was validated
        $violations = new ConstraintViolationList(array(
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'lastName',
                ''
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyValidatesReferences()
    {
        $entity = new Entity();
        $entity->reference = new Entity();

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate entity when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        // invoke validation on an object
        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // generated by the reference
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference',
                $entity->reference
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyValidatesArraysByDefault()
    {
        $entity = new Entity();
        $entity->reference = array('key' => new Entity());

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate array when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // generated by the reference
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference[key]',
                $entity->reference['key']
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyValidatesTraversableByDefault()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator(array('key' => new Entity()));

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate array when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // generated by the reference
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference[key]',
                $entity->reference['key']
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyDoesNotValidateTraversableIfDisabled()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator(array('key' => new Entity()));

        $this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate array when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid(array(
            'traverse' => false,
        )));

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // nothing generated by the reference!
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testMetadataMayNotExistIfTraversalIsEnabled()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator();

        $this->metadata->addPropertyConstraint('reference', new Valid(array(
            'traverse' => true,
        )));

        $this->visitor->validate($entity, 'Default', '');
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\NoSuchMetadataException
     */
    public function testMetadataMustExistIfTraversalIsDisabled()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator();

        $this->metadata->addPropertyConstraint('reference', new Valid(array(
            'traverse' => false,
        )));

        $this->visitor->validate($entity, 'Default', '');
    }

    public function testValidateCascadedPropertyDoesNotRecurseByDefault()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator(array(
            // The inner iterator should not be traversed by default
            'key' => new \ArrayIterator(array(
                'nested' => new Entity(),
            )),
        ));

        $this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate iterator when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // nothing generated by the reference!
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    // https://github.com/symfony/symfony/issues/6246
    public function testValidateCascadedPropertyRecursesArraysByDefault()
    {
        $entity = new Entity();
        $entity->reference = array(
            'key' => array(
                'nested' => new Entity(),
            ),
        );

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate iterator when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // nothing generated by the reference!
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference[key][nested]',
                $entity->reference['key']['nested']
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyRecursesIfDeepIsSet()
    {
        $entity = new Entity();
        $entity->reference = new \ArrayIterator(array(
            // The inner iterator should now be traversed
            'key' => new \ArrayIterator(array(
                'nested' => new Entity(),
            )),
        ));

        // add a constraint for the entity that always fails
        $this->metadata->addConstraint(new FailingConstraint());

        // validate iterator when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid(array(
            'deep' => true,
        )));

        $this->visitor->validate($entity, 'Default', '');

        $violations = new ConstraintViolationList(array(
            // generated by the root object
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                '',
                $entity
            ),
            // nothing generated by the reference!
            new ConstraintViolation(
                'Failed',
                'Failed',
                array(),
                'Root',
                'reference[key][nested]',
                $entity->reference['key']['nested']
            ),
        ));

        $this->assertEquals($violations, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyDoesNotValidateNestedScalarValues()
    {
        $entity = new Entity();
        $entity->reference = array('scalar', 'values');

        // validate array when validating the property "reference"
        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $this->assertCount(0, $this->visitor->getViolations());
    }

    public function testValidateCascadedPropertyDoesNotValidateNullValues()
    {
        $entity = new Entity();
        $entity->reference = null;

        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');

        $this->assertCount(0, $this->visitor->getViolations());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\NoSuchMetadataException
     */
    public function testValidateCascadedPropertyRequiresObjectOrArray()
    {
        $entity = new Entity();
        $entity->reference = 'no object';

        $this->metadata->addPropertyConstraint('reference', new Valid());

        $this->visitor->validate($entity, 'Default', '');
    }
}
PK51[K��y'$'$=Validator/Symfony/Component/Validator/Tests/ValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity;
use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Component\Validator\Tests\Fixtures\FailingConstraint;
use Symfony\Component\Validator\Validator;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;

class ValidatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var FakeMetadataFactory
     */
    private $metadataFactory;

    /**
     * @var Validator
     */
    private $validator;

    protected function setUp()
    {
        $this->metadataFactory = new FakeMetadataFactory();
        $this->validator = new Validator($this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());
    }

    protected function tearDown()
    {
        $this->metadataFactory = null;
        $this->validator = null;
    }

    public function testValidateDefaultGroup()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint());
        $metadata->addPropertyConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Custom',
        )));
        $this->metadataFactory->addMetadata($metadata);

        // Only the constraint of group "Default" failed
        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'firstName',
            ''
        ));

        $this->assertEquals($violations, $this->validator->validate($entity));
    }

    public function testValidateOneGroup()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint());
        $metadata->addPropertyConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Custom',
        )));
        $this->metadataFactory->addMetadata($metadata);

        // Only the constraint of group "Custom" failed
        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'lastName',
            ''
        ));

        $this->assertEquals($violations, $this->validator->validate($entity, 'Custom'));
    }

    public function testValidateMultipleGroups()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
            'groups' => 'First',
        )));
        $metadata->addPropertyConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Second',
        )));
        $this->metadataFactory->addMetadata($metadata);

        // The constraints of both groups failed
        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'firstName',
            ''
        ));
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'lastName',
            ''
        ));

        $result = $this->validator->validate($entity, array('First', 'Second'));

        $this->assertEquals($violations, $result);
    }

    public function testValidateGroupSequenceProvider()
    {
        $entity = new GroupSequenceProviderEntity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
            'groups' => 'First',
        )));
        $metadata->addPropertyConstraint('lastName', new FailingConstraint(array(
            'groups' => 'Second',
        )));
        $metadata->setGroupSequenceProvider(true);
        $this->metadataFactory->addMetadata($metadata);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'firstName',
            ''
        ));

        $entity->setGroups(array('First'));
        $result = $this->validator->validate($entity);
        $this->assertEquals($violations, $result);

        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            $entity,
            'lastName',
            ''
        ));

        $entity->setGroups(array('Second'));
        $result = $this->validator->validate($entity);
        $this->assertEquals($violations, $result);

        $entity->setGroups(array());
        $result = $this->validator->validate($entity);
        $this->assertEquals(new ConstraintViolationList(), $result);
    }

    public function testValidateProperty()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint());
        $this->metadataFactory->addMetadata($metadata);

        $result = $this->validator->validateProperty($entity, 'firstName');

        $this->assertCount(1, $result);

        $result = $this->validator->validateProperty($entity, 'lastName');

        $this->assertCount(0, $result);
    }

    public function testValidatePropertyValue()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $metadata->addPropertyConstraint('firstName', new FailingConstraint());
        $this->metadataFactory->addMetadata($metadata);

        $result = $this->validator->validatePropertyValue(get_class($entity), 'firstName', 'Bernhard');

        $this->assertCount(1, $result);
    }

    public function testValidateValue()
    {
        $violations = new ConstraintViolationList();
        $violations->add(new ConstraintViolation(
            'Failed',
            'Failed',
            array(),
            'Bernhard',
            '',
            'Bernhard'
        ));

        $this->assertEquals($violations, $this->validator->validateValue('Bernhard', new FailingConstraint()));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ValidatorException
     */
    public function testValidateValueRejectsValid()
    {
        $entity = new Entity();
        $metadata = new ClassMetadata(get_class($entity));
        $this->metadataFactory->addMetadata($metadata);

        $this->validator->validateValue($entity, new Valid());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ValidatorException
     */
    public function testValidatePropertyFailsIfPropertiesNotSupported()
    {
        // $metadata does not implement PropertyMetadataContainerInterface
        $metadata = $this->getMock('Symfony\Component\Validator\MetadataInterface');
        $this->metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');
        $this->metadataFactory->expects($this->any())
            ->method('getMetadataFor')
            ->with('VALUE')
            ->will($this->returnValue($metadata));
        $this->validator = new Validator($this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());

        $this->validator->validateProperty('VALUE', 'someProperty');
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ValidatorException
     */
    public function testValidatePropertyValueFailsIfPropertiesNotSupported()
    {
        // $metadata does not implement PropertyMetadataContainerInterface
        $metadata = $this->getMock('Symfony\Component\Validator\MetadataInterface');
        $this->metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');
        $this->metadataFactory->expects($this->any())
            ->method('getMetadataFor')
            ->with('VALUE')
            ->will($this->returnValue($metadata));
        $this->validator = new Validator($this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());

        $this->validator->validatePropertyValue('VALUE', 'someProperty', 'propertyValue');
    }

    public function testGetMetadataFactory()
    {
        $this->assertInstanceOf(
            'Symfony\Component\Validator\MetadataFactoryInterface',
            $this->validator->getMetadataFactory()
        );
    }
}
PK51[�P�6�)�)DValidator/Symfony/Component/Validator/Tests/ExecutionContextTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\ValidationVisitor;
use Symfony\Component\Validator\ConstraintValidatorFactory;

class ExecutionContextTest extends \PHPUnit_Framework_TestCase
{
    const TRANS_DOMAIN = 'trans_domain';

    private $visitor;
    private $violations;
    private $metadata;
    private $metadataFactory;
    private $globalContext;
    private $translator;

    /**
     * @var ExecutionContext
     */
    private $context;

    protected function setUp()
    {
        $this->visitor = $this->getMockBuilder('Symfony\Component\Validator\ValidationVisitor')
            ->disableOriginalConstructor()
            ->getMock();
        $this->violations = new ConstraintViolationList();
        $this->metadata = $this->getMock('Symfony\Component\Validator\MetadataInterface');
        $this->metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');
        $this->globalContext = $this->getMock('Symfony\Component\Validator\GlobalExecutionContextInterface');
        $this->globalContext->expects($this->any())
            ->method('getRoot')
            ->will($this->returnValue('Root'));
        $this->globalContext->expects($this->any())
            ->method('getViolations')
            ->will($this->returnValue($this->violations));
        $this->globalContext->expects($this->any())
            ->method('getVisitor')
            ->will($this->returnValue($this->visitor));
        $this->globalContext->expects($this->any())
            ->method('getMetadataFactory')
            ->will($this->returnValue($this->metadataFactory));
        $this->translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
        $this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', 'foo.bar');
    }

    protected function tearDown()
    {
        $this->globalContext = null;
        $this->context = null;
    }

    public function testInit()
    {
        $this->assertCount(0, $this->context->getViolations());
        $this->assertSame('Root', $this->context->getRoot());
        $this->assertSame('foo.bar', $this->context->getPropertyPath());
        $this->assertSame('Group', $this->context->getGroup());
    }

    public function testClone()
    {
        $clone = clone $this->context;

        // Cloning the context keeps the reference to the original violation
        // list. This way we can efficiently duplicate context instances during
        // the validation run and only modify the properties that need to be
        // changed.
        $this->assertSame($this->context->getViolations(), $clone->getViolations());
    }

    public function testAddViolation()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array('foo' => 'bar'))
            ->will($this->returnValue('Translated error'));

        $this->context->addViolation('Error', array('foo' => 'bar'), 'invalid');

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array('foo' => 'bar'),
                'Root',
                'foo.bar',
                'invalid'
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationUsesPreconfiguredValueIfNotPassed()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array())
            ->will($this->returnValue('Translated error'));

        $this->context->addViolation('Error');

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array(),
                'Root',
                'foo.bar',
                'currentValue'
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationUsesPassedNullValue()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array('foo1' => 'bar1'))
            ->will($this->returnValue('Translated error'));
        $this->translator->expects($this->once())
            ->method('transChoice')
            ->with('Choice error', 1, array('foo2' => 'bar2'))
            ->will($this->returnValue('Translated choice error'));

        // passed null value should override preconfigured value "invalid"
        $this->context->addViolation('Error', array('foo1' => 'bar1'), null);
        $this->context->addViolation('Choice error', array('foo2' => 'bar2'), null, 1);

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array('foo1' => 'bar1'),
                'Root',
                'foo.bar',
                null
            ),
            new ConstraintViolation(
                'Translated choice error',
                'Choice error',
                array('foo2' => 'bar2'),
                'Root',
                'foo.bar',
                null,
                1
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationAt()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array('foo' => 'bar'))
            ->will($this->returnValue('Translated error'));

        // override preconfigured property path
        $this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), 'invalid');

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array('foo' => 'bar'),
                'Root',
                'foo.bar.bam.baz',
                'invalid'
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationAtUsesPreconfiguredValueIfNotPassed()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array())
            ->will($this->returnValue('Translated error'));

        $this->context->addViolationAt('bam.baz', 'Error');

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array(),
                'Root',
                'foo.bar.bam.baz',
                'currentValue'
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationAtUsesPassedNullValue()
    {
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('Error', array('foo' => 'bar'))
            ->will($this->returnValue('Translated error'));
        $this->translator->expects($this->once())
            ->method('transChoice')
            ->with('Choice error', 2, array('foo' => 'bar'))
            ->will($this->returnValue('Translated choice error'));

        // passed null value should override preconfigured value "invalid"
        $this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), null);
        $this->context->addViolationAt('bam.baz', 'Choice error', array('foo' => 'bar'), null, 2);

        $this->assertEquals(new ConstraintViolationList(array(
            new ConstraintViolation(
                'Translated error',
                'Error',
                array('foo' => 'bar'),
                'Root',
                'foo.bar.bam.baz',
                null
            ),
            new ConstraintViolation(
                'Translated choice error',
                'Choice error',
                array('foo' => 'bar'),
                'Root',
                'foo.bar.bam.baz',
                null,
                2
            ),
        )), $this->context->getViolations());
    }

    public function testAddViolationPluralTranslationError()
    {
        $this->translator->expects($this->once())
            ->method('transChoice')
            ->with('foo')
            ->will($this->throwException(new \InvalidArgumentException()));
        $this->translator->expects($this->once())
            ->method('trans')
            ->with('foo');

        $this->context->addViolation('foo', array(), null, 2);
    }

    public function testGetPropertyPath()
    {
        $this->assertEquals('foo.bar', $this->context->getPropertyPath());
    }

    public function testGetPropertyPathWithIndexPath()
    {
        $this->assertEquals('foo.bar[bam]', $this->context->getPropertyPath('[bam]'));
    }

    public function testGetPropertyPathWithEmptyPath()
    {
        $this->assertEquals('foo.bar', $this->context->getPropertyPath(''));
    }

    public function testGetPropertyPathWithEmptyCurrentPropertyPath()
    {
        $this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', '');

        $this->assertEquals('bam.baz', $this->context->getPropertyPath('bam.baz'));
    }

    public function testGetPropertyPathWithNestedCollectionsMixed()
    {
        $constraints = new Collection(array(
            'foo' => new Collection(array(
                'foo' => new ConstraintA(),
                'bar' => new ConstraintA(),
             )),
            'name' => new ConstraintA()
        ));

        $visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), $this->translator);
        $context = new ExecutionContext($visitor, $this->translator, self::TRANS_DOMAIN);
        $context->validateValue(array('foo' => array('foo' => 'VALID')), $constraints);
        $violations = $context->getViolations();

        $this->assertEquals('[name]', $violations[1]->getPropertyPath());
    }
}

class ExecutionContextTest_TestClass
{
    public $myProperty;
}
PK51[����LValidator/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\AllValidator;

class AllValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new AllValidator();
        $this->validator->initialize($this->context);

        $this->context->expects($this->any())
            ->method('getGroup')
            ->will($this->returnValue('MyGroup'));
    }

    protected function tearDown()
    {
        $this->validator = null;
        $this->context = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new All(new Range(array('min' => 4))));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testThrowsExceptionIfNotTraversable()
    {
        $this->validator->validate('foo.barbar', new All(new Range(array('min' => 4))));
    }

    /**
     * @dataProvider getValidArguments
     */
    public function testWalkSingleConstraint($array)
    {
        $constraint = new Range(array('min' => 4));

        $i = 1;

        foreach ($array as $key => $value) {
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($value, $constraint, '['.$key.']', 'MyGroup');
        }

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($array, new All($constraint));
    }

    /**
     * @dataProvider getValidArguments
     */
    public function testWalkMultipleConstraints($array)
    {
        $constraint1 = new Range(array('min' => 4));
        $constraint2 = new NotNull();

        $constraints = array($constraint1, $constraint2);
        $i = 1;

        foreach ($array as $key => $value) {
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($value, $constraint1, '['.$key.']', 'MyGroup');
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($value, $constraint2, '['.$key.']', 'MyGroup');
        }

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($array, new All($constraints));
    }

    public function getValidArguments()
    {
        return array(
            array(array(5, 6, 7)),
            array(new \ArrayObject(array(5, 6, 7))),
        );
    }
}
PK51[�ĀDDNValidator/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\RegexValidator;

class RegexValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new RegexValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Regex(array('pattern' => '/^[0-9]+$/')));
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Regex(array('pattern' => '/^[0-9]+$/')));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
    }

    /**
     * @dataProvider getValidValues
     */
    public function testValidValues($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
        $this->validator->validate($value, $constraint);
    }

    public function getValidValues()
    {
        return array(
            array(0),
            array('0'),
            array('090909'),
            array(90909),
        );
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value)
    {
        $constraint = new Regex(array(
            'pattern' => '/^[0-9]+$/',
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $value,
            ));

        $this->validator->validate($value, $constraint);
    }

    public function getInvalidValues()
    {
        return array(
            array('abcd'),
            array('090foo'),
        );
    }

    public function testConstraintGetDefaultOption()
    {
        $constraint = new Regex(array(
            'pattern' => '/^[0-9]+$/',
        ));

        $this->assertEquals('pattern', $constraint->getDefaultOption());
    }

    public function testHtmlPatternEscaping()
    {
        $constraint = new Regex(array(
            'pattern' => '/^[0-9]+\/$/',
        ));

        $this->assertEquals('[0-9]+/', $constraint->getHtmlPattern());

        $constraint = new Regex(array(
            'pattern' => '#^[0-9]+\#$#',
        ));

        $this->assertEquals('[0-9]+#', $constraint->getHtmlPattern());
    }

    public function testHtmlPattern()
    {
        // Specified htmlPattern
        $constraint = new Regex(array(
            'pattern' => '/^[a-z]+$/i',
            'htmlPattern' => '[a-zA-Z]+',
        ));
        $this->assertEquals('[a-zA-Z]+', $constraint->getHtmlPattern());

        // Disabled htmlPattern
        $constraint = new Regex(array(
            'pattern' => '/^[a-z]+$/i',
            'htmlPattern' => false,
        ));
        $this->assertNull($constraint->getHtmlPattern());

        // Cannot be converted
        $constraint = new Regex(array(
            'pattern' => '/^[a-z]+$/i',
        ));
        $this->assertNull($constraint->getHtmlPattern());

        // Automatically converted
        $constraint = new Regex(array(
            'pattern' => '/^[a-z]+$/',
        ));
        $this->assertEquals('[a-z]+', $constraint->getHtmlPattern());

        // Automatically converted, adds .*
        $constraint = new Regex(array(
            'pattern' => '/[a-z]+/',
        ));
        $this->assertEquals('.*[a-z]+.*', $constraint->getHtmlPattern());

        // Dropped because of match=false
        $constraint = new Regex(array(
            'pattern' => '/[a-z]+/',
            'match' => false
        ));
        $this->assertNull($constraint->getHtmlPattern());
    }
}
PK51[�Q�XValidator/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\LessThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThanOrEqualValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class LessThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new LessThanOrEqualValidator();
    }

    protected function createConstraint(array $options)
    {
        return new LessThanOrEqual($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(1, 2),
            array(1, 1),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
            array(new \DateTime('2000-01-01'), new \DateTime('2020-01-01')),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)),
            array('a', 'a'),
            array('a', 'z'),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(2, 1, '1', 'integer'),
            array(new \DateTime('2010-01-01'), new \DateTime('2000-01-01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(4), '4', __NAMESPACE__.'\ComparisonTest_Class'),
            array('c', 'b', "'b'", 'string')
        );
    }
}
PK51[�;�55MValidator/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Issn;
use Symfony\Component\Validator\Constraints\IssnValidator;

/**
 * @see https://en.wikipedia.org/wiki/Issn
 */
class IssnValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    public function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new IssnValidator();
        $this->validator->initialize($this->context);
    }

    public function getValidLowerCasedIssn()
    {
        return array(
            array('2162-321x'),
            array('2160-200x'),
            array('1537-453x'),
            array('1937-710x'),
            array('0002-922x'),
            array('1553-345x'),
            array('1553-619x'),
        );
    }

    public function getValidNonHyphenatedIssn()
    {
        return array(
            array('2162321X'),
            array('01896016'),
            array('15744647'),
            array('14350645'),
            array('07174055'),
            array('20905076'),
            array('14401592'),
        );
    }

    public function getFullValidIssn()
    {
        return array(
            array('1550-7416'),
            array('1539-8560'),
            array('2156-5376'),
            array('1119-023X'),
            array('1684-5315'),
            array('1996-0786'),
            array('1684-5374'),
            array('1996-0794'),
        );
    }

    public function getValidIssn()
    {
        return array_merge(
            $this->getValidLowerCasedIssn(),
            $this->getValidNonHyphenatedIssn(),
            $this->getFullValidIssn()
        );
    }

    public function getInvalidFormatedIssn()
    {
        return array(
            array(0),
            array('1539'),
            array('2156-537A')
        );
    }

    public function getInvalidValueIssn()
    {
        return array(
            array('1119-0231'),
            array('1684-5312'),
            array('1996-0783'),
            array('1684-537X'),
            array('1996-0795'),
        );

    }

    public function getInvalidIssn()
    {
        return array_merge(
            $this->getInvalidFormatedIssn(),
            $this->getInvalidValueIssn()
        );
    }

    public function testNullIsValid()
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, $constraint);
    }

    public function testEmptyStringIsValid()
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $constraint = new Issn();
        $this->validator->validate(new \stdClass(), $constraint);
    }

    /**
     * @dataProvider getValidLowerCasedIssn
     */
    public function testCaseSensitiveIssns($issn)
    {
        $constraint = new Issn(array('caseSensitive' => true));
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->message);

        $this->validator->validate($issn, $constraint);
    }

    /**
     * @dataProvider getValidNonHyphenatedIssn
     */
    public function testRequireHyphenIssns($issn)
    {
        $constraint = new Issn(array('requireHyphen' => true));
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->message);

        $this->validator->validate($issn, $constraint);
    }

    /**
     * @dataProvider getValidIssn
     */
    public function testValidIssn($issn)
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($issn, $constraint);
    }

    /**
     * @dataProvider getInvalidFormatedIssn
     */
    public function testInvalidFormatIssn($issn)
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->message);

        $this->validator->validate($issn, $constraint);
    }

    /**
     * @dataProvider getInvalidValueIssn
     */
    public function testInvalidValueIssn($issn)
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->message);

        $this->validator->validate($issn, $constraint);
    }

    /**
     * @dataProvider getInvalidIssn
     */
    public function testInvalidIssn($issn)
    {
        $constraint = new Issn();
        $this->context
            ->expects($this->once())
            ->method('addViolation');

        $this->validator->validate($issn, $constraint);
    }
}
PK51[����K1K1KValidator/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Ip;
use Symfony\Component\Validator\Constraints\IpValidator;

class IpValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new IpValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Ip());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Ip());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Ip());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidValidatorVersion()
    {
        $ip = new Ip(array(
            'version' => 666,
        ));
    }

    /**
     * @dataProvider getValidIpsV4
     */
    public function testValidIpsV4($ip)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($ip, new Ip(array(
            'version' => Ip::V4,
        )));
    }

    public function getValidIpsV4()
    {
        return array(
            array('0.0.0.0'),
            array('10.0.0.0'),
            array('123.45.67.178'),
            array('172.16.0.0'),
            array('192.168.1.0'),
            array('224.0.0.1'),
            array('255.255.255.255'),
            array('127.0.0.0'),
        );
    }

    /**
     * @dataProvider getValidIpsV6
     */
    public function testValidIpsV6($ip)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($ip, new Ip(array(
            'version' => Ip::V6,
        )));
    }

    public function getValidIpsV6()
    {
        return array(
            array('2001:0db8:85a3:0000:0000:8a2e:0370:7334'),
            array('2001:0DB8:85A3:0000:0000:8A2E:0370:7334'),
            array('2001:0Db8:85a3:0000:0000:8A2e:0370:7334'),
            array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
            array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
            array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
            array('fe80:0000:0000:0000:0202:b3ff:fe1e:8329'),
            array('fe80:0:0:0:202:b3ff:fe1e:8329'),
            array('fe80::202:b3ff:fe1e:8329'),
            array('0:0:0:0:0:0:0:0'),
            array('::'),
            array('0::'),
            array('::0'),
            array('0::0'),
            // IPv4 mapped to IPv6
            array('2001:0db8:85a3:0000:0000:8a2e:0.0.0.0'),
            array('::0.0.0.0'),
            array('::255.255.255.255'),
            array('::123.45.67.178'),
        );
    }

    /**
     * @dataProvider getValidIpsAll
     */
    public function testValidIpsAll($ip)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($ip, new Ip(array(
            'version' => Ip::ALL,
        )));
    }

    public function getValidIpsAll()
    {
        return array_merge($this->getValidIpsV4(), $this->getValidIpsV6());
    }

    /**
     * @dataProvider getInvalidIpsV4
     */
    public function testInvalidIpsV4($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V4,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidIpsV4()
    {
        return array(
            array('0'),
            array('0.0'),
            array('0.0.0'),
            array('256.0.0.0'),
            array('0.256.0.0'),
            array('0.0.256.0'),
            array('0.0.0.256'),
            array('-1.0.0.0'),
            array('foobar'),
        );
    }

    /**
     * @dataProvider getInvalidPrivateIpsV4
     */
    public function testInvalidPrivateIpsV4($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V4_NO_PRIV,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPrivateIpsV4()
    {
        return array(
            array('10.0.0.0'),
            array('172.16.0.0'),
            array('192.168.1.0'),
        );
    }

    /**
     * @dataProvider getInvalidReservedIpsV4
     */
    public function testInvalidReservedIpsV4($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V4_NO_RES,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidReservedIpsV4()
    {
        return array(
            array('0.0.0.0'),
            array('224.0.0.1'),
            array('255.255.255.255'),
        );
    }

    /**
     * @dataProvider getInvalidPublicIpsV4
     */
    public function testInvalidPublicIpsV4($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V4_ONLY_PUBLIC,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPublicIpsV4()
    {
        return array_merge($this->getInvalidPrivateIpsV4(), $this->getInvalidReservedIpsV4());
    }

    /**
     * @dataProvider getInvalidIpsV6
     */
    public function testInvalidIpsV6($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V6,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidIpsV6()
    {
        return array(
            array('z001:0db8:85a3:0000:0000:8a2e:0370:7334'),
            array('fe80'),
            array('fe80:8329'),
            array('fe80:::202:b3ff:fe1e:8329'),
            array('fe80::202:b3ff::fe1e:8329'),
            // IPv4 mapped to IPv6
            array('2001:0db8:85a3:0000:0000:8a2e:0370:0.0.0.0'),
            array('::0.0'),
            array('::0.0.0'),
            array('::256.0.0.0'),
            array('::0.256.0.0'),
            array('::0.0.256.0'),
            array('::0.0.0.256'),
        );
    }

    /**
     * @dataProvider getInvalidPrivateIpsV6
     */
    public function testInvalidPrivateIpsV6($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V6_NO_PRIV,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPrivateIpsV6()
    {
        return array(
            array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
            array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
            array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
        );
    }

    /**
     * @dataProvider getInvalidReservedIpsV6
     */
    public function testInvalidReservedIpsV6($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V6_NO_RES,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidReservedIpsV6()
    {
        // Quoting after official filter documentation:
        // "FILTER_FLAG_NO_RES_RANGE = This flag does not apply to IPv6 addresses."
        // Full description: http://php.net/manual/en/filter.filters.flags.php
        return $this->getInvalidIpsV6();
    }

    /**
     * @dataProvider getInvalidPublicIpsV6
     */
    public function testInvalidPublicIpsV6($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::V6_ONLY_PUBLIC,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPublicIpsV6()
    {
        return array_merge($this->getInvalidPrivateIpsV6(), $this->getInvalidReservedIpsV6());
    }

    /**
     * @dataProvider getInvalidIpsAll
     */
    public function testInvalidIpsAll($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::ALL,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidIpsAll()
    {
        return array_merge($this->getInvalidIpsV4(), $this->getInvalidIpsV6());
    }

    /**
     * @dataProvider getInvalidPrivateIpsAll
     */
    public function testInvalidPrivateIpsAll($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::ALL_NO_PRIV,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPrivateIpsAll()
    {
        return array_merge($this->getInvalidPrivateIpsV4(), $this->getInvalidPrivateIpsV6());
    }

    /**
     * @dataProvider getInvalidReservedIpsAll
     */
    public function testInvalidReservedIpsAll($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::ALL_NO_RES,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidReservedIpsAll()
    {
        return array_merge($this->getInvalidReservedIpsV4(), $this->getInvalidReservedIpsV6());
    }

    /**
     * @dataProvider getInvalidPublicIpsAll
     */
    public function testInvalidPublicIpsAll($ip)
    {
        $constraint = new Ip(array(
            'version' => Ip::ALL_ONLY_PUBLIC,
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $ip,
            ));

        $this->validator->validate($ip, $constraint);
    }

    public function getInvalidPublicIpsAll()
    {
        return array_merge($this->getInvalidPublicIpsV4(), $this->getInvalidPublicIpsV6());
    }
}
PK51[�rH���dValidator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

/**
 * This class is a hand written simplified version of PHP native `ArrayObject`
 * class, to show that it behaves differently than the PHP native implementation.
 */
class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable
{
    private $array;

    public function __construct(array $array = null)
    {
        $this->array = $array ?: array();
    }

    public function offsetExists($offset)
    {
        return array_key_exists($offset, $this->array);
    }

    public function offsetGet($offset)
    {
        return $this->array[$offset];
    }

    public function offsetSet($offset, $value)
    {
        if (null === $offset) {
            $this->array[] = $value;
        } else {
            $this->array[$offset] = $value;
        }
    }

    public function offsetUnset($offset)
    {
        unset($this->array[$offset]);
    }

    public function getIterator()
    {
        return new \ArrayIterator($this->array);
    }

    public function count()
    {
        return count($this->array);
    }

    public function serialize()
    {
        return serialize($this->array);
    }

    public function unserialize($serialized)
    {
        $this->array = (array) unserialize((string) $serialized);
    }
}

class CollectionValidatorCustomArrayObjectTest extends CollectionValidatorTest
{
    public function prepareTestData(array $contents)
    {
        return new CustomArrayObject($contents);
    }
}
PK51[�GRf��PValidator/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\NotNullValidator;

class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new NotNullValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    /**
     * @dataProvider getValidValues
     */
    public function testValidValues($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($value, new NotNull());
    }

    public function getValidValues()
    {
        return array(
            array(0),
            array(false),
            array(true),
            array(''),
        );
    }

    public function testNullIsInvalid()
    {
        $constraint = new NotNull(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
            ));

        $this->validator->validate(null, $constraint);
    }
}
PK51[���I��JValidator/Symfony/Component/Validator/Tests/Constraints/CollectionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\Required;
use Symfony\Component\Validator\Constraints\Optional;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Valid;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CollectionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectInvalidFieldsOption()
    {
        new Collection(array(
            'fields' => 'foo',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectNonConstraints()
    {
        new Collection(array(
            'foo' => 'bar',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectValidConstraint()
    {
        new Collection(array(
            'foo' => new Valid(),
        ));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectValidConstraintWithinOptional()
    {
        new Collection(array(
            'foo' => new Optional(new Valid()),
        ));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectValidConstraintWithinRequired()
    {
        new Collection(array(
            'foo' => new Required(new Valid()),
        ));
    }

    public function testAcceptOptionalConstraintAsOneElementArray()
    {
        $collection1 = new Collection(array(
            "fields" => array(
                "alternate_email" => array(
                    new Optional(new Email()),
                ),
            ),
        ));

        $collection2 = new Collection(array(
            "fields" => array(
                "alternate_email" => new Optional(new Email()),
            ),
        ));

        $this->assertEquals($collection1, $collection2);
    }

    public function testAcceptRequiredConstraintAsOneElementArray()
    {
        $collection1 = new Collection(array(
            "fields" => array(
                "alternate_email" => array(
                    new Required(new Email()),
                ),
            ),
        ));

        $collection2 = new Collection(array(
            "fields" => array(
                "alternate_email" => new Required(new Email()),
            ),
        ));

        $this->assertEquals($collection1, $collection2);
    }
}
PK51[���W��SValidator/Symfony/Component/Validator/Tests/Constraints/FileValidatorObjectTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\HttpFoundation\File\File;

class FileValidatorObjectTest extends FileValidatorTest
{
    protected function getFile($filename)
    {
        return new File($filename);
    }
}
PK51[s{*pQQMValidator/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\True;
use Symfony\Component\Validator\Constraints\TrueValidator;

class TrueValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new TrueValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new True());
    }

    public function testTrueIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(true, new True());
    }

    public function testFalseIsInvalid()
    {
        $constraint = new True(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
            ));

        $this->validator->validate(false, $constraint);
    }
}
PK51[�|�++RValidator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gifnu�[���GIF89a�������!�
,L
;PK51[J��++SValidator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gifnu�[���GIF89a�������!�
,L
;PK51[Ѝ��!!IValidator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test.gifnu�[���GIF89a����,;PK51[)m�ROValidator/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\LengthValidator;

class LengthValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new LengthValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Length(6));
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Length(6));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Length(5));
    }

    public function getThreeOrLessCharacters()
    {
        return array(
            array(12),
            array('12'),
            array('üü', true),
            array('éé', true),
            array(123),
            array('123'),
            array('üüü', true),
            array('ééé', true),
        );
    }

    public function getFourCharacters()
    {
        return array(
            array(1234),
            array('1234'),
            array('üüüü', true),
            array('éééé', true),
        );
    }

    public function getNotFourCharacters()
    {
        return array_merge(
            $this->getThreeOrLessCharacters(),
            $this->getFiveOrMoreCharacters()
        );
    }

    public function getFiveOrMoreCharacters()
    {
        return array(
            array(12345),
            array('12345'),
            array('üüüüü', true),
            array('ééééé', true),
            array(123456),
            array('123456'),
            array('üüüüüü', true),
            array('éééééé', true),
        );
    }

    /**
     * @dataProvider getFiveOrMoreCharacters
     */
    public function testValidValuesMin($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Length(array('min' => 5));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getThreeOrLessCharacters
     */
    public function testValidValuesMax($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Length(array('max' => 3));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getFourCharacters
     */
    public function testValidValuesExact($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Length(4);
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getThreeOrLessCharacters
     */
    public function testInvalidValuesMin($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $constraint = new Length(array(
            'min' => 4,
            'minMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ value }}' => (string) $value,
                '{{ limit }}' => 4,
            )), $this->identicalTo($value), 4);

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getFiveOrMoreCharacters
     */
    public function testInvalidValuesMax($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $constraint = new Length(array(
            'max' => 4,
            'maxMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ value }}' => (string) $value,
                '{{ limit }}' => 4,
            )), $this->identicalTo($value), 4);

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getNotFourCharacters
     */
    public function testInvalidValuesExact($value, $mbOnly = false)
    {
        if ($mbOnly && !function_exists('mb_strlen')) {
            $this->markTestSkipped('mb_strlen does not exist');
        }

        $constraint = new Length(array(
            'min' => 4,
            'max' => 4,
            'exactMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ value }}' => (string) $value,
                '{{ limit }}' => 4,
            )), $this->identicalTo($value), 4);

        $this->validator->validate($value, $constraint);
    }

    public function testConstraintGetDefaultOption()
    {
        $constraint = new Length(5);

        $this->assertEquals(5, $constraint->min);
        $this->assertEquals(5, $constraint->max);
    }
}
PK51[��̈́
�
OValidator/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Locale;
use Symfony\Component\Validator\Constraints\LocaleValidator;

class LocaleValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new LocaleValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Locale());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Locale());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Locale());
    }

    /**
     * @dataProvider getValidLocales
     */
    public function testValidLocales($locale)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($locale, new Locale());
    }

    public function getValidLocales()
    {
        return array(
            array('en'),
            array('en_US'),
            array('pt'),
            array('pt_PT'),
            array('zh_Hans'),
        );
    }

    /**
     * @dataProvider getInvalidLocales
     */
    public function testInvalidLocales($locale)
    {
        $constraint = new Locale(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $locale,
            ));

        $this->validator->validate($locale, $constraint);
    }

    public function getInvalidLocales()
    {
        return array(
            array('EN'),
            array('foobar'),
        );
    }
}
PK51[�s�VVSValidator/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\NotEqualTo;
use Symfony\Component\Validator\Constraints\NotEqualToValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class NotEqualToValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new NotEqualToValidator();
    }

    protected function createConstraint(array $options)
    {
        return new NotEqualTo($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(1, 2),
            array('22', '333'),
            array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01')),
            array(new ComparisonTest_Class(6), new ComparisonTest_Class(5)),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(3, 3, '3', 'integer'),
            array('2', 2, '2', 'integer'),
            array('a', 'a', "'a'", 'string'),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
        );
    }
}
PK51[���8w
w
NValidator/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;

class EmailValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new EmailValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Email());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Email());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Email());
    }

    /**
     * @dataProvider getValidEmails
     */
    public function testValidEmails($email)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($email, new Email());
    }

    public function getValidEmails()
    {
        return array(
            array('fabien@symfony.com'),
            array('example@example.co.uk'),
            array('fabien_potencier@example.fr'),
        );
    }

    /**
     * @dataProvider getInvalidEmails
     */
    public function testInvalidEmails($email)
    {
        $constraint = new Email(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $email,
            ));

        $this->validator->validate($email, $constraint);
    }

    public function getInvalidEmails()
    {
        return array(
            array('example'),
            array('example@'),
            array('example@localhost'),
            array('example@example.com@example.com'),
        );
    }
}
PK61[�w88WValidator/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

class CountValidatorCountableTest_Countable implements \Countable
{
    private $content;

    public function __construct(array $content)
    {
        $this->content = $content;
    }

    public function count()
    {
        return count($this->content);
    }
}

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CountValidatorCountableTest extends CountValidatorTest
{
    protected function createCollection(array $content)
    {
        return new CountValidatorCountableTest_Countable($content);
    }
}
PK61[];XwwNValidator/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Blank;
use Symfony\Component\Validator\Constraints\BlankValidator;

class BlankValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new BlankValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Blank());
    }

    public function testBlankIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Blank());
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value)
    {
        $constraint = new Blank(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $value,
            ));

        $this->validator->validate($value, $constraint);
    }

    public function getInvalidValues()
    {
        return array(
            array('foobar'),
            array(0),
            array(false),
            array(1234),
        );
    }
}
PK61[3�ê�
�
_Validator/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\AbstractComparisonValidator;

class ComparisonTest_Class
{
    protected $value;

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function __toString()
    {
        return (string) $this->value;
    }
}

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
abstract class AbstractComparisonValidatorTestCase extends \PHPUnit_Framework_TestCase
{
    private $validator;
    private $context;

    protected function setUp()
    {
        $this->validator = $this->createValidator();
        $this->context = $this->getMockBuilder('Symfony\Component\Validator\ExecutionContext')
            ->disableOriginalConstructor()
            ->getMock();
        $this->validator->initialize($this->context);
    }

    /**
     * @return AbstractComparisonValidator
     */
    abstract protected function createValidator();

    public function testThrowsConstraintExceptionIfNoValueOrProperty()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        $comparison = $this->createConstraint(array());
        $this->validator->validate('some value', $comparison);
    }

    /**
     * @dataProvider provideValidComparisons
     * @param mixed $dirtyValue
     * @param mixed $comparisonValue
     */
    public function testValidComparisonToValue($dirtyValue, $comparisonValue)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = $this->createConstraint(array('value' => $comparisonValue));

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('property1'));

        $this->validator->validate($dirtyValue, $constraint);
    }

    /**
     * @return array
     */
    abstract public function provideValidComparisons();

    /**
     * @dataProvider provideInvalidComparisons
     * @param mixed  $dirtyValue
     * @param mixed  $comparedValue
     * @param mixed  $comparedValueString
     * @param string $comparedValueType
     */
    public function testInvalidComparisonToValue($dirtyValue, $comparedValue, $comparedValueString, $comparedValueType)
    {
        $constraint = $this->createConstraint(array('value' => $comparedValue));
        $constraint->message = 'Constraint Message';

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('property1'));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Constraint Message', array(
                '{{ value }}' => $comparedValueString,
                '{{ compared_value }}' => $comparedValueString,
                '{{ compared_value_type }}' => $comparedValueType
            ));

        $this->validator->validate($dirtyValue, $constraint);
    }

    /**
     * @return array
     */
    abstract public function provideInvalidComparisons();

    /**
     * @param  array      $options Options for the constraint
     * @return Constraint
     */
    abstract protected function createConstraint(array $options);
}
PK61[7��a��OValidator/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Constraints\ChoiceValidator;

function choice_callback()
{
    return array('foo', 'bar');
}

class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    public static function staticCallback()
    {
        return array('foo', 'bar');
    }

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new ChoiceValidator();
        $this->validator->initialize($this->context);

        $this->context->expects($this->any())
            ->method('getClassName')
            ->will($this->returnValue(__CLASS__));
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectArrayIfMultipleIsTrue()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar'),
            'multiple' => true,
        ));

        $this->validator->validate('asdf', $constraint);
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Choice(array('choices' => array('foo', 'bar'))));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testChoicesOrCallbackExpected()
    {
        $this->validator->validate('foobar', new Choice());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testValidCallbackExpected()
    {
        $this->validator->validate('foobar', new Choice(array('callback' => 'abcd')));
    }

    public function testValidChoiceArray()
    {
        $constraint = new Choice(array('choices' => array('foo', 'bar')));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('bar', $constraint);
    }

    public function testValidChoiceCallbackFunction()
    {
        $constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback'));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('bar', $constraint);
    }

    public function testValidChoiceCallbackClosure()
    {
        $constraint = new Choice(array('callback' => function () {
            return array('foo', 'bar');
        }));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('bar', $constraint);
    }

    public function testValidChoiceCallbackStaticMethod()
    {
        $constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback')));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('bar', $constraint);
    }

    public function testValidChoiceCallbackContextMethod()
    {
        $constraint = new Choice(array('callback' => 'staticCallback'));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('bar', $constraint);
    }

    public function testMultipleChoices()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar', 'baz'),
            'multiple' => true,
        ));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(array('baz', 'bar'), $constraint);
    }

    public function testInvalidChoice()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar'),
            'message' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => 'baz',
            ), null, null);

        $this->validator->validate('baz', $constraint);
    }

    public function testInvalidChoiceMultiple()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar'),
            'multipleMessage' => 'myMessage',
            'multiple' => true,
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => 'baz',
            ));

        $this->validator->validate(array('foo', 'baz'), $constraint);
    }

    public function testTooFewChoices()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar', 'moo', 'maa'),
            'multiple' => true,
            'min' => 2,
            'minMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ limit }}' => 2,
            ), null, 2);

        $this->validator->validate(array('foo'), $constraint);
    }

    public function testTooManyChoices()
    {
        $constraint = new Choice(array(
            'choices' => array('foo', 'bar', 'moo', 'maa'),
            'multiple' => true,
            'max' => 2,
            'maxMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ limit }}' => 2,
            ), null, 2);

        $this->validator->validate(array('foo', 'bar', 'moo'), $constraint);
    }

    public function testNonStrict()
    {
        $constraint = new Choice(array(
            'choices' => array(1, 2),
            'strict' => false,
        ));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('2', $constraint);
        $this->validator->validate(2, $constraint);
    }

    public function testStrictAllowsExactValue()
    {
        $constraint = new Choice(array(
            'choices' => array(1, 2),
            'strict' => true,
        ));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(2, $constraint);
    }

    public function testStrictDisallowsDifferentType()
    {
        $constraint = new Choice(array(
            'choices' => array(1, 2),
            'strict' => true,
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => '2',
            ));

        $this->validator->validate('2', $constraint);
    }

    public function testNonStrictWithMultipleChoices()
    {
        $constraint = new Choice(array(
            'choices' => array(1, 2, 3),
            'multiple' => true,
            'strict' => false
        ));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(array('2', 3), $constraint);
    }

    public function testStrictWithMultipleChoices()
    {
        $constraint = new Choice(array(
            'choices' => array(1, 2, 3),
            'multiple' => true,
            'strict' => true,
            'multipleMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => '3',
            ));

        $this->validator->validate(array(2, '3'), $constraint);
    }
}
PK61[�2�(�(MValidator/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\FileValidator;
use Symfony\Component\HttpFoundation\File\UploadedFile;

abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;
    protected $path;
    protected $file;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new FileValidator();
        $this->validator->initialize($this->context);
        $this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest';
        $this->file = fopen($this->path, 'w');
    }

    protected function tearDown()
    {
        fclose($this->file);

        $this->context = null;
        $this->validator = null;
        $this->path = null;
        $this->file = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new File());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new File());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleTypeOrFile()
    {
        $this->validator->validate(new \stdClass(), new File());
    }

    public function testValidFile()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($this->path, new File());
    }

    public function testValidUploadedfile()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $file = new UploadedFile($this->path, 'originalName', null, null, null, true);
        $this->validator->validate($file, new File());
    }

    public function testTooLargeBytes()
    {
        fwrite($this->file, str_repeat('0', 11));

        $constraint = new File(array(
            'maxSize'           => 10,
            'maxSizeMessage'    => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ limit }}'   => '10',
                '{{ size }}'    => '11',
                '{{ suffix }}'  => 'bytes',
                '{{ file }}'    => $this->path,
            ));

        $this->validator->validate($this->getFile($this->path), $constraint);
    }

    public function testTooLargeKiloBytes()
    {
        fwrite($this->file, str_repeat('0', 1400));

        $constraint = new File(array(
            'maxSize'           => '1k',
            'maxSizeMessage'    => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ limit }}'   => '1',
                '{{ size }}'    => '1.4',
                '{{ suffix }}'  => 'kB',
                '{{ file }}'    => $this->path,
            ));

        $this->validator->validate($this->getFile($this->path), $constraint);
    }

    public function testTooLargeMegaBytes()
    {
        fwrite($this->file, str_repeat('0', 1400000));

        $constraint = new File(array(
            'maxSize'           => '1M',
            'maxSizeMessage'    => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ limit }}'   => '1',
                '{{ size }}'    => '1.4',
                '{{ suffix }}'  => 'MB',
                '{{ file }}'    => $this->path,
            ));

        $this->validator->validate($this->getFile($this->path), $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMaxSize()
    {
        $constraint = new File(array(
            'maxSize' => '1abc',
        ));

        $this->validator->validate($this->path, $constraint);
    }

    public function testValidMimeType()
    {
        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $file
            ->expects($this->once())
            ->method('getPathname')
            ->will($this->returnValue($this->path))
        ;
        $file
            ->expects($this->once())
            ->method('getMimeType')
            ->will($this->returnValue('image/jpg'))
        ;

        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new File(array(
            'mimeTypes' => array('image/png', 'image/jpg'),
        ));

        $this->validator->validate($file, $constraint);
    }

    public function testValidWildcardMimeType()
    {
        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $file
            ->expects($this->once())
            ->method('getPathname')
            ->will($this->returnValue($this->path))
        ;
        $file
            ->expects($this->once())
            ->method('getMimeType')
            ->will($this->returnValue('image/jpg'))
        ;

        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new File(array(
            'mimeTypes' => array('image/*'),
        ));

        $this->validator->validate($file, $constraint);
    }

    public function testInvalidMimeType()
    {
        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $file
            ->expects($this->once())
            ->method('getPathname')
            ->will($this->returnValue($this->path))
        ;
        $file
            ->expects($this->once())
            ->method('getMimeType')
            ->will($this->returnValue('application/pdf'))
        ;

        $constraint = new File(array(
            'mimeTypes' => array('image/png', 'image/jpg'),
            'mimeTypesMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ type }}'    => '"application/pdf"',
                '{{ types }}'   => '"image/png", "image/jpg"',
                '{{ file }}'    => $this->path,
            ));

        $this->validator->validate($file, $constraint);
    }

    public function testInvalidWildcardMimeType()
    {
        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $file
            ->expects($this->once())
            ->method('getPathname')
            ->will($this->returnValue($this->path))
        ;
        $file
            ->expects($this->once())
            ->method('getMimeType')
            ->will($this->returnValue('application/pdf'))
        ;

        $constraint = new File(array(
            'mimeTypes' => array('image/*', 'image/jpg'),
            'mimeTypesMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ type }}'    => '"application/pdf"',
                '{{ types }}'   => '"image/*", "image/jpg"',
                '{{ file }}'    => $this->path,
            ));

        $this->validator->validate($file, $constraint);
    }

    /**
     * @dataProvider uploadedFileErrorProvider
     */
    public function testUploadedFileError($error, $message, array $params = array(), $maxSize = null)
    {
        $file = new UploadedFile('/path/to/file', 'originalName', 'mime', 0, $error);

        $constraint = new File(array(
            $message => 'myMessage',
            'maxSize' => $maxSize
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $params);

        $this->validator->validate($file, $constraint);

    }

    public function uploadedFileErrorProvider()
    {
        $tests = array(
            array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'),
            array(UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'),
            array(UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'),
            array(UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'),
            array(UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'),
            array(UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage'),
        );

        if (class_exists('Symfony\Component\HttpFoundation\File\UploadedFile')) {
            // when no maxSize is specified on constraint, it should use the ini value
            $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
                '{{ limit }}' => UploadedFile::getMaxFilesize(),
                '{{ suffix }}' => 'bytes',
            ));

            // it should use the smaller limitation (maxSize option in this case)
            $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
                '{{ limit }}' => 1,
                '{{ suffix }}' => 'bytes',
            ), '1');

            // it correctly parses the maxSize option and not only uses simple string comparison
            // 1000M should be bigger than the ini value
            $tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
                '{{ limit }}' => UploadedFile::getMaxFilesize(),
                '{{ suffix }}' => 'bytes',
            ), '1000M');
        }

        return $tests;
    }

    abstract protected function getFile($filename);
}
PK61[�����SValidator/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\CardScheme;
use Symfony\Component\Validator\Constraints\CardSchemeValidator;

class CardSchemeValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CardSchemeValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new CardScheme(array('schemes' => array())));
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new CardScheme(array('schemes' => array())));
    }

    /**
     * @dataProvider getValidNumbers
     */
    public function testValidNumbers($scheme, $number)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($number, new CardScheme(array('schemes' => $scheme)));
    }

    /**
     * @dataProvider getInvalidNumbers
     */
    public function testInvalidNumbers($scheme, $number)
    {
        $this->context->expects($this->once())
            ->method('addViolation');

        $this->validator->validate($number, new CardScheme(array('schemes' => $scheme)));
    }

    public function getValidNumbers()
    {
        return array(
            array('AMEX', '378282246310005'),
            array('AMEX', '371449635398431'),
            array('AMEX', '378734493671000'),
            array('AMEX', '347298508610146'),
            array('CHINA_UNIONPAY', '6228888888888888'),
            array('CHINA_UNIONPAY', '62288888888888888'),
            array('CHINA_UNIONPAY', '622888888888888888'),
            array('CHINA_UNIONPAY', '6228888888888888888'),
            array('DINERS', '30569309025904'),
            array('DINERS', '36088894118515'),
            array('DINERS', '38520000023237'),
            array('DISCOVER', '6011111111111117'),
            array('DISCOVER', '6011000990139424'),
            array('INSTAPAYMENT', '6372476031350068'),
            array('INSTAPAYMENT', '6385537775789749'),
            array('INSTAPAYMENT', '6393440808445746'),
            array('JCB', '3530111333300000'),
            array('JCB', '3566002020360505'),
            array('JCB', '213112345678901'),
            array('JCB', '180012345678901'),
            array('LASER', '6304678107004080'),
            array('LASER', '6706440607428128629'),
            array('LASER', '6771656738314582216'),
            array('MAESTRO', '6759744069209'),
            array('MAESTRO', '5020507657408074712'),
            array('MAESTRO', '6759744069209'),
            array('MAESTRO', '6759744069209'),
            array('MASTERCARD', '5555555555554444'),
            array('MASTERCARD', '5105105105105100'),
            array('VISA', '4111111111111111'),
            array('VISA', '4012888888881881'),
            array('VISA', '4222222222222'),
            array(array('AMEX', 'VISA'), '4111111111111111'),
            array(array('AMEX', 'VISA'), '378282246310005'),
            array(array('JCB', 'MASTERCARD'), '5105105105105100'),
            array(array('VISA', 'MASTERCARD'), '5105105105105100'),
        );
    }

    public function getInvalidNumbers()
    {
        return array(
            array('VISA', '42424242424242424242'),
            array('AMEX', '357298508610146'),
            array('DINERS', '31569309025904'),
            array('DINERS', '37088894118515'),
            array('INSTAPAYMENT', '6313440808445746'),
            array('CHINA_UNIONPAY', '622888888888888'),
            array('CHINA_UNIONPAY', '62288888888888888888'),
            array('AMEX', '30569309025904'), // DINERS number
            array('AMEX', 'invalid'), // A string
            array('AMEX', 0), // a lone number
            array('AMEX', '0'), // a lone number
            array('AMEX', '000000000000'), // a lone number
            array('DINERS', '3056930'), // only first part of the number
            array('DISCOVER', '1117'), // only last 4 digits
        );
    }
}
PK61[{r>K��MValidator/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Isbn;
use Symfony\Component\Validator\Constraints\IsbnValidator;

/**
 * @see https://en.wikipedia.org/wiki/Isbn
 */
class IsbnValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    public function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new IsbnValidator();
        $this->validator->initialize($this->context);
    }

    public function getValidIsbn10()
    {
        return array(
            array('2723442284'),
            array('2723442276'),
            array('2723455041'),
            array('2070546810'),
            array('2711858839'),
            array('2756406767'),
            array('2870971648'),
            array('226623854X'),
            array('2851806424'),
            array('0321812700'),
            array('0-45122-5244'),
            array('0-4712-92311'),
        );
    }

    public function getInvalidIsbn10()
    {
        return array(
            array('1234567890'),
            array('987'),
            array('0987656789'),
            array(0),
            array('7-35622-5444'),
            array('0-4X19-92611'),
            array('0_45122_5244'),
            array('2870#971#648'),
        );
    }

    public function getValidIsbn13()
    {
        return array(
            array('978-2723442282'),
            array('978-2723442275'),
            array('978-2723455046'),
            array('978-2070546817'),
            array('978-2711858835'),
            array('978-2756406763'),
            array('978-2870971642'),
            array('978-2266238540'),
            array('978-2851806420'),
            array('978-0321812704'),
            array('978-0451225245'),
            array('978-0471292319'),
        );
    }

    public function getInvalidIsbn13()
    {
        return array(
            array('1234567890'),
            array('987'),
            array('0987656789'),
            array(0),
            array('0-4X19-9261981'),
            array('978-0321513774'),
            array('979-0431225385'),
            array('980-0474292319'),
            array('978_0451225245'),
            array('978#0471292319'),
        );
    }

    public function getValidIsbn()
    {
        return array_merge(
            $this->getValidIsbn10(),
            $this->getValidIsbn13()
        );
    }

    public function getInvalidIsbn()
    {
        return array_merge(
            $this->getInvalidIsbn10(),
            $this->getInvalidIsbn13()
        );
    }

    public function testNullIsValid()
    {
        $constraint = new Isbn(true);
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, $constraint);
    }

    public function testEmptyStringIsValid()
    {
        $constraint = new Isbn(true);
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $constraint = new Isbn(true);
        $this->validator->validate(new \stdClass(), $constraint);
    }

    /**
     * @dataProvider getValidIsbn10
     */
    public function testValidIsbn10($isbn)
    {
        $constraint = new Isbn(array('isbn10' => true));
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($isbn, $constraint);
    }

    /**
     * @dataProvider getInvalidIsbn10
     */
    public function testInvalidIsbn10($isbn)
    {
        $constraint = new Isbn(array('isbn10' => true));
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->isbn10Message);

        $this->validator->validate($isbn, $constraint);
    }

    /**
     * @dataProvider getValidIsbn13
     */
    public function testValidIsbn13($isbn)
    {
        $constraint = new Isbn(array('isbn13' => true));
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($isbn, $constraint);
    }

    /**
     * @dataProvider getInvalidIsbn13
     */
    public function testInvalidIsbn13($isbn)
    {
        $constraint = new Isbn(array('isbn13' => true));
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->isbn13Message);

        $this->validator->validate($isbn, $constraint);
    }

    /**
     * @dataProvider getValidIsbn
     */
    public function testValidIsbn($isbn)
    {
        $constraint = new Isbn(array('isbn10' => true, 'isbn13' => true));
        $this->context
            ->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($isbn, $constraint);
    }

    /**
     * @dataProvider getInvalidIsbn
     */
    public function testInvalidIsbn($isbn)
    {
        $constraint = new Isbn(array('isbn10' => true, 'isbn13' => true));
        $this->context
            ->expects($this->once())
            ->method('addViolation')
            ->with($constraint->bothIsbnMessage);

        $this->validator->validate($isbn, $constraint);
    }
}
PK61[jTL�99PValidator/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints\EqualToValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class EqualToValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new EqualToValidator();
    }

    protected function createConstraint(array $options)
    {
        return new EqualTo($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(3, 3),
            array(3, '3'),
            array('a', 'a'),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(1, 2, '2', 'integer'),
            array('22', '333', "'333'", 'string'),
            array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
        );
    }
}
PK61[�$&��TValidator/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\IdenticalTo;
use Symfony\Component\Validator\Constraints\IdenticalToValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class IdenticalToValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new IdenticalToValidator();
    }

    protected function createConstraint(array $options)
    {
        return new IdenticalTo($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        $date = new \DateTime('2000-01-01');
        $object = new ComparisonTest_Class(2);

        return array(
            array(3, 3),
            array('a', 'a'),
            array($date, $date),
            array($object, $object),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(1, 2, '2', 'integer'),
            array(2, '2', "'2'", 'string'),
            array('22', '333', "'333'", 'string'),
            array(new \DateTime('2001-01-01'), new \DateTime('2001-01-01'), '2001-01-01 00:00:00', 'DateTime'),
            array(new \DateTime('2001-01-01'), new \DateTime('1999-01-01'), '1999-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
        );
    }
}
PK61[��|=��^Validator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorArrayObjectTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

class CollectionValidatorArrayObjectTest extends CollectionValidatorTest
{
    public function prepareTestData(array $contents)
    {
        return new \ArrayObject($contents);
    }
}
PK61[�z0���PValidator/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Country;
use Symfony\Component\Validator\Constraints\CountryValidator;

class CountryValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CountryValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Country());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Country());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Country());
    }

    /**
     * @dataProvider getValidCountries
     */
    public function testValidCountries($country)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($country, new Country());
    }

    public function getValidCountries()
    {
        return array(
            array('GB'),
            array('AT'),
            array('MY'),
        );
    }

    /**
     * @dataProvider getInvalidCountries
     */
    public function testInvalidCountries($country)
    {
        $constraint = new Country(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $country,
            ));

        $this->validator->validate($country, $constraint);
    }

    public function getInvalidCountries()
    {
        return array(
            array('foobar'),
            array('EN'),
        );
    }

    public function testValidateUsingCountrySpecificLocale()
    {
        \Locale::setDefault('en_GB');
        $existingCountry = 'GB';
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($existingCountry, new Country());
    }
}
PK61[�rZccWValidator/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\NotIdenticalTo;
use Symfony\Component\Validator\Constraints\NotIdenticalToValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class NotIdenticalToValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new NotIdenticalToValidator();
    }

    protected function createConstraint(array $options)
    {
        return new NotIdenticalTo($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(1, 2),
            array('2', 2),
            array('22', '333'),
            array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01')),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        $date = new \DateTime('2000-01-01');
        $object = new ComparisonTest_Class(2);

        return array(
            array(3, 3, '3', 'integer'),
            array('a', 'a', "'a'", 'string'),
            array($date, $date, '2000-01-01 00:00:00', 'DateTime'),
            array($object, $object, '2', __NAMESPACE__.'\ComparisonTest_Class'),
        );
    }
}
PK61[�C��NNLValidator/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;

class UrlValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new UrlValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Url());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Url());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Url());
    }

    /**
     * @dataProvider getValidUrls
     */
    public function testValidUrls($url)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($url, new Url());
    }

    public function getValidUrls()
    {
        return array(
            array('http://a.pl'),
            array('http://www.google.com'),
            array('http://www.google.museum'),
            array('https://google.com/'),
            array('https://google.com:80/'),
            array('http://www.example.coop/'),
            array('http://www.test-example.com/'),
            array('http://www.symfony.com/'),
            array('http://symfony.fake/blog/'),
            array('http://symfony.com/?'),
            array('http://symfony.com/search?type=&q=url+validator'),
            array('http://symfony.com/#'),
            array('http://symfony.com/#?'),
            array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'),
            array('http://very.long.domain.name.com/'),
            array('http://127.0.0.1/'),
            array('http://127.0.0.1:80/'),
            array('http://[::1]/'),
            array('http://[::1]:80/'),
            array('http://[1:2:3::4:5:6:7]/'),
            array('http://sãopaulo.com/'),
            array('http://xn--sopaulo-xwa.com/'),
            array('http://sãopaulo.com.br/'),
            array('http://xn--sopaulo-xwa.com.br/'),
            array('http://пример.испытание/'),
            array('http://xn--e1afmkfd.xn--80akhbyknj4f/'),
            array('http://مثال.إختبار/'),
            array('http://xn--mgbh0fb.xn--kgbechtv/'),
            array('http://例子.测试/'),
            array('http://xn--fsqu00a.xn--0zwm56d/'),
            array('http://例子.測試/'),
            array('http://xn--fsqu00a.xn--g6w251d/'),
            array('http://例え.テスト/'),
            array('http://xn--r8jz45g.xn--zckzah/'),
            array('http://مثال.آزمایشی/'),
            array('http://xn--mgbh0fb.xn--hgbk6aj7f53bba/'),
            array('http://실례.테스트/'),
            array('http://xn--9n2bp8q.xn--9t4b11yi5a/'),
            array('http://العربية.idn.icann.org/'),
            array('http://xn--ogb.idn.icann.org/'),
            array('http://xn--e1afmkfd.xn--80akhbyknj4f.xn--e1afmkfd/'),
            array('http://xn--espaa-rta.xn--ca-ol-fsay5a/'),
            array('http://xn--d1abbgf6aiiy.xn--p1ai/'),
            array('http://☎.com/'),
        );
    }

    /**
     * @dataProvider getInvalidUrls
     */
    public function testInvalidUrls($url)
    {
        $constraint = new Url(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $url,
            ));

        $this->validator->validate($url, $constraint);
    }

    public function getInvalidUrls()
    {
        return array(
            array('google.com'),
            array('://google.com'),
            array('http ://google.com'),
            array('http:/google.com'),
            array('http://goog_le.com'),
            array('http://google.com::aa'),
            array('http://google.com:aa'),
            array('http://symfony.com?'),
            array('http://symfony.com#'),
            array('ftp://google.fr'),
            array('faked://google.fr'),
            array('http://127.0.0.1:aa/'),
            array('ftp://[::1]/'),
            array('http://[::1'),
        );
    }

    /**
     * @dataProvider getValidCustomUrls
     */
    public function testCustomProtocolIsValid($url)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Url(array(
            'protocols' => array('ftp', 'file', 'git')
        ));

        $this->validator->validate($url, $constraint);
    }

    public function getValidCustomUrls()
    {
        return array(
            array('ftp://google.com'),
            array('file://127.0.0.1'),
            array('git://[::1]/'),
        );
    }
}
PK61[(�3��EValidator/Symfony/Component/Validator/Tests/Constraints/ValidTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Valid;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ValidTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectGroupsOption()
    {
        new Valid(array('groups' => 'foo'));
    }
}
PK61[���A��QValidator/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Currency;
use Symfony\Component\Validator\Constraints\CurrencyValidator;

class CurrencyValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CurrencyValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Currency());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Currency());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Currency());
    }

    /**
     * @dataProvider getValidCurrencies
     */
    public function testValidCurrencies($currency)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($currency, new Currency());
    }

    /**
     * @dataProvider getValidCurrencies
     **/
    public function testValidCurrenciesWithCountrySpecificLocale($currency)
    {
        \Locale::setDefault('en_GB');
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($currency, new Currency());
    }

    public function getValidCurrencies()
    {
        return array(
            array('EUR'),
            array('USD'),
            array('SIT'),
            array('AUD'),
            array('CAD'),
        );
    }

    /**
     * @dataProvider getInvalidCurrencies
     */
    public function testInvalidCurrencies($currency)
    {
        $constraint = new Currency(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $currency,
            ));

        $this->validator->validate($currency, $constraint);
    }

    public function getInvalidCurrencies()
    {
        return array(
            array('EN'),
            array('foobar'),
        );
    }
}
PK61[B����CValidator/Symfony/Component/Validator/Tests/Constraints/AllTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\Valid;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class AllTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectNonConstraints()
    {
        new All(array(
            'foo',
        ));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testRejectValidConstraint()
    {
        new All(array(
            new Valid(),
        ));
    }
}
PK61[�p�)D
D
MValidator/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Luhn;
use Symfony\Component\Validator\Constraints\LuhnValidator;

class LuhnValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new LuhnValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Luhn());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Luhn());
    }

    /**
     * @dataProvider getValidNumbers
     */
    public function testValidNumbers($number)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($number, new Luhn());
    }

    public function getValidNumbers()
    {
        return array(
            array('42424242424242424242'),
            array('378282246310005'),
            array('371449635398431'),
            array('378734493671000'),
            array('5610591081018250'),
            array('30569309025904'),
            array('38520000023237'),
            array('6011111111111117'),
            array('6011000990139424'),
            array('3530111333300000'),
            array('3566002020360505'),
            array('5555555555554444'),
            array('5105105105105100'),
            array('4111111111111111'),
            array('4012888888881881'),
            array('4222222222222'),
            array('5019717010103742'),
            array('6331101999990016'),
        );
    }

    /**
     * @dataProvider getInvalidNumbers
     */
    public function testInvalidNumbers($number)
    {
        $constraint = new Luhn();

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with($constraint->message);

        $this->validator->validate($number, $constraint);
    }

    public function getInvalidNumbers()
    {
        return array(
            array('1234567812345678'),
            array('4222222222222222'),
            array('0000000000000000'),
        );
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     * @dataProvider getInvalidTypes
     */
    public function testInvalidTypes($number)
    {
        $constraint = new Luhn();

        $this->validator->validate($number, $constraint);
    }

    public function getInvalidTypes()
    {
        return array(
            array(0),
            array(123),
            array(42424242424242424242),
            array(378282246310005),
            array(371449635398431),
        );
    }
}
PK61[��͸�NValidator/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\RangeValidator;

class RangeValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new RangeValidator();
        $this->validator->initialize($this->context);
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Range(array('min' => 10, 'max' => 20)));
    }

    public function getTenToTwenty()
    {
        return array(
            array(10.00001),
            array(19.99999),
            array('10.00001'),
            array('19.99999'),
            array(10),
            array(20),
            array(10.0),
            array(20.0),
        );
    }

    public function getLessThanTen()
    {
        return array(
            array(9.99999),
            array('9.99999'),
            array(5),
            array(1.0),
        );
    }

    public function getMoreThanTwenty()
    {
        return array(
            array(20.000001),
            array('20.000001'),
            array(21),
            array(30.0),
        );
    }

    /**
     * @dataProvider getTenToTwenty
     */
    public function testValidValuesMin($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Range(array('min' => 10));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getTenToTwenty
     */
    public function testValidValuesMax($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Range(array('max' => 20));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getTenToTwenty
     */
    public function testValidValuesMinMax($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Range(array('min' => 10, 'max' => 20));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getLessThanTen
     */
    public function testInvalidValuesMin($value)
    {
        $constraint = new Range(array(
            'min' => 10,
            'minMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ value }}' => $value,
                '{{ limit }}' => 10,
        )));

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getMoreThanTwenty
     */
    public function testInvalidValuesMax($value)
    {
        $constraint = new Range(array(
            'max' => 20,
            'maxMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ value }}' => $value,
                '{{ limit }}' => 20,
            )));

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getMoreThanTwenty
     */
    public function testInvalidValuesCombinedMax($value)
    {
        $constraint = new Range(array(
            'min' => 10,
            'max' => 20,
            'minMessage' => 'myMinMessage',
            'maxMessage' => 'myMaxMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMaxMessage', $this->identicalTo(array(
                '{{ value }}' => $value,
                '{{ limit }}' => 20,
            )));

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getLessThanTen
     */
    public function testInvalidValuesCombinedMin($value)
    {
        $constraint = new Range(array(
            'min' => 10,
            'max' => 20,
            'minMessage' => 'myMinMessage',
            'maxMessage' => 'myMaxMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMinMessage', $this->identicalTo(array(
            '{{ value }}' => $value,
            '{{ limit }}' => 10,
        )));

        $this->validator->validate($value, $constraint);
    }

    public function getInvalidValues()
    {
        return array(
            array(9.999999),
            array(20.000001),
            array('9.999999'),
            array('20.000001'),
            array(new \stdClass()),
        );
    }

    public function testMinMessageIsSet()
    {
        $constraint = new Range(array(
            'min' => 10,
            'max' => 20,
            'minMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => 9,
                '{{ limit }}' => 10,
            ));

        $this->validator->validate(9, $constraint);
    }

    public function testMaxMessageIsSet()
    {
        $constraint = new Range(array(
            'min' => 10,
            'max' => 20,
            'maxMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => 21,
                '{{ limit }}' => 20,
            ));

        $this->validator->validate(21, $constraint);
    }
}
PK61[Q��s(s(QValidator/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\CallbackValidator;

class CallbackValidatorTest_Class
{
    public static function validateCallback($object, ExecutionContext $context)
    {
        $context->addViolation('Callback message', array('{{ value }}' => 'foobar'), 'invalidValue');

        return false;
    }
}

class CallbackValidatorTest_Object
{
    public function validate(ExecutionContext $context)
    {
        $context->addViolation('My message', array('{{ value }}' => 'foobar'), 'invalidValue');

        return false;
    }

    public static function validateStatic($object, ExecutionContext $context)
    {
        $context->addViolation('Static message', array('{{ value }}' => 'baz'), 'otherInvalidValue');

        return false;
    }
}

class CallbackValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CallbackValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Callback(array('foo')));
    }

    public function testSingleMethod()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback('validate');

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testSingleMethodExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array('callback' => 'validate'));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testSingleStaticMethod()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback('validateStatic');

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Static message', array(
                '{{ value }}' => 'baz',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testClosure()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(function ($object, ExecutionContext $context) {
            $context->addViolation('My message', array('{{ value }}' => 'foobar'), 'invalidValue');

            return false;
        });

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testClosureExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(
            'callback' => function ($object, ExecutionContext $context) {
                $context->addViolation('My message', array('{{ value }}' => 'foobar'), 'invalidValue');

                return false;
            },
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testArrayCallable()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(__CLASS__.'_Class', 'validateCallback'));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Callback message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    public function testArrayCallableExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(
            'callback' => array(__CLASS__.'_Class', 'validateCallback'),
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Callback message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testSingleMethodBc()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array('validate'));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testSingleMethodBcExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array('methods' => array('validate')));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testMultipleMethodsBc()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array('validate', 'validateStatic'));

        $this->context->expects($this->at(0))
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));
        $this->context->expects($this->at(1))
            ->method('addViolation')
            ->with('Static message', array(
                '{{ value }}' => 'baz',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testMultipleMethodsBcExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(
            'methods' => array('validate', 'validateStatic'),
        ));

        $this->context->expects($this->at(0))
            ->method('addViolation')
            ->with('My message', array(
                '{{ value }}' => 'foobar',
            ));
        $this->context->expects($this->at(1))
            ->method('addViolation')
            ->with('Static message', array(
                '{{ value }}' => 'baz',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testSingleStaticMethodBc()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(
            array(__CLASS__.'_Class', 'validateCallback')
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Callback message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    // BC with Symfony < 2.4
    public function testSingleStaticMethodBcExplicitName()
    {
        $object = new CallbackValidatorTest_Object();
        $constraint = new Callback(array(
            'methods' => array(array(__CLASS__.'_Class', 'validateCallback')),
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('Callback message', array(
                '{{ value }}' => 'foobar',
            ));

        $this->validator->validate($object, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testExpectValidMethods()
    {
        $object = new CallbackValidatorTest_Object();

        $this->validator->validate($object, new Callback(array('foobar')));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testExpectValidCallbacks()
    {
        $object = new CallbackValidatorTest_Object();

        $this->validator->validate($object, new Callback(array(array('foo', 'bar'))));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testExpectEitherCallbackOrMethods()
    {
        $object = new CallbackValidatorTest_Object();

        $this->validator->validate($object, new Callback(array(
            'callback' => 'validate',
            'methods' => array('validateStatic'),
        )));
    }

    public function testConstraintGetTargets()
    {
        $constraint = new Callback(array('foo'));

        $this->assertEquals('class', $constraint->getTargets());
    }

    // Should succeed. Needed when defining constraints as annotations.
    public function testNoConstructorArguments()
    {
        new Callback();
    }

    public function testAnnotationInvocationSingleValued()
    {
        $constraint = new Callback(array('value' => 'validateStatic'));

        $this->assertEquals(new Callback('validateStatic'), $constraint);
    }

    public function testAnnotationInvocationMultiValued()
    {
        $constraint = new Callback(array('value' => array(__CLASS__.'_Class', 'validateCallback')));

        $this->assertEquals(new Callback(array(__CLASS__.'_Class', 'validateCallback')), $constraint);
    }
}
PK61[@*�VHHMValidator/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\DateValidator;

class DateValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new DateValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Date());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Date());
    }

    public function testDateTimeClassIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(new \DateTime(), new Date());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Date());
    }

    /**
     * @dataProvider getValidDates
     */
    public function testValidDates($date)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($date, new Date());
    }

    public function getValidDates()
    {
        return array(
            array('2010-01-01'),
            array('1955-12-12'),
            array('2030-05-31'),
        );
    }

    /**
     * @dataProvider getInvalidDates
     */
    public function testInvalidDates($date)
    {
        $constraint = new Date(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $date,
            ));

        $this->validator->validate($date, $constraint);
    }

    public function getInvalidDates()
    {
        return array(
            array('foobar'),
            array('foobar 2010-13-01'),
            array('2010-13-01 foobar'),
            array('2010-13-01'),
            array('2010-04-32'),
            array('2010-02-29'),
        );
    }
}
PK61[�� BTTMValidator/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Time;
use Symfony\Component\Validator\Constraints\TimeValidator;

class TimeValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new TimeValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Time());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Time());
    }

    public function testDateTimeClassIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(new \DateTime(), new Time());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Time());
    }

    /**
     * @dataProvider getValidTimes
     */
    public function testValidTimes($time)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($time, new Time());
    }

    public function getValidTimes()
    {
        return array(
            array('01:02:03'),
            array('00:00:00'),
            array('23:59:59'),
        );
    }

    /**
     * @dataProvider getInvalidTimes
     */
    public function testInvalidTimes($time)
    {
        $constraint = new Time(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $time,
            ));

        $this->validator->validate($time, $constraint);
    }

    public function getInvalidTimes()
    {
        return array(
            array('foobar'),
            array('foobar 12:34:56'),
            array('12:34:56 foobar'),
            array('00:00'),
            array('24:00:00'),
            array('00:60:00'),
            array('00:00:60'),
        );
    }
}
PK61[�i�KKNValidator/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\False;
use Symfony\Component\Validator\Constraints\FalseValidator;

class FalseValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new FalseValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new False());
    }

    public function testFalseIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(false, new False());
    }

    public function testTrueIsInvalid()
    {
        $constraint = new False(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array());

        $this->validator->validate(true, $constraint);
    }
}
PK71[Ϗ�R��SValidator/Symfony/Component/Validator/Tests/Constraints/CountValidatorArrayTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CountValidatorArrayTest extends CountValidatorTest
{
    protected function createCollection(array $content)
    {
        return $content;
    }
}
PK71[qC����QValidator/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Language;
use Symfony\Component\Validator\Constraints\LanguageValidator;

class LanguageValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        IntlTestHelper::requireIntl($this);

        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new LanguageValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Language());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Language());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new Language());
    }

    /**
     * @dataProvider getValidLanguages
     */
    public function testValidLanguages($language)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($language, new Language());
    }

    public function getValidLanguages()
    {
        return array(
            array('en'),
            array('en_US'),
            array('my'),
        );
    }

    /**
     * @dataProvider getInvalidLanguages
     */
    public function testInvalidLanguages($language)
    {
        $constraint = new Language(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $language,
            ));

        $this->validator->validate($language, $constraint);
    }

    public function getInvalidLanguages()
    {
        return array(
            array('EN'),
            array('foobar'),
        );
    }

    public function testValidateUsingCountrySpecificLocale()
    {
        \Locale::setDefault('fr_FR');
        $existingLanguage = 'en';
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($existingLanguage, new Language(array(
            'message' => 'aMessage'
        )));
    }
}
PK71[ֆ���NValidator/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Count;
use Symfony\Component\Validator\Constraints\CountValidator;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class CountValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CountValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    abstract protected function createCollection(array $content);

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Count(6));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsCountableType()
    {
        $this->validator->validate(new \stdClass(), new Count(5));
    }

    public function getThreeOrLessElements()
    {
        return array(
            array($this->createCollection(array(1))),
            array($this->createCollection(array(1, 2))),
            array($this->createCollection(array(1, 2, 3))),
            array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3))),
        );
    }

    public function getFourElements()
    {
        return array(
            array($this->createCollection(array(1, 2, 3, 4))),
            array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4))),
        );
    }

    public function getNotFourElements()
    {
        return array_merge(
            $this->getThreeOrLessElements(),
            $this->getFiveOrMoreElements()
        );
    }

    public function getFiveOrMoreElements()
    {
        return array(
            array($this->createCollection(array(1, 2, 3, 4, 5))),
            array($this->createCollection(array(1, 2, 3, 4, 5, 6))),
            array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5))),
        );
    }

    /**
     * @dataProvider getThreeOrLessElements
     */
    public function testValidValuesMax($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Count(array('max' => 3));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getFiveOrMoreElements
     */
    public function testValidValuesMin($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Count(array('min' => 5));
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getFourElements
     */
    public function testValidValuesExact($value)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Count(4);
        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getFiveOrMoreElements
     */
    public function testInvalidValuesMax($value)
    {
        $constraint = new Count(array(
            'max' => 4,
            'maxMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ count }}' => count($value),
                '{{ limit }}' => 4,
            )), $value, 4);

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getThreeOrLessElements
     */
    public function testInvalidValuesMin($value)
    {
        $constraint = new Count(array(
            'min' => 4,
            'minMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
                '{{ count }}' => count($value),
                '{{ limit }}' => 4,
            )), $value, 4);

        $this->validator->validate($value, $constraint);
    }

    /**
     * @dataProvider getNotFourElements
     */
    public function testInvalidValuesExact($value)
    {
        $constraint = new Count(array(
            'min' => 4,
            'max' => 4,
            'exactMessage' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', $this->identicalTo(array(
            '{{ count }}' => count($value),
            '{{ limit }}' => 4,
        )), $value, 4);

        $this->validator->validate($value, $constraint);
    }

    public function testDefaultOption()
    {
        $constraint = new Count(5);

        $this->assertEquals(5, $constraint->min);
        $this->assertEquals(5, $constraint->max);
    }
}
PK71[��LwwTValidator/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\GreaterThanValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class GreaterThanValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new GreaterThanValidator();
    }

    protected function createConstraint(array $options)
    {
        return new GreaterThan($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(2, 1),
            array(new \DateTime('2005/01/01'), new \DateTime('2001/01/01')),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(4)),
            array('333', '22'),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(1, 2, '2', 'integer'),
            array(2, 2, '2', 'integer'),
            array(new \DateTime('2000/01/01'), new \DateTime('2005/01/01'), '2005-01-01 00:00:00', 'DateTime'),
            array(new \DateTime('2000/01/01'), new \DateTime('2000/01/01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
            array('22', '333', "'333'", 'string'),
            array('22', '22', "'22'", 'string')
        );
    }
}
PK71[���kkQValidator/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\File;

class FileValidatorPathTest extends FileValidatorTest
{
    protected function getFile($filename)
    {
        return $filename;
    }

    public function testFileNotFound()
    {
        $constraint = new File(array(
            'notFoundMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ file }}' => 'foobar',
            ));

        $this->validator->validate('foobar', $constraint);
    }
}
PK71[׫��[Validator/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqualValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class GreaterThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new GreaterThanOrEqualValidator();
    }

    protected function createConstraint(array $options)
    {
        return new GreaterThanOrEqual($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(3, 2),
            array(1, 1),
            array(new \DateTime('2010/01/01'), new \DateTime('2000/01/01')),
            array(new \DateTime('2000/01/01'), new \DateTime('2000/01/01')),
            array('a', 'a'),
            array('z', 'a'),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(1, 2, '2', 'integer'),
            array(new \DateTime('2000/01/01'), new \DateTime('2005/01/01'), '2005-01-01 00:00:00', 'DateTime'),
            array('b', 'c', "'c'", 'string')
        );
    }
}
PK71[W�@� � MValidator/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Iban;
use Symfony\Component\Validator\Constraints\IbanValidator;

class IbanValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new IbanValidator();
        $this->validator->initialize($this->context);
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())->method('addViolation');

        $this->validator->validate(null, new Iban());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())->method('addViolation');

        $this->validator->validate('', new Iban());
    }

    /**
     * @dataProvider getValidIbans
     */
    public function testValidIbans($iban)
    {
        $this->context->expects($this->never())->method('addViolation');

        $this->validator->validate($iban, new Iban());
    }

    public function getValidIbans()
    {
        return array(
            array('CH9300762011623852957'), // Switzerland without spaces

            //Country list
            //http://www.rbs.co.uk/corporate/international/g0/guide-to-international-business/regulatory-information/iban/iban-example.ashx

            array('AL47 2121 1009 0000 0002 3569 8741'), //Albania
            array('AD12 0001 2030 2003 5910 0100'), //Andorra
            array('AT61 1904 3002 3457 3201'), //Austria
            array('AZ21 NABZ 0000 0000 1370 1000 1944'), //Azerbaijan
            array('BH67 BMAG 0000 1299 1234 56'), //Bahrain
            array('BE62 5100 0754 7061'), //Belgium
            array('BA39 1290 0794 0102 8494'), //Bosnia and Herzegovina
            array('BG80 BNBG 9661 1020 3456 78'), //Bulgaria
            array('HR12 1001 0051 8630 0016 0'), //Croatia
            array('CY17 0020 0128 0000 0012 0052 7600'), //Cyprus
            array('CZ65 0800 0000 1920 0014 5399'), //Czech Republic
            array('DK50 0040 0440 1162 43'), //Denmark
            array('EE38 2200 2210 2014 5685'), //Estonia
            array('FO97 5432 0388 8999 44'), //Faroe Islands
            array('FI21 1234 5600 0007 85'), //Finland
            array('FR14 2004 1010 0505 0001 3M02 606'), //France
            array('GE29 NB00 0000 0101 9049 17'), //Georgia
            array('DE89 3704 0044 0532 0130 00'), //Germany
            array('GI75 NWBK 0000 0000 7099 453'), //Gibraltar
            array('GR16 0110 1250 0000 0001 2300 695'), //Greece
            array('GL56 0444 9876 5432 10'), //Greenland
            array('HU42 1177 3016 1111 1018 0000 0000'), //Hungary
            array('IS14 0159 2600 7654 5510 7303 39'), //Iceland
            array('IE29 AIBK 9311 5212 3456 78'), //Ireland
            array('IL62 0108 0000 0009 9999 999'), //Israel
            array('IT40 S054 2811 1010 0000 0123 456'), //Italy
            array('LV80 BANK 0000 4351 9500 1'), //Latvia
            array('LB62 0999 0000 0001 0019 0122 9114'), //Lebanon
            array('LI21 0881 0000 2324 013A A'), //Liechtenstein
            array('LT12 1000 0111 0100 1000'), //Lithuania
            array('LU28 0019 4006 4475 0000'), //Luxembourg
            array('MK072 5012 0000 0589 84'), //Macedonia
            array('MT84 MALT 0110 0001 2345 MTLC AST0 01S'), //Malta
            array('MU17 BOMM 0101 1010 3030 0200 000M UR'), //Mauritius
            array('MD24 AG00 0225 1000 1310 4168'), //Moldova
            array('MC93 2005 2222 1001 1223 3M44 555'), //Monaco
            array('ME25 5050 0001 2345 6789 51'), //Montenegro
            array('NL39 RABO 0300 0652 64'), //Netherlands
            array('NO93 8601 1117 947'), //Norway
            array('PK36 SCBL 0000 0011 2345 6702'), //Pakistan
            array('PL60 1020 1026 0000 0422 7020 1111'), //Poland
            array('PT50 0002 0123 1234 5678 9015 4'), //Portugal
            array('RO49 AAAA 1B31 0075 9384 0000'), //Romania
            array('SM86 U032 2509 8000 0000 0270 100'), //San Marino
            array('SA03 8000 0000 6080 1016 7519'), //Saudi Arabia
            array('RS35 2600 0560 1001 6113 79'), //Serbia
            array('SK31 1200 0000 1987 4263 7541'), //Slovak Republic
            array('SI56 1910 0000 0123 438'), //Slovenia
            array('ES80 2310 0001 1800 0001 2345'), //Spain
            array('SE35 5000 0000 0549 1000 0003'), //Sweden
            array('CH93 0076 2011 6238 5295 7'), //Switzerland
            array('TN59 1000 6035 1835 9847 8831'), //Tunisia
            array('TR33 0006 1005 1978 6457 8413 26'), //Turkey
            array('AE07 0331 2345 6789 0123 456'), //UAE
            array('GB 12 CPBK 0892 9965 0449 91'), //United Kingdom

            //Extended country list
            //http://www.nordea.com/Our+services/International+products+and+services/Cash+Management/IBAN+countries/908462.html
            array('AO06000600000100037131174'), //Angola
            array('AZ21NABZ00000000137010001944'), //Azerbaijan
            array('BH29BMAG1299123456BH00'), //Bahrain
            array('BJ11B00610100400271101192591'), //Benin
            array('VG96VPVG0000012345678901'), //British Virgin Islands
            array('BF1030134020015400945000643'), //Burkina Faso
            array('BI43201011067444'), //Burundi
            array('CM2110003001000500000605306'), //Cameroon
            array('CV64000300004547069110176'), //Cape Verde
            array('FR7630007000110009970004942'), //Central African Republic
            array('CG5230011000202151234567890'), //Congo
            array('CR0515202001026284066'), //Costa Rica
            array('DO28BAGR00000001212453611324'), //Dominican Republic
            array('GT82TRAJ01020000001210029690'), //Guatemala
            array('IR580540105180021273113007'), //Iran
            array('IL620108000000099999999'), //Israel
            array('CI05A00060174100178530011852'), //Ivory Coast
            array('KZ176010251000042993'), //Kazakhstan
            array('KW74NBOK0000000000001000372151'), //Kuwait
            array('LB30099900000001001925579115'), //Lebanon
            array('MG4600005030010101914016056'), //Madagascar
            array('ML03D00890170001002120000447'), //Mali
            array('MR1300012000010000002037372'), //Mauritania
            array('MU17BOMM0101101030300200000MUR'), //Mauritius
            array('MZ59000100000011834194157'), //Mozambique
            array('PS92PALS000000000400123456702'), //Palestinian Territory
            array('PT50000200000163099310355'), //Sao Tome and Principe
            array('SA0380000000608010167519'), //Saudi Arabia
            array('SN12K00100152000025690007542'), //Senegal
            array('TN5914207207100707129648'), //Tunisia
            array('TR330006100519786457841326'), //Turkey
            array('AE260211000000230064016'), //United Arab Emirates
        );
    }

    /**
     * @dataProvider getInvalidIbans
     */
    public function testInvalidIbans($iban)
    {
        $constraint = new Iban(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $iban,
            ));

        $this->validator->validate($iban, $constraint);
    }

    public function getInvalidIbans()
    {
        return array(
            array('CH93 0076 2011 6238 5295'),
            array('CH930076201162385295'),
            array('GB29 RBOS 6016 1331 9268 19'),
            array('CH930072011623852957'),
            array('NL39 RASO 0300 0652 64'),
            array('NO93 8601117 947'),
            array('CY170020 128 0000 0012 0052 7600'),
            array('foo'),
            array('123'),
            array('0750447346'),

            //Ibans with lower case values are invalid
            array('Ae260211000000230064016'),
            array('ae260211000000230064016')
        );
    }
}
PK71[�y7{==MValidator/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Constraints\TypeValidator;

class TypeValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected static $file;

    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new TypeValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Type(array('type' => 'integer')));
    }

    public function testEmptyIsValidIfString()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Type(array('type' => 'string')));
    }

    public function testEmptyIsInvalidIfNoString()
    {
        $this->context->expects($this->once())
            ->method('addViolation');

        $this->validator->validate('', new Type(array('type' => 'integer')));
    }

    /**
     * @dataProvider getValidValues
     */
    public function testValidValues($value, $type)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Type(array('type' => $type));

        $this->validator->validate($value, $constraint);
    }

    public function getValidValues()
    {
        $object = new \stdClass();
        $file = $this->createFile();

        return array(
            array(true, 'Boolean'),
            array(false, 'Boolean'),
            array(true, 'boolean'),
            array(false, 'boolean'),
            array(true, 'bool'),
            array(false, 'bool'),
            array(0, 'numeric'),
            array('0', 'numeric'),
            array(1.5, 'numeric'),
            array('1.5', 'numeric'),
            array(0, 'integer'),
            array(1.5, 'float'),
            array('12345', 'string'),
            array(array(), 'array'),
            array($object, 'object'),
            array($object, 'stdClass'),
            array($file, 'resource'),
            array('12345', 'digit'),
            array('12a34', 'alnum'),
            array('abcde', 'alpha'),
            array("\n\r\t", 'cntrl'),
            array('arf12', 'graph'),
            array('abcde', 'lower'),
            array('ABCDE', 'upper'),
            array('arf12', 'print'),
            array('*&$()', 'punct'),
            array("\n\r\t", 'space'),
            array('AB10BC99', 'xdigit'),
        );
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value, $type, $valueAsString)
    {
        $constraint = new Type(array(
            'type' => $type,
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $valueAsString,
                '{{ type }}' => $type,
            ));

        $this->validator->validate($value, $constraint);
    }

    public function getInvalidValues()
    {
        $object = new \stdClass();
        $file = $this->createFile();

        return array(
            array('foobar', 'numeric', 'foobar'),
            array('foobar', 'boolean', 'foobar'),
            array('0', 'integer', '0'),
            array('1.5', 'float', '1.5'),
            array(12345, 'string', '12345'),
            array($object, 'boolean', 'stdClass'),
            array($object, 'numeric', 'stdClass'),
            array($object, 'integer', 'stdClass'),
            array($object, 'float', 'stdClass'),
            array($object, 'string', 'stdClass'),
            array($object, 'resource', 'stdClass'),
            array($file, 'boolean', (string) $file),
            array($file, 'numeric', (string) $file),
            array($file, 'integer', (string) $file),
            array($file, 'float', (string) $file),
            array($file, 'string', (string) $file),
            array($file, 'object', (string) $file),
            array('12a34', 'digit', '12a34'),
            array('1a#23', 'alnum', '1a#23'),
            array('abcd1', 'alpha', 'abcd1'),
            array("\nabc", 'cntrl', "\nabc"),
            array("abc\n", 'graph', "abc\n"),
            array('abCDE', 'lower', 'abCDE'),
            array('ABcde', 'upper', 'ABcde'),
            array("\nabc", 'print', "\nabc"),
            array('abc&$!', 'punct', 'abc&$!'),
            array("\nabc", 'space', "\nabc"),
            array('AR1012', 'xdigit', 'AR1012'),
        );
    }

    protected function createFile()
    {
        if (!self::$file) {
            self::$file = fopen(__FILE__, 'r');
        }

        return self::$file;
    }

    public static function tearDownAfterClass()
    {
        if (self::$file) {
            fclose(self::$file);
        }
    }
}
PK71[\z?�+�+SValidator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Required;
use Symfony\Component\Validator\Constraints\Optional;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\CollectionValidator;

abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new CollectionValidator();
        $this->validator->initialize($this->context);

        $this->context->expects($this->any())
            ->method('getGroup')
            ->will($this->returnValue('MyGroup'));
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    abstract protected function prepareTestData(array $contents);

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate(null, new Collection(array('fields' => array(
            'foo' => new Range(array('min' => 4)),
        ))));
    }

    public function testFieldsAsDefaultOption()
    {
        $data = $this->prepareTestData(array('foo' => 'foobar'));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'foo' => new Range(array('min' => 4)),
        )));
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testThrowsExceptionIfNotTraversable()
    {
        $this->validator->validate('foobar', new Collection(array('fields' => array(
            'foo' => new Range(array('min' => 4)),
        ))));
    }

    public function testWalkSingleConstraint()
    {
        $constraint = new Range(array('min' => 4));

        $array = array(
            'foo' => 3,
            'bar' => 5,
        );
        $i = 1;

        foreach ($array as $key => $value) {
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($value, $constraint, '['.$key.']', 'MyGroup');
        }

        $data = $this->prepareTestData($array);

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'fields' => array(
                'foo' => $constraint,
                'bar' => $constraint,
            ),
        )));
    }

    public function testWalkMultipleConstraints()
    {
        $constraints = array(
            new Range(array('min' => 4)),
            new NotNull(),
        );

        $array = array(
            'foo' => 3,
            'bar' => 5,
        );
        $i = 1;

        foreach ($array as $key => $value) {
            foreach ($constraints as $constraint) {
                $this->context->expects($this->at($i++))
                    ->method('validateValue')
                    ->with($value, $constraint, '['.$key.']', 'MyGroup');
            }
        }

        $data = $this->prepareTestData($array);

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'fields' => array(
                'foo' => $constraints,
                'bar' => $constraints,
            )
        )));
    }

    public function testExtraFieldsDisallowed()
    {
        $data = $this->prepareTestData(array(
            'foo' => 5,
            'baz' => 6,
        ));

        $this->context->expects($this->once())
            ->method('addViolationAt')
            ->with('[baz]', 'myMessage', array(
                '{{ field }}' => 'baz'
            ));

        $this->validator->validate($data, new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 4)),
            ),
            'extraFieldsMessage' => 'myMessage',
        )));
    }

    // bug fix
    public function testNullNotConsideredExtraField()
    {
        $data = $this->prepareTestData(array(
            'foo' => null,
        ));

        $constraint = new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 4)),
            ),
        ));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, $constraint);
    }

    public function testExtraFieldsAllowed()
    {
        $data = $this->prepareTestData(array(
            'foo' => 5,
            'bar' => 6,
        ));

        $constraint = new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 4)),
            ),
            'allowExtraFields' => true,
        ));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, $constraint);
    }

    public function testMissingFieldsDisallowed()
    {
        $data = $this->prepareTestData(array());

        $constraint = new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 4)),
            ),
            'missingFieldsMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolationAt')
            ->with('[foo]', 'myMessage', array(
                '{{ field }}' => 'foo',
            ));

        $this->validator->validate($data, $constraint);
    }

    public function testMissingFieldsAllowed()
    {
        $data = $this->prepareTestData(array());

        $constraint = new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 4)),
            ),
            'allowMissingFields' => true,
        ));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, $constraint);
    }

    public function testOptionalFieldPresent()
    {
        $data = $this->prepareTestData(array(
            'foo' => null,
        ));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'foo' => new Optional(),
        )));
    }

    public function testOptionalFieldNotPresent()
    {
        $data = $this->prepareTestData(array());

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'foo' => new Optional(),
        )));
    }

    public function testOptionalFieldSingleConstraint()
    {
        $array = array(
            'foo' => 5,
        );

        $constraint = new Range(array('min' => 4));

        $this->context->expects($this->once())
            ->method('validateValue')
            ->with($array['foo'], $constraint, '[foo]', 'MyGroup');

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $data = $this->prepareTestData($array);

        $this->validator->validate($data, new Collection(array(
            'foo' => new Optional($constraint),
        )));
    }

    public function testOptionalFieldMultipleConstraints()
    {
        $array = array(
            'foo' => 5,
        );

        $constraints = array(
            new NotNull(),
            new Range(array('min' => 4)),
        );
        $i = 1;

        foreach ($constraints as $constraint) {
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($array['foo'], $constraint, '[foo]', 'MyGroup');
        }

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $data = $this->prepareTestData($array);

        $this->validator->validate($data, new Collection(array(
            'foo' => new Optional($constraints),
        )));
    }

    public function testRequiredFieldPresent()
    {
        $data = $this->prepareTestData(array(
            'foo' => null,
        ));

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $this->validator->validate($data, new Collection(array(
            'foo' => new Required(),
        )));
    }

    public function testRequiredFieldNotPresent()
    {
        $data = $this->prepareTestData(array());

        $this->context->expects($this->once())
            ->method('addViolationAt')
            ->with('[foo]', 'myMessage', array(
                '{{ field }}' => 'foo',
            ));

        $this->validator->validate($data, new Collection(array(
            'fields' => array(
                'foo' => new Required(),
            ),
            'missingFieldsMessage' => 'myMessage',
        )));
    }

    public function testRequiredFieldSingleConstraint()
    {
        $array = array(
            'foo' => 5,
        );

        $constraint = new Range(array('min' => 4));

        $this->context->expects($this->once())
            ->method('validateValue')
            ->with($array['foo'], $constraint, '[foo]', 'MyGroup');

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $data = $this->prepareTestData($array);

        $this->validator->validate($data, new Collection(array(
            'foo' => new Required($constraint),
        )));
    }

    public function testRequiredFieldMultipleConstraints()
    {
        $array = array(
            'foo' => 5,
        );

        $constraints = array(
            new NotNull(),
            new Range(array('min' => 4)),
        );
        $i = 1;

        foreach ($constraints as $constraint) {
            $this->context->expects($this->at($i++))
                ->method('validateValue')
                ->with($array['foo'], $constraint, '[foo]', 'MyGroup');
        }

        $this->context->expects($this->never())
            ->method('addViolationAt');

        $data = $this->prepareTestData($array);

        $this->validator->validate($array, new Collection(array(
            'foo' => new Required($constraints),
        )));
    }

    public function testObjectShouldBeLeftUnchanged()
    {
        $value = new \ArrayObject(array(
            'foo' => 3
        ));

        $this->validator->validate($value, new Collection(array(
            'fields' => array(
                'foo' => new Range(array('min' => 2)),
            )
        )));

        $this->assertEquals(array(
            'foo' => 3
        ), (array) $value);
    }
}
PK71[C���77QValidator/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\LessThan;
use Symfony\Component\Validator\Constraints\LessThanValidator;

/**
 * @author Daniel Holmes <daniel@danielholmes.org>
 */
class LessThanValidatorTest extends AbstractComparisonValidatorTestCase
{
    protected function createValidator()
    {
        return new LessThanValidator();
    }

    protected function createConstraint(array $options)
    {
        return new LessThan($options);
    }

    /**
     * {@inheritDoc}
     */
    public function provideValidComparisons()
    {
        return array(
            array(1, 2),
            array(new \DateTime('2000-01-01'), new \DateTime('2010-01-01')),
            array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)),
            array('22', '333'),
            array(null, 1),
        );
    }

    /**
     * {@inheritDoc}
     */
    public function provideInvalidComparisons()
    {
        return array(
            array(3, 2, '2', 'integer'),
            array(2, 2, '2', 'integer'),
            array(new \DateTime('2010-01-01'), new \DateTime('2000-01-01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01'), '2000-01-01 00:00:00', 'DateTime'),
            array(new ComparisonTest_Class(5), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
            array(new ComparisonTest_Class(6), new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
            array('333', '22', "'22'", 'string'),
        );
    }
}
PK71[b���ggQValidator/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Validator\Constraints\DateTimeValidator;

class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new DateTimeValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new DateTime());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new DateTime());
    }

    public function testDateTimeClassIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(new \DateTime(), new DateTime());
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
     */
    public function testExpectsStringCompatibleType()
    {
        $this->validator->validate(new \stdClass(), new DateTime());
    }

    /**
     * @dataProvider getValidDateTimes
     */
    public function testValidDateTimes($dateTime)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($dateTime, new DateTime());
    }

    public function getValidDateTimes()
    {
        return array(
            array('2010-01-01 01:02:03'),
            array('1955-12-12 00:00:00'),
            array('2030-05-31 23:59:59'),
        );
    }

    /**
     * @dataProvider getInvalidDateTimes
     */
    public function testInvalidDateTimes($dateTime)
    {
        $constraint = new DateTime(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $dateTime,
            ));

        $this->validator->validate($dateTime, $constraint);
    }

    public function getInvalidDateTimes()
    {
        return array(
            array('foobar'),
            array('2010-01-01'),
            array('00:00:00'),
            array('2010-01-01 00:00'),
            array('2010-13-01 00:00:00'),
            array('2010-04-32 00:00:00'),
            array('2010-02-29 00:00:00'),
            array('2010-01-01 24:00:00'),
            array('2010-01-01 00:60:00'),
            array('2010-01-01 00:00:60'),
        );
    }
}
PK71[;���,,SValidator/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\ExpressionValidator;

class ExpressionValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new ExpressionValidator(PropertyAccess::createPropertyAccessor());
        $this->validator->initialize($this->context);

        $this->context->expects($this->any())
            ->method('getClassName')
            ->will($this->returnValue(__CLASS__));
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Expression('value == 1'));
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Expression('value == 1'));
    }

    public function testSucceedingExpressionAtObjectLevel()
    {
        $constraint = new Expression('this.property == 1');

        $object = (object) array('property' => '1');

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue(null));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($object, $constraint);
    }

    public function testFailingExpressionAtObjectLevel()
    {
        $constraint = new Expression(array(
            'expression' => 'this.property == 1',
            'message' => 'myMessage',
        ));

        $object = (object) array('property' => '2');

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue(null));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate($object, $constraint);
    }

    public function testSucceedingExpressionAtPropertyLevel()
    {
        $constraint = new Expression('value == this.expected');

        $object = (object) array('expected' => '1');

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getRoot')
            ->will($this->returnValue($object));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('1', $constraint);
    }

    public function testFailingExpressionAtPropertyLevel()
    {
        $constraint = new Expression(array(
            'expression' => 'value == this.expected',
            'message' => 'myMessage',
        ));

        $object = (object) array('expected' => '1');

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getRoot')
            ->will($this->returnValue($object));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate('2', $constraint);
    }

    public function testSucceedingExpressionAtNestedPropertyLevel()
    {
        $constraint = new Expression('value == this.expected');

        $object = (object) array('expected' => '1');
        $root = (object) array('nested' => $object);

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('nested.property'));

        $this->context->expects($this->any())
            ->method('getRoot')
            ->will($this->returnValue($root));

        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('1', $constraint);
    }

    public function testFailingExpressionAtNestedPropertyLevel()
    {
        $constraint = new Expression(array(
            'expression' => 'value == this.expected',
            'message' => 'myMessage',
        ));

        $object = (object) array('expected' => '1');
        $root = (object) array('nested' => $object);

        $this->context->expects($this->any())
            ->method('getPropertyName')
            ->will($this->returnValue('property'));

        $this->context->expects($this->any())
            ->method('getPropertyPath')
            ->will($this->returnValue('nested.property'));

        $this->context->expects($this->any())
            ->method('getRoot')
            ->will($this->returnValue($root));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate('2', $constraint);
    }
}
PK71[�Zf^
^
QValidator/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotBlankValidator;

class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new NotBlankValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    /**
     * @dataProvider getValidValues
     */
    public function testValidValues($date)
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($date, new NotBlank());
    }

    public function getValidValues()
    {
        return array(
            array('foobar'),
            array(0),
            array(0.0),
            array('0'),
            array(1234),
        );
    }

    public function testNullIsInvalid()
    {
        $constraint = new NotBlank(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate(null, $constraint);
    }

    public function testBlankIsInvalid()
    {
        $constraint = new NotBlank(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate('', $constraint);
    }

    public function testFalseIsInvalid()
    {
        $constraint = new NotBlank(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate(false, $constraint);
    }

    public function testEmptyArrayIsInvalid()
    {
        $constraint = new NotBlank(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage');

        $this->validator->validate(array(), $constraint);
    }
}
PK71[}mW��XValidator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorArrayTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

class CollectionValidatorArrayTest extends CollectionValidatorTest
{
    public function prepareTestData(array $contents)
    {
        return $contents;
    }
}
PK71[�r3UUMValidator/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Null;
use Symfony\Component\Validator\Constraints\NullValidator;

class NullValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new NullValidator();
        $this->validator->initialize($this->context);
    }

    protected function tearDown()
    {
        $this->context = null;
        $this->validator = null;
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Null());
    }

    /**
     * @dataProvider getInvalidValues
     */
    public function testInvalidValues($value, $readableValue)
    {
        $constraint = new Null(array(
            'message' => 'myMessage'
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ value }}' => $readableValue,
            ));

        $this->validator->validate($value, $constraint);
    }

    public function getInvalidValues()
    {
        return array(
            array(0, 0),
            array(false, false),
            array(true, true),
            array('', ''),
            array('foo bar', 'foo bar'),
            array(new \DateTime(), 'DateTime'),
            array(array(), 'Array'),
        );
    }
}
PK71[0�h'��NValidator/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Image;
use Symfony\Component\Validator\Constraints\ImageValidator;

class ImageValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected $context;
    protected $validator;
    protected $path;
    protected $image;
    protected $imageLandscape;
    protected $imagePortrait;

    protected function setUp()
    {
        $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
        $this->validator = new ImageValidator();
        $this->validator->initialize($this->context);
        $this->image = __DIR__.'/Fixtures/test.gif';
        $this->imageLandscape = __DIR__.'/Fixtures/test_landscape.gif';
        $this->imagePortrait = __DIR__.'/Fixtures/test_portrait.gif';
    }

    public function testNullIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate(null, new Image());
    }

    public function testEmptyStringIsValid()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate('', new Image());
    }

    public function testValidImage()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $this->validator->validate($this->image, new Image());
    }

    public function testValidSize()
    {
        $this->context->expects($this->never())
            ->method('addViolation');

        $constraint = new Image(array(
            'minWidth' => 1,
            'maxWidth' => 2,
            'minHeight' => 1,
            'maxHeight' => 2,
        ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testWidthTooSmall()
    {
        $constraint = new Image(array(
            'minWidth' => 3,
            'minWidthMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ width }}' => '2',
                '{{ min_width }}' => '3',
            ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testWidthTooBig()
    {
        $constraint = new Image(array(
            'maxWidth' => 1,
            'maxWidthMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ width }}' => '2',
                '{{ max_width }}' => '1',
            ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testHeightTooSmall()
    {
        $constraint = new Image(array(
            'minHeight' => 3,
            'minHeightMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ height }}' => '2',
                '{{ min_height }}' => '3',
            ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testHeightTooBig()
    {
        $constraint = new Image(array(
            'maxHeight' => 1,
            'maxHeightMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ height }}' => '2',
                '{{ max_height }}' => '1',
            ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMinWidth()
    {
        $constraint = new Image(array(
            'minWidth' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMaxWidth()
    {
        $constraint = new Image(array(
            'maxWidth' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMinHeight()
    {
        $constraint = new Image(array(
            'minHeight' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMaxHeight()
    {
        $constraint = new Image(array(
            'maxHeight' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testRatioTooSmall()
    {
        $constraint = new Image(array(
            'minRatio' => 2,
            'minRatioMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ ratio }}' => 1,
                '{{ min_ratio }}' => 2,
            ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testRatioTooBig()
    {
        $constraint = new Image(array(
            'maxRatio' => 0.5,
            'maxRatioMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ ratio }}' => 1,
                '{{ max_ratio }}' => 0.5,
            ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMinRatio()
    {
        $constraint = new Image(array(
            'minRatio' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    /**
     * @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
     */
    public function testInvalidMaxRatio()
    {
        $constraint = new Image(array(
            'maxRatio' => '1abc',
        ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testSquareNotAllowed()
    {
        $constraint = new Image(array(
            'allowSquare' => false,
            'allowSquareMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ width }}' => 2,
                '{{ height }}' => 2,
            ));

        $this->validator->validate($this->image, $constraint);
    }

    public function testLandscapeNotAllowed()
    {
        $constraint = new Image(array(
            'allowLandscape' => false,
            'allowLandscapeMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ width }}' => 2,
                '{{ height }}' => 1,
            ));

        $this->validator->validate($this->imageLandscape, $constraint);
    }

    public function testPortraitNotAllowed()
    {
        $constraint = new Image(array(
            'allowPortrait' => false,
            'allowPortraitMessage' => 'myMessage',
        ));

        $this->context->expects($this->once())
            ->method('addViolation')
            ->with('myMessage', array(
                '{{ width }}' => 1,
                '{{ height }}' => 2,
            ));

        $this->validator->validate($this->imagePortrait, $constraint);
    }
}
PK71[�d��..>Validator/Symfony/Component/Validator/Tests/ConstraintTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Validator\Tests;

use Symfony\Component\Validator\Tests\Fixtures\ClassConstraint;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintC;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintWithValue;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintWithValueAsDefault;

class ConstraintTest extends \PHPUnit_Framework_TestCase
{
    public function testSetProperties()
    {
        $constraint = new ConstraintA(array(
            'property1' => 'foo',
            'property2' => 'bar',
        ));

        $this->assertEquals('foo', $constraint->property1);
        $this->assertEquals('bar', $constraint->property2);
    }

    public function testSetNotExistingPropertyThrowsException()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');

        new ConstraintA(array(
            'foo' => 'bar',
        ));
    }

    public function testMagicPropertiesAreNotAllowed()
    {
        $constraint = new ConstraintA();

        $this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');

        $constraint->foo = 'bar';
    }

    public function testInvalidAndRequiredOptionsPassed()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');

        new ConstraintC(array(
            'option1' => 'default',
            'foo' => 'bar'
        ));
    }

    public function testSetDefaultProperty()
    {
        $constraint = new ConstraintA('foo');

        $this->assertEquals('foo', $constraint->property2);
    }

    public function testSetDefaultPropertyDoctrineStyle()
    {
        $constraint = new ConstraintA(array('value' => 'foo'));

        $this->assertEquals('foo', $constraint->property2);
    }

    public function testSetDefaultPropertyDoctrineStylePlusOtherProperty()
    {
        $constraint = new ConstraintA(array('value' => 'foo', 'property1' => 'bar'));

        $this->assertEquals('foo', $constraint->property2);
        $this->assertEquals('bar', $constraint->property1);
    }

    public function testSetDefaultPropertyDoctrineStyleWhenDefaultPropertyIsNamedValue()
    {
        $constraint = new ConstraintWithValueAsDefault(array('value' => 'foo'));

        $this->assertEquals('foo', $constraint->value);
        $this->assertNull($constraint->property);
    }

    public function testDontSetDefaultPropertyIfValuePropertyExists()
    {
        $constraint = new ConstraintWithValue(array('value' => 'foo'));

        $this->assertEquals('foo', $constraint->value);
        $this->assertNull($constraint->property);
    }

    public function testSetUndefinedDefaultProperty()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');

        new ConstraintB('foo');
    }

    public function testRequiredOptionsMustBeDefined()
    {
        $this->setExpectedException('Symfony\Component\Validator\Exception\MissingOptionsException');

        new ConstraintC();
    }

    public function testRequiredOptionsPassed()
    {
        new ConstraintC(array('option1' => 'default'));
    }

    public function testGroupsAreConvertedToArray()
    {
        $constraint = new ConstraintA(array('groups' => 'Foo'));

        $this->assertEquals(array('Foo'), $constraint->groups);
    }

    public function testAddDefaultGroupAddsGroup()
    {
        $constraint = new ConstraintA(array('groups' => 'Default'));
        $constraint->addImplicitGroupName('Foo');
        $this->assertEquals(array('Default', 'Foo'), $constraint->groups);
    }

    public function testAllowsSettingZeroRequiredPropertyValue()
    {
        $constraint = new ConstraintA(0);
        $this->assertEquals(0, $constraint->property2);
    }

    public function testCanCreateConstraintWithNoDefaultOptionAndEmptyArray()
    {
        new ConstraintB(array());
    }

    public function testGetTargetsCanBeString()
    {
        $constraint = new ClassConstraint();

        $this->assertEquals('class', $constraint->getTargets());
    }

    public function testGetTargetsCanBeArray()
    {
        $constraint = new ConstraintA();

        $this->assertEquals(array('property', 'class'), $constraint->getTargets());
    }
}
PK71[��,Q886Validator/Symfony/Component/Validator/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Validator Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK71[�����FDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Logger;

use Symfony\Bridge\Doctrine\Logger\DbalLogger;

class DbalLoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getLogFixtures
     */
    public function testLog($sql, $params, $logParams)
    {
        $logger = $this->getMock('Psr\\Log\\LoggerInterface');

        $dbalLogger = $this
            ->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
            ->setConstructorArgs(array($logger, null))
            ->setMethods(array('log'))
            ->getMock()
        ;

        $dbalLogger
            ->expects($this->once())
            ->method('log')
            ->with($sql, $logParams)
        ;

        $dbalLogger->startQuery($sql, $params);
    }

    public function getLogFixtures()
    {
        return array(
            array('SQL', null, array()),
            array('SQL', array(), array()),
            array('SQL', array('foo' => 'bar'), array('foo' => 'bar'))
        );
    }

    public function testLogNonUtf8()
    {
        $logger = $this->getMock('Psr\\Log\\LoggerInterface');

        $dbalLogger = $this
            ->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
            ->setConstructorArgs(array($logger, null))
            ->setMethods(array('log'))
            ->getMock()
        ;

        $dbalLogger
            ->expects($this->once())
            ->method('log')
            ->with('SQL', array('utf8' => 'foo', 'nonutf8' => DbalLogger::BINARY_DATA_VALUE))
        ;

        $dbalLogger->startQuery('SQL', array(
            'utf8'    => 'foo',
            'nonutf8' => "\x7F\xFF",
        ));
    }

    public function testLogLongString()
    {
        $logger = $this->getMock('Symfony\\Component\\HttpKernel\\Log\\LoggerInterface');

        $dbalLogger = $this
            ->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
            ->setConstructorArgs(array($logger, null))
            ->setMethods(array('log'))
            ->getMock()
        ;

        $testString = 'abc';

        $shortString = str_pad('', DbalLogger::MAX_STRING_LENGTH, $testString);
        $longString = str_pad('', DbalLogger::MAX_STRING_LENGTH+1, $testString);

        $dbalLogger
            ->expects($this->once())
            ->method('log')
            ->with('SQL', array('short' => $shortString, 'long' => substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6).' [...]'))
        ;

        $dbalLogger->startQuery('SQL', array(
            'short' => $shortString,
            'long'  => $longString,
        ));
    }

    public function testLogUTF8LongString()
    {
        if (!function_exists('mb_detect_encoding')) {
            $this->markTestSkipped('Testing log shortening of utf8 charsets requires the mb_detect_encoding() function.');
        }

        $logger = $this->getMock('Symfony\\Component\\HttpKernel\\Log\\LoggerInterface');

        $dbalLogger = $this
            ->getMockBuilder('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')
            ->setConstructorArgs(array($logger, null))
            ->setMethods(array('log'))
            ->getMock()
        ;

        $testStringArray = array('é', 'á', 'ű', 'ő', 'ú', 'ö', 'ü', 'ó', 'í');
        $testStringCount = count($testStringArray);

        $shortString = '';
        $longString = '';
        for ($i = 1; $i <= DbalLogger::MAX_STRING_LENGTH; $i++) {
            $shortString .= $testStringArray[$i % $testStringCount];
            $longString .= $testStringArray[$i % $testStringCount];
        }
        $longString .= $testStringArray[$i % $testStringCount];

        $dbalLogger
            ->expects($this->once())
            ->method('log')
            ->with('SQL', array('short' => $shortString, 'long' => mb_substr($longString, 0, DbalLogger::MAX_STRING_LENGTH - 6, mb_detect_encoding($longString)).' [...]'))
        ;

        $dbalLogger->startQuery('SQL', array(
                'short' => $shortString,
                'long'  => $longString,
            ));
    }

}
PK71[l;���:DoctrineBridge/Symfony/Bridge/Doctrine/Tests/bootstrap.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

$loader = require __DIR__.'/../vendor/autoload.php';

Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
PK71[1g��KDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleIntIdEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class SingleIntIdEntity
{
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column(type="string", nullable=true) */
    public $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function __toString()
    {
        return (string) $this->name;
    }
}
PK71[I>�[��UDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleIntIdNoToStringEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class SingleIntIdNoToStringEntity
{
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column(type="string", nullable=true) */
    public $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }
}
PK71[�+�88NDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/CompositeIntIdEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class CompositeIntIdEntity
{
    /** @Id @Column(type="integer") */
    protected $id1;

    /** @Id @Column(type="integer") */
    protected $id2;

    /** @Column(type="string") */
    public $name;

    public function __construct($id1, $id2, $name)
    {
        $this->id1 = $id1;
        $this->id2 = $id2;
        $this->name = $name;
    }

    public function __toString()
    {
        return $this->name;
    }
}
PK71[�ͭ��KDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/AssociationEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class AssociationEntity
{
    /**
     * @var int
     * @ORM\Id @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="SingleIntIdEntity")
     * @var \Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity
     */
    public $single;

    /**
     * @ORM\ManyToOne(targetEntity="CompositeIntIdEntity")
     * @ORM\JoinColumns({
     *  @ORM\JoinColumn(name="composite_id1", referencedColumnName="id1"),
     *  @ORM\JoinColumn(name="composite_id2", referencedColumnName="id2")
     * })
     * @var \Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity
     */
    public $composite;
}
PK71[��3IDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/GroupableEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class GroupableEntity
{
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column(type="string", nullable=true) */
    public $name;

    /** @Column(type="string", nullable=true) */
    public $groupName;

    public function __construct($id, $name, $groupName)
    {
        $this->id = $id;
        $this->name = $name;
        $this->groupName = $groupName;
    }
}
PK81[��!��NDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleStringIdEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class SingleStringIdEntity
{
    /** @Id @Column(type="string") */
    protected $id;

    /** @Column(type="string") */
    public $name;

    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

    public function __toString()
    {
        return $this->name;
    }
}
PK81[6i+**ODoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/ContainerAwareFixture.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;

class ContainerAwareFixture implements FixtureInterface, ContainerAwareInterface
{
    public $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {
    }
}
PK81[�m��JDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/DoubleNameEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class DoubleNameEntity
{
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column(type="string") */
    public $name;

    /** @Column(type="string", nullable=true) */
    public $name2;

    public function __construct($id, $name, $name2)
    {
        $this->id = $id;
        $this->name = $name;
        $this->name2 = $name2;
    }
}
PK81[�%b�99QDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/CompositeStringIdEntity.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;

/** @Entity */
class CompositeStringIdEntity
{
    /** @Id @Column(type="string") */
    protected $id1;

    /** @Id @Column(type="string") */
    protected $id2;

    /** @Column(type="string") */
    public $name;

    public function __construct($id1, $id2, $name)
    {
        $this->id1 = $id1;
        $this->id2 = $id2;
        $this->name = $name;
    }

    public function __toString()
    {
        return $this->name;
    }
}
PK81[�'N|qq>DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/User.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Fixtures;

use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\Entity;
use Symfony\Component\Security\Core\User\UserInterface;

/** @Entity */
class User implements UserInterface
{
    /** @Id @Column(type="integer") */
    protected $id1;

    /** @Id @Column(type="integer") */
    protected $id2;

    /** @Column(type="string") */
    public $name;

    public function __construct($id1, $id2, $name)
    {
        $this->id1 = $id1;
        $this->id2 = $id2;
        $this->name = $name;
    }

    public function getRoles()
    {
    }

    public function getPassword()
    {
    }

    public function getSalt()
    {
    }

    public function getUsername()
    {
        return $this->name;
    }

    public function eraseCredentials()
    {
    }

    public function equals(UserInterface $user)
    {
    }
}
PK81[��.���DDoctrineBridge/Symfony/Bridge/Doctrine/Tests/DoctrineOrmTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;

/**
 * Class DoctrineOrmTestCase
 *
 * @deprecated Deprecated as of Symfony 2.4, to be removed in Symfony 3.0.
 *             Use {@link DoctrineTestHelper} instead.
 */
abstract class DoctrineOrmTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @return \Doctrine\ORM\EntityManager
     */
    public static function createTestEntityManager()
    {
        return DoctrineTestHelper::createTestEntityManager();
    }
}
PK81[��۵��PDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form;

use Doctrine\Common\Persistence\Mapping\ClassMetadata;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser;
use Symfony\Component\Form\Guess\Guess;
use Symfony\Component\Form\Guess\ValueGuess;

class DoctrineOrmTypeGuesserTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider requiredProvider
     */
    public function testRequiredGuesser($classMetadata, $expected)
    {
        $this->assertEquals($expected, $this->getGuesser($classMetadata)->guessRequired('TestEntity', 'field'));
    }

    public function requiredProvider()
    {
        $return = array();

        // Simple field, not nullable
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(true));
        $classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(false));

        $return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));

        // Simple field, nullable
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(true));
        $classMetadata->expects($this->once())->method('isNullable')->with('field')->will($this->returnValue(true));

        $return[] = array($classMetadata, new ValueGuess(false, Guess::MEDIUM_CONFIDENCE));

        // One-to-one, nullable (by default)
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(false));
        $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));

        $mapping = array('joinColumns' => array(array()));
        $classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));

        $return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));

        // One-to-one, nullable (explicit)
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(false));
        $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));

        $mapping = array('joinColumns' => array(array('nullable'=>true)));
        $classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));

        $return[] = array($classMetadata, new ValueGuess(false, Guess::HIGH_CONFIDENCE));

        // One-to-one, not nullable
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(false));
        $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(true));

        $mapping = array('joinColumns' => array(array('nullable'=>false)));
        $classMetadata->expects($this->once())->method('getAssociationMapping')->with('field')->will($this->returnValue($mapping));

        $return[] = array($classMetadata, new ValueGuess(true, Guess::HIGH_CONFIDENCE));

        // One-to-many, no clue
        $classMetadata = $this->getMockBuilder('Doctrine\ORM\Mapping\ClassMetadata')->disableOriginalConstructor()->getMock();
        $classMetadata->expects($this->once())->method('hasField')->with('field')->will($this->returnValue(false));
        $classMetadata->expects($this->once())->method('isAssociationWithSingleJoinColumn')->with('field')->will($this->returnValue(false));

        $return[] = array($classMetadata, null);

        return $return;
    }

    private function getGuesser(ClassMetadata $classMetadata)
    {
        $em = $this->getMock('Doctrine\Common\Persistence\ObjectManager');
        $em->expects($this->once())->method('getClassMetaData')->with('TestEntity')->will($this->returnValue($classMetadata));

        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $registry->expects($this->once())->method('getManagers')->will($this->returnValue(array($em)));

        return new DoctrineOrmTypeGuesser($registry);
    }

}
PK81[��`Հ�kDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleStringIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListSingleStringIdTest
{
    public function testGetIndicesForValuesIgnoresNonExistingValues()
    {
        $this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
    }
}
PK81[�'�;�!�!\DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/GenericEntityChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdNoToStringEntity;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Doctrine\ORM\Tools\SchemaTool;

class GenericEntityChoiceListTest extends \PHPUnit_Framework_TestCase
{
    const SINGLE_INT_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';

    const SINGLE_STRING_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity';

    const COMPOSITE_ID_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity';

    const GROUPABLE_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity';

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    protected function setUp()
    {
        if (!class_exists('Symfony\Component\Form\Form')) {
            $this->markTestSkipped('The "Form" component is not available');
        }

        if (!class_exists('Doctrine\DBAL\Platforms\MySqlPlatform')) {
            $this->markTestSkipped('Doctrine DBAL is not available.');
        }

        if (!class_exists('Doctrine\Common\Version')) {
            $this->markTestSkipped('Doctrine Common is not available.');
        }

        if (!class_exists('Doctrine\ORM\EntityManager')) {
            $this->markTestSkipped('Doctrine ORM is not available.');
        }

        $this->em = DoctrineTestHelper::createTestEntityManager();

        $schemaTool = new SchemaTool($this->em);
        $classes = array(
            $this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS),
            $this->em->getClassMetadata(self::SINGLE_STRING_ID_CLASS),
            $this->em->getClassMetadata(self::COMPOSITE_ID_CLASS),
            $this->em->getClassMetadata(self::GROUPABLE_CLASS),
        );

        try {
            $schemaTool->dropSchema($classes);
        } catch (\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }

        parent::setUp();
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em = null;
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\StringCastException
     * @expectedMessage   Entity "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity" passed to the choice field must have a "__toString()" method defined (or you can also override the "property" option).
     */
    public function testEntitiesMustHaveAToStringMethod()
    {
        $entity1 = new SingleIntIdNoToStringEntity(1, 'Foo');
        $entity2 = new SingleIntIdNoToStringEntity(2, 'Bar');

        // Persist for managed state
        $this->em->persist($entity1);
        $this->em->persist($entity2);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::SINGLE_INT_ID_CLASS,
            null,
            null,
            array(
                $entity1,
                $entity2,
            )
        );

        $choiceList->getValues();
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\RuntimeException
     */
    public function testChoicesMustBeManaged()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        // no persist here!

        $choiceList = new EntityChoiceList(
            $this->em,
            self::SINGLE_INT_ID_CLASS,
            'name',
            null,
            array(
                $entity1,
                $entity2,
            )
        );

        // triggers loading -> exception
        $choiceList->getChoices();
    }

    public function testInitExplicitChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        // Persist for managed state
        $this->em->persist($entity1);
        $this->em->persist($entity2);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::SINGLE_INT_ID_CLASS,
            'name',
            null,
            array(
                $entity1,
                $entity2,
            )
        );

        $this->assertSame(array(1 => $entity1, 2 => $entity2), $choiceList->getChoices());
    }

    public function testInitEmptyChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        // Persist for managed state
        $this->em->persist($entity1);
        $this->em->persist($entity2);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::SINGLE_INT_ID_CLASS,
            'name',
            null,
            array()
        );

        $this->assertSame(array(), $choiceList->getChoices());
    }

    public function testInitNestedChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        // Oh yeah, we're persisting with fire now!
        $this->em->persist($entity1);
        $this->em->persist($entity2);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::SINGLE_INT_ID_CLASS,
            'name',
            null,
            array(
                'group1' => array($entity1),
                'group2' => array($entity2),
            ),
            array()
        );

        $this->assertSame(array(1 => $entity1, 2 => $entity2), $choiceList->getChoices());
        $this->assertEquals(array(
            'group1' => array(1 => new ChoiceView($entity1, '1', 'Foo')),
            'group2' => array(2 => new ChoiceView($entity2, '2', 'Bar'))
        ), $choiceList->getRemainingViews());
    }

    public function testGroupByPropertyPath()
    {
        $item1 = new GroupableEntity(1, 'Foo', 'Group1');
        $item2 = new GroupableEntity(2, 'Bar', 'Group1');
        $item3 = new GroupableEntity(3, 'Baz', 'Group2');
        $item4 = new GroupableEntity(4, 'Boo!', null);

        $this->em->persist($item1);
        $this->em->persist($item2);
        $this->em->persist($item3);
        $this->em->persist($item4);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::GROUPABLE_CLASS,
            'name',
            null,
            array(
                $item1,
                $item2,
                $item3,
                $item4,
            ),
            array(),
            'groupName'
        );

        $this->assertEquals(array(1 => $item1, 2 => $item2, 3 => $item3, 4 => $item4), $choiceList->getChoices());
        $this->assertEquals(array(
            'Group1' => array(1 => new ChoiceView($item1, '1', 'Foo'), 2 => new ChoiceView($item2, '2', 'Bar')),
            'Group2' => array(3 => new ChoiceView($item3, '3', 'Baz')),
            4 => new ChoiceView($item4, '4', 'Boo!')
        ), $choiceList->getRemainingViews());
    }

    public function testGroupByInvalidPropertyPathReturnsFlatChoices()
    {
        $item1 = new GroupableEntity(1, 'Foo', 'Group1');
        $item2 = new GroupableEntity(2, 'Bar', 'Group1');

        $this->em->persist($item1);
        $this->em->persist($item2);

        $choiceList = new EntityChoiceList(
            $this->em,
            self::GROUPABLE_CLASS,
            'name',
            null,
            array(
                $item1,
                $item2,
            ),
            array(),
            'child.that.does.not.exist'
        );

        $this->assertEquals(array(
            1 => $item1,
            2 => $item2
        ), $choiceList->getChoices());
    }

    public function testInitShorthandEntityName()
    {
        $item1 = new SingleIntIdEntity(1, 'Foo');
        $item2 = new SingleIntIdEntity(2, 'Bar');

        $this->em->persist($item1);
        $this->em->persist($item2);

        $choiceList = new EntityChoiceList(
            $this->em,
            'SymfonyTestsDoctrine:SingleIntIdEntity'
        );

        $this->assertEquals(array(1, 2), $choiceList->getValuesForChoices(array($item1, $item2)));
        $this->assertEquals(array(1, 2), $choiceList->getIndicesForChoices(array($item1, $item2)));
    }
}
PK81[9&��{DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleStringIdWithQueryBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListSingleStringIdWithQueryBuilderTest extends UnloadedEntityChoiceListSingleStringIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
        $loader = new ORMQueryBuilderLoader($qb);

        return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
    }
}
PK81[b#����hDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListSingleIntIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListTest
{
    protected function getEntityClass()
    {
        return 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createObjects()
    {
        return array(
            new SingleIntIdEntity(-10, 'A'),
            new SingleIntIdEntity(10, 'B'),
            new SingleIntIdEntity(20, 'C'),
            new SingleIntIdEntity(30, 'D'),
        );
    }

    protected function getChoices()
    {
        return array('_10' => $this->obj1, 10 => $this->obj2, 20 => $this->obj3, 30 => $this->obj4);
    }

    protected function getLabels()
    {
        return array('_10' => 'A', 10 => 'B', 20 => 'C', 30 => 'D');
    }

    protected function getValues()
    {
        return array('_10' => '-10', 10 => '10', 20 => '20', 30 => '30');
    }

    protected function getIndices()
    {
        return array('_10', 10, 20, 30);
    }
}
PK81[AGA��xDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleIntIdWithQueryBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListSingleIntIdWithQueryBuilderTest extends UnloadedEntityChoiceListSingleIntIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
        $loader = new ORMQueryBuilderLoader($qb);

        return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
    }
}
PK81[�~h���xDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListCompositeIdWithQueryBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListCompositeIdWithQueryBuilderTest extends UnloadedEntityChoiceListCompositeIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $qb = $this->em->createQueryBuilder()->select('s')->from($this->getEntityClass(), 's');
        $loader = new ORMQueryBuilderLoader($qb);

        return new EntityChoiceList($this->em, $this->getEntityClass(), null, $loader);
    }
}
PK81[�'j��iDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListSingleStringIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class LoadedEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListSingleStringIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $list = parent::createChoiceList();

        // load list
        $list->getChoices();

        return $list;
    }
}
PK81[�0�e��fDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListSingleIntIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class LoadedEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListSingleIntIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $list = parent::createChoiceList();

        // load list
        $list->getChoices();

        return $list;
    }
}
PK81[��V
zzhDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListCompositeIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListCompositeIdTest
{
    public function testGetIndicesForValuesIgnoresNonExistingValues()
    {
        $this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
    }
}
PK81[��*��hDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListCompositeIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListTest
{
    protected function getEntityClass()
    {
        return 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity';
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createObjects()
    {
        return array(
            new CompositeIntIdEntity(10, 11, 'A'),
            new CompositeIntIdEntity(20, 21, 'B'),
            new CompositeIntIdEntity(30, 31, 'C'),
            new CompositeIntIdEntity(40, 41, 'D'),
        );
    }

    protected function getChoices()
    {
        return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => '0', 1 => '1', 2 => '2', 3 => '3');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK81[�n<-	-	ZDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader;
use Symfony\Bridge\Doctrine\Tests\DoctrineOrmTestCase;
use Doctrine\DBAL\Connection;

class ORMQueryBuilderLoaderTest extends DoctrineOrmTestCase
{
    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testItOnlyWorksWithQueryBuilderOrClosure()
    {
        new ORMQueryBuilderLoader(new \stdClass());
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testClosureRequiresTheEntityManager()
    {
        $closure = function () {};

        new ORMQueryBuilderLoader($closure);
    }

    public function testIdentifierTypeIsStringArray()
    {
        $this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity', Connection::PARAM_STR_ARRAY);
    }

    public function testIdentifierTypeIsIntegerArray()
    {
        $this->checkIdentifierType('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', Connection::PARAM_INT_ARRAY);
    }

    protected function checkIdentifierType($classname, $expectedType)
    {
        $em = $this->createTestEntityManager();

        $query = $this->getMockBuilder('QueryMock')
            ->setMethods(array('setParameter', 'getResult', 'getSql', '_doExecute'))
            ->getMock();

        $query->expects($this->once())
            ->method('setParameter')
            ->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(), $expectedType)
            ->will($this->returnValue($query));

        $qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
            ->setConstructorArgs(array($em))
            ->setMethods(array('getQuery'))
            ->getMock();

        $qb->expects($this->once())
            ->method('getQuery')
            ->will($this->returnValue($query));

        $qb->select('e')
            ->from($classname, 'e');

        $loader = new ORMQueryBuilderLoader($qb);
        $loader->getEntitiesByIds('id', array());
    }
}
PK81[�-��1
1
]DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityChoiceList;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Component\Form\Tests\Extension\Core\ChoiceList\AbstractChoiceListTest;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractEntityChoiceListTest extends AbstractChoiceListTest
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    protected $obj1;

    protected $obj2;

    protected $obj3;

    protected $obj4;

    protected function setUp()
    {
        if (!class_exists('Symfony\Component\Form\Form')) {
            $this->markTestSkipped('The "Form" component is not available');
        }

        if (!class_exists('Doctrine\DBAL\Platforms\MySqlPlatform')) {
            $this->markTestSkipped('Doctrine DBAL is not available.');
        }

        if (!class_exists('Doctrine\Common\Version')) {
            $this->markTestSkipped('Doctrine Common is not available.');
        }

        if (!class_exists('Doctrine\ORM\EntityManager')) {
            $this->markTestSkipped('Doctrine ORM is not available.');
        }

        $this->em = DoctrineTestHelper::createTestEntityManager();

        $schemaTool = new SchemaTool($this->em);
        $classes = array($this->em->getClassMetadata($this->getEntityClass()));

        try {
            $schemaTool->dropSchema($classes);
        } catch (\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }

        list($this->obj1, $this->obj2, $this->obj3, $this->obj4) = $this->createObjects();

        $this->em->persist($this->obj1);
        $this->em->persist($this->obj2);
        $this->em->persist($this->obj3);
        $this->em->persist($this->obj4);
        $this->em->flush();

        parent::setUp();
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em = null;
    }

    abstract protected function getEntityClass();

    abstract protected function createObjects();

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        return new EntityChoiceList($this->em, $this->getEntityClass());
    }
}
PK81[c�&zzhDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleIntIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class UnloadedEntityChoiceListSingleIntIdTest extends AbstractEntityChoiceListSingleIntIdTest
{
    public function testGetIndicesForValuesIgnoresNonExistingValues()
    {
        $this->markTestSkipped('Non-existing values are not detected for unloaded choice lists.');
    }
}
PK81[�ǜ"��fDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListCompositeIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class LoadedEntityChoiceListCompositeIdTest extends AbstractEntityChoiceListCompositeIdTest
{
    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createChoiceList()
    {
        $list = parent::createChoiceList();

        // load list
        $list->getChoices();

        return $list;
    }
}
PK81[_UNF��kDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListSingleStringIdTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\ChoiceList;

use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
abstract class AbstractEntityChoiceListSingleStringIdTest extends AbstractEntityChoiceListTest
{
    protected function getEntityClass()
    {
        return 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity';
    }

    /**
     * @return \Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface
     */
    protected function createObjects()
    {
        return array(
            new SingleStringIdEntity('a', 'A'),
            new SingleStringIdEntity('b', 'B'),
            new SingleStringIdEntity('c', 'C'),
            new SingleStringIdEntity('d', 'D'),
        );
    }

    protected function getChoices()
    {
        return array(0 => $this->obj1, 1 => $this->obj2, 2 => $this->obj3, 3 => $this->obj4);
    }

    protected function getLabels()
    {
        return array(0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D');
    }

    protected function getValues()
    {
        return array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd');
    }

    protected function getIndices()
    {
        return array(0, 1, 2, 3);
    }
}
PK91[Yv�:B	B	fDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\DataTransformer;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Form\DataTransformer\CollectionToArrayTransformer;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CollectionToArrayTransformerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var CollectionToArrayTransformer
     */
    private $transformer;

    protected function setUp()
    {
        $this->transformer = new CollectionToArrayTransformer();
    }

    public function testTransform()
    {
        $array = array(
            2 => 'foo',
            3 => 'bar',
        );

        $this->assertSame($array, $this->transformer->transform(new ArrayCollection($array)));
    }

    /**
     * This test is needed for cases when getXxxs() in the entity returns the
     * result of $collection->toArray(), in order to prevent modifications of
     * the inner collection.
     *
     * See https://github.com/symfony/symfony/pull/9308
     */
    public function testTransformArray()
    {
        $array = array(
            2 => 'foo',
            3 => 'bar',
        );

        $this->assertSame($array, $this->transformer->transform($array));
    }

    public function testTransformNull()
    {
        $this->assertSame(array(), $this->transformer->transform(null));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\TransformationFailedException
     */
    public function testTransformExpectsArrayOrCollection()
    {
        $this->transformer->transform('Foo');
    }

    public function testReverseTransform()
    {
        $array = array(
            2 => 'foo',
            3 => 'bar',
        );

        $this->assertEquals(new ArrayCollection($array), $this->transformer->reverseTransform($array));
    }

    public function testReverseTransformEmpty()
    {
        $this->assertEquals(new ArrayCollection(), $this->transformer->reverseTransform(''));
    }

    public function testReverseTransformNull()
    {
        $this->assertEquals(new ArrayCollection(), $this->transformer->reverseTransform(null));
    }
}
PK91[��(iiIDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\Type;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\Test\TypeTestCase;
use Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeStringIdEntity;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;

class EntityTypeTest extends TypeTestCase
{
    const ITEM_GROUP_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\GroupableEntity';
    const SINGLE_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
    const SINGLE_STRING_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleStringIdEntity';
    const COMPOSITE_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity';
    const COMPOSITE_STRING_IDENT_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeStringIdEntity';

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $emRegistry;

    protected function setUp()
    {
        if (!class_exists('Symfony\Component\Form\Form')) {
            $this->markTestSkipped('The "Form" component is not available');
        }

        if (!class_exists('Doctrine\DBAL\Platforms\MySqlPlatform')) {
            $this->markTestSkipped('Doctrine DBAL is not available.');
        }

        if (!class_exists('Doctrine\Common\Version')) {
            $this->markTestSkipped('Doctrine Common is not available.');
        }

        if (!class_exists('Doctrine\ORM\EntityManager')) {
            $this->markTestSkipped('Doctrine ORM is not available.');
        }

        $this->em = DoctrineTestHelper::createTestEntityManager();
        $this->emRegistry = $this->createRegistryMock('default', $this->em);

        parent::setUp();

        $schemaTool = new SchemaTool($this->em);
        $classes = array(
            $this->em->getClassMetadata(self::ITEM_GROUP_CLASS),
            $this->em->getClassMetadata(self::SINGLE_IDENT_CLASS),
            $this->em->getClassMetadata(self::SINGLE_STRING_IDENT_CLASS),
            $this->em->getClassMetadata(self::COMPOSITE_IDENT_CLASS),
            $this->em->getClassMetadata(self::COMPOSITE_STRING_IDENT_CLASS),
        );

        try {
            $schemaTool->dropSchema($classes);
        } catch (\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }
    }

    protected function tearDown()
    {
        parent::tearDown();

        $this->em = null;
        $this->emRegistry = null;
    }

    protected function getExtensions()
    {
        return array_merge(parent::getExtensions(), array(
            new DoctrineOrmExtension($this->emRegistry),
        ));
    }

    protected function persist(array $entities)
    {
        foreach ($entities as $entity) {
            $this->em->persist($entity);
        }

        $this->em->flush();
        // no clear, because entities managed by the choice field must
        // be managed!
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException
     */
    public function testClassOptionIsRequired()
    {
        $this->factory->createNamed('name', 'entity');
    }

    public function testSetDataToUninitializedEntityWithNonRequired()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        $this->persist(array($entity1, $entity2));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'required' => false,
            'property' => 'name'
        ));

        $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']);
    }

    public function testSetDataToUninitializedEntityWithNonRequiredToString()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        $this->persist(array($entity1, $entity2));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'required' => false,
        ));

        $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']);
    }

    public function testSetDataToUninitializedEntityWithNonRequiredQueryBuilder()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        $this->persist(array($entity1, $entity2));
        $qb = $this->em->createQueryBuilder()->select('e')->from(self::SINGLE_IDENT_CLASS, 'e');

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'required' => false,
            'property' => 'name',
            'query_builder' => $qb
        ));

        $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']);
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testConfigureQueryBuilderWithNonQueryBuilderAndNonClosure()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'query_builder' => new \stdClass(),
        ));
    }

    /**
     * @expectedException \Symfony\Component\Form\Exception\UnexpectedTypeException
     */
    public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'query_builder' => function () {
                return new \stdClass();
            },
        ));

        $field->submit('2');
    }

    public function testSetDataSingleNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->setData(null);

        $this->assertNull($field->getData());
        $this->assertSame('', $field->getViewData());
    }

    public function testSetDataMultipleExpandedNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => true,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->setData(null);

        $this->assertNull($field->getData());
        $this->assertSame(array(), $field->getViewData());
    }

    public function testSetDataMultipleNonExpandedNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->setData(null);

        $this->assertNull($field->getData());
        $this->assertSame(array(), $field->getViewData());
    }

    public function testSubmitSingleExpandedNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => true,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->submit(null);

        $this->assertNull($field->getData());
        $this->assertSame(array(), $field->getViewData());
    }

    public function testSubmitSingleNonExpandedNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->submit(null);

        $this->assertNull($field->getData());
        $this->assertSame('', $field->getViewData());
    }

    public function testSubmitMultipleNull()
    {
        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
        ));
        $field->submit(null);

        $this->assertEquals(new ArrayCollection(), $field->getData());
        $this->assertSame(array(), $field->getViewData());
    }

    public function testSubmitSingleNonExpandedSingleIdentifier()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        $this->persist(array($entity1, $entity2));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'property' => 'name',
        ));

        $field->submit('2');

        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity2, $field->getData());
        $this->assertSame('2', $field->getViewData());
    }

    public function testSubmitSingleNonExpandedCompositeIdentifier()
    {
        $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');
        $entity2 = new CompositeIntIdEntity(30, 40, 'Bar');

        $this->persist(array($entity1, $entity2));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => false,
            'em' => 'default',
            'class' => self::COMPOSITE_IDENT_CLASS,
            'property' => 'name',
        ));

        // the collection key is used here
        $field->submit('1');

        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity2, $field->getData());
        $this->assertSame('1', $field->getViewData());
    }

    public function testSubmitMultipleNonExpandedSingleIdentifier()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'property' => 'name',
        ));

        $field->submit(array('1', '3'));

        $expected = new ArrayCollection(array($entity1, $entity3));

        $this->assertTrue($field->isSynchronized());
        $this->assertEquals($expected, $field->getData());
        $this->assertSame(array('1', '3'), $field->getViewData());
    }

    public function testSubmitMultipleNonExpandedSingleIdentifierForExistingData()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'property' => 'name',
        ));

        $existing = new ArrayCollection(array(0 => $entity2));

        $field->setData($existing);
        $field->submit(array('1', '3'));

        // entry with index 0 ($entity2) was replaced
        $expected = new ArrayCollection(array(0 => $entity1, 1 => $entity3));

        $this->assertTrue($field->isSynchronized());
        $this->assertEquals($expected, $field->getData());
        // same object still, useful if it is a PersistentCollection
        $this->assertSame($existing, $field->getData());
        $this->assertSame(array('1', '3'), $field->getViewData());
    }

    public function testSubmitMultipleNonExpandedCompositeIdentifier()
    {
        $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');
        $entity2 = new CompositeIntIdEntity(30, 40, 'Bar');
        $entity3 = new CompositeIntIdEntity(50, 60, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => false,
            'em' => 'default',
            'class' => self::COMPOSITE_IDENT_CLASS,
            'property' => 'name',
        ));

        // because of the composite key collection keys are used
        $field->submit(array('0', '2'));

        $expected = new ArrayCollection(array($entity1, $entity3));

        $this->assertTrue($field->isSynchronized());
        $this->assertEquals($expected, $field->getData());
        $this->assertSame(array('0', '2'), $field->getViewData());
    }

    public function testSubmitMultipleNonExpandedCompositeIdentifierExistingData()
    {
        $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');
        $entity2 = new CompositeIntIdEntity(30, 40, 'Bar');
        $entity3 = new CompositeIntIdEntity(50, 60, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => false,
            'em' => 'default',
            'class' => self::COMPOSITE_IDENT_CLASS,
            'property' => 'name',
        ));

        $existing = new ArrayCollection(array(0 => $entity2));

        $field->setData($existing);
        $field->submit(array('0', '2'));

        // entry with index 0 ($entity2) was replaced
        $expected = new ArrayCollection(array(0 => $entity1, 1 => $entity3));

        $this->assertTrue($field->isSynchronized());
        $this->assertEquals($expected, $field->getData());
        // same object still, useful if it is a PersistentCollection
        $this->assertSame($existing, $field->getData());
        $this->assertSame(array('0', '2'), $field->getViewData());
    }

    public function testSubmitSingleExpanded()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');

        $this->persist(array($entity1, $entity2));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => true,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'property' => 'name',
        ));

        $field->submit('2');

        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity2, $field->getData());
        $this->assertFalse($field['1']->getData());
        $this->assertTrue($field['2']->getData());
        $this->assertNull($field['1']->getViewData());
        $this->assertSame('2', $field['2']->getViewData());
    }

    public function testSubmitMultipleExpanded()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Bar');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => true,
            'expanded' => true,
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'property' => 'name',
        ));

        $field->submit(array('1', '3'));

        $expected = new ArrayCollection(array($entity1, $entity3));

        $this->assertTrue($field->isSynchronized());
        $this->assertEquals($expected, $field->getData());
        $this->assertTrue($field['1']->getData());
        $this->assertFalse($field['2']->getData());
        $this->assertTrue($field['3']->getData());
        $this->assertSame('1', $field['1']->getViewData());
        $this->assertNull($field['2']->getViewData());
        $this->assertSame('3', $field['3']->getViewData());
    }

    public function testOverrideChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            // not all persisted entities should be displayed
            'choices' => array($entity1, $entity2),
            'property' => 'name',
        ));

        $field->submit('2');

        $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']);
        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity2, $field->getData());
        $this->assertSame('2', $field->getViewData());
    }

    public function testGroupByChoices()
    {
        $item1 = new GroupableEntity(1, 'Foo', 'Group1');
        $item2 = new GroupableEntity(2, 'Bar', 'Group1');
        $item3 = new GroupableEntity(3, 'Baz', 'Group2');
        $item4 = new GroupableEntity(4, 'Boo!', null);

        $this->persist(array($item1, $item2, $item3, $item4));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::ITEM_GROUP_CLASS,
            'choices' => array($item1, $item2, $item3, $item4),
            'property' => 'name',
            'group_by' => 'groupName',
        ));

        $field->submit('2');

        $this->assertSame('2', $field->getViewData());
        $this->assertEquals(array(
            'Group1' => array(1 => new ChoiceView($item1, '1', 'Foo'), 2 => new ChoiceView($item2, '2', 'Bar')),
            'Group2' => array(3 => new ChoiceView($item3, '3', 'Baz')),
            '4' => new ChoiceView($item4, '4', 'Boo!')
        ), $field->createView()->vars['choices']);
    }

    public function testPreferredChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'preferred_choices' => array($entity3, $entity2),
            'property' => 'name',
        ));

        $this->assertEquals(array(3 => new ChoiceView($entity3, '3', 'Baz'), 2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['preferred_choices']);
        $this->assertEquals(array(1 => new ChoiceView($entity1, '1', 'Foo')), $field->createView()->vars['choices']);
    }

    public function testOverrideChoicesWithPreferredChoices()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'choices' => array($entity2, $entity3),
            'preferred_choices' => array($entity3),
            'property' => 'name',
        ));

        $this->assertEquals(array(3 => new ChoiceView($entity3, '3', 'Baz')), $field->createView()->vars['preferred_choices']);
        $this->assertEquals(array(2 => new ChoiceView($entity2, '2', 'Bar')), $field->createView()->vars['choices']);
    }

    public function testDisallowChoicesThatAreNotIncludedChoicesSingleIdentifier()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'choices' => array($entity1, $entity2),
            'property' => 'name',
        ));

        $field->submit('3');

        $this->assertFalse($field->isSynchronized());
        $this->assertNull($field->getData());
    }

    public function testDisallowChoicesThatAreNotIncludedChoicesCompositeIdentifier()
    {
        $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');
        $entity2 = new CompositeIntIdEntity(30, 40, 'Bar');
        $entity3 = new CompositeIntIdEntity(50, 60, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::COMPOSITE_IDENT_CLASS,
            'choices' => array($entity1, $entity2),
            'property' => 'name',
        ));

        $field->submit('2');

        $this->assertFalse($field->isSynchronized());
        $this->assertNull($field->getData());
    }

    public function testDisallowChoicesThatAreNotIncludedQueryBuilderSingleIdentifier()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $repository = $this->em->getRepository(self::SINGLE_IDENT_CLASS);

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'query_builder' => $repository->createQueryBuilder('e')
                ->where('e.id IN (1, 2)'),
            'property' => 'name',
        ));

        $field->submit('3');

        $this->assertFalse($field->isSynchronized());
        $this->assertNull($field->getData());
    }

    public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureSingleIdentifier()
    {
        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $entity2 = new SingleIntIdEntity(2, 'Bar');
        $entity3 = new SingleIntIdEntity(3, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::SINGLE_IDENT_CLASS,
            'query_builder' => function ($repository) {
                return $repository->createQueryBuilder('e')
                        ->where('e.id IN (1, 2)');
            },
            'property' => 'name',
        ));

        $field->submit('3');

        $this->assertFalse($field->isSynchronized());
        $this->assertNull($field->getData());
    }

    public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureCompositeIdentifier()
    {
        $entity1 = new CompositeIntIdEntity(10, 20, 'Foo');
        $entity2 = new CompositeIntIdEntity(30, 40, 'Bar');
        $entity3 = new CompositeIntIdEntity(50, 60, 'Baz');

        $this->persist(array($entity1, $entity2, $entity3));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'em' => 'default',
            'class' => self::COMPOSITE_IDENT_CLASS,
            'query_builder' => function ($repository) {
                return $repository->createQueryBuilder('e')
                        ->where('e.id1 IN (10, 50)');
            },
            'property' => 'name',
        ));

        $field->submit('2');

        $this->assertFalse($field->isSynchronized());
        $this->assertNull($field->getData());
    }

    public function testSubmitSingleStringIdentifier()
    {
        $entity1 = new SingleStringIdEntity('foo', 'Foo');

        $this->persist(array($entity1));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => false,
            'em' => 'default',
            'class' => self::SINGLE_STRING_IDENT_CLASS,
            'property' => 'name',
        ));

        $field->submit('foo');

        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity1, $field->getData());
        $this->assertSame('foo', $field->getViewData());
    }

    public function testSubmitCompositeStringIdentifier()
    {
        $entity1 = new CompositeStringIdEntity('foo1', 'foo2', 'Foo');

        $this->persist(array($entity1));

        $field = $this->factory->createNamed('name', 'entity', null, array(
            'multiple' => false,
            'expanded' => false,
            'em' => 'default',
            'class' => self::COMPOSITE_STRING_IDENT_CLASS,
            'property' => 'name',
        ));

        // the collection key is used here
        $field->submit('0');

        $this->assertTrue($field->isSynchronized());
        $this->assertSame($entity1, $field->getData());
        $this->assertSame('0', $field->getViewData());
    }

    public function testGetManagerForClassIfNoEm()
    {
        $this->emRegistry->expects($this->never())
            ->method('getManager');

        $this->emRegistry->expects($this->once())
            ->method('getManagerForClass')
            ->with(self::SINGLE_IDENT_CLASS)
            ->will($this->returnValue($this->em));

        $this->factory->createNamed('name', 'entity', null, array(
            'class' => self::SINGLE_IDENT_CLASS,
            'required' => false,
            'property' => 'name'
        ));
    }

    protected function createRegistryMock($name, $em)
    {
        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $registry->expects($this->any())
                 ->method('getManager')
                 ->with($this->equalTo($name))
                 ->will($this->returnValue($em));

        return $registry;
    }
}
PK91[�I�m��TDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Form\Type;

use Symfony\Component\Form\Tests\FormPerformanceTestCase;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Doctrine\ORM\Tools\SchemaTool;
use Symfony\Bridge\Doctrine\Tests\DoctrineOrmTestCase;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class EntityTypePerformanceTest extends FormPerformanceTestCase
{
    const ENTITY_CLASS = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $em;

    protected function getExtensions()
    {
        $manager = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');

        $manager->expects($this->any())
            ->method('getManager')
            ->will($this->returnValue($this->em));

        $manager->expects($this->any())
            ->method('getManagerForClass')
            ->will($this->returnValue($this->em));

        return array(
            new CoreExtension(),
            new DoctrineOrmExtension($manager)
        );
    }

    protected function setUp()
    {
        $this->em = DoctrineOrmTestCase::createTestEntityManager();

        parent::setUp();

        $schemaTool = new SchemaTool($this->em);
        $classes = array(
            $this->em->getClassMetadata(self::ENTITY_CLASS),
        );

        try {
            $schemaTool->dropSchema($classes);
        } catch (\Exception $e) {
        }

        try {
            $schemaTool->createSchema($classes);
        } catch (\Exception $e) {
        }

        $ids = range(1, 300);

        foreach ($ids as $id) {
            $name = 65 + chr($id % 57);
            $this->em->persist(new SingleIntIdEntity($id, $name));
        }

        $this->em->flush();
    }

    /**
     * This test case is realistic in collection forms where each
     * row contains the same entity field.
     *
     * @group benchmark
     */
    public function testCollapsedEntityField()
    {
        $this->setMaxRunningTime(1);

        for ($i = 0; $i < 40; ++$i) {
            $form = $this->factory->create('entity', null, array(
                'class' => self::ENTITY_CLASS,
            ));

            // force loading of the choice list
            $form->createView();
        }
    }

    /**
     * @group benchmark
     */
    public function testCollapsedEntityFieldWithChoices()
    {
        $choices = $this->em->createQuery('SELECT c FROM '.self::ENTITY_CLASS.' c')->getResult();
        $this->setMaxRunningTime(1);

        for ($i = 0; $i < 40; ++$i) {
            $form = $this->factory->create('entity', null, array(
                'class' => self::ENTITY_CLASS,
                'choices' => $choices,
            ));

            // force loading of the choice list
            $form->createView();
        }
    }

    /**
     * @group benchmark
     */
    public function testCollapsedEntityFieldWithPreferredChoices()
    {
        $choices = $this->em->createQuery('SELECT c FROM '.self::ENTITY_CLASS.' c')->getResult();
        $this->setMaxRunningTime(1);

        for ($i = 0; $i < 40; ++$i) {
            $form = $this->factory->create('entity', null, array(
                    'class' => self::ENTITY_CLASS,
                    'preferred_choices' => $choices,
                ));

            // force loading of the choice list
            $form->createView();
        }
    }
}
PK91[�;��
�
UDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Security\User;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\User;
use Symfony\Bridge\Doctrine\Security\User\EntityUserProvider;
use Doctrine\ORM\Tools\SchemaTool;

class EntityUserProviderTest extends \PHPUnit_Framework_TestCase
{
    public function testRefreshUserGetsUserByPrimaryKey()
    {
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);

        $user1 = new User(1, 1, 'user1');
        $user2 = new User(1, 2, 'user2');

        $em->persist($user1);
        $em->persist($user2);
        $em->flush();

        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        // try to change the user identity
        $user1->name = 'user2';

        $this->assertSame($user1, $provider->refreshUser($user1));
    }

    public function testRefreshUserRequiresId()
    {
        $em = DoctrineTestHelper::createTestEntityManager();

        $user1 = new User(null, null, 'user1');
        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        $this->setExpectedException(
            'InvalidArgumentException',
            'You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine'
        );
        $provider->refreshUser($user1);
    }

    public function testRefreshInvalidUser()
    {
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);

        $user1 = new User(1, 1, 'user1');

        $em->persist($user1);
        $em->flush();

        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        $user2 = new User(1, 2, 'user2');
        $this->setExpectedException(
            'Symfony\Component\Security\Core\Exception\UsernameNotFoundException',
            'User with id {"id1":1,"id2":2} not found'
        );
        $provider->refreshUser($user2);
    }

    public function testSupportProxy()
    {
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);

        $user1 = new User(1, 1, 'user1');

        $em->persist($user1);
        $em->flush();
        $em->clear();

        $provider = new EntityUserProvider($this->getManager($em), 'Symfony\Bridge\Doctrine\Tests\Fixtures\User', 'name');

        $user2 = $em->getReference('Symfony\Bridge\Doctrine\Tests\Fixtures\User', array('id1' => 1, 'id2' => 1));
        $this->assertTrue($provider->supportsClass(get_class($user2)));
    }

    private function getManager($em, $name = null)
    {
        $manager = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $manager->expects($this->once())
            ->method('getManager')
            ->with($this->equalTo($name))
            ->will($this->returnValue($em));

        return $manager;
    }

    private function createSchema($em)
    {
        $schemaTool = new SchemaTool($em);
        $schemaTool->createSchema(array(
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'),
        ));
    }
}
PK91[}��u>u>ZDoctrineBridge/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\Validator\Constraints;

use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity;
use Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Validator;
use Doctrine\ORM\Tools\SchemaTool;

class UniqueValidatorTest extends \PHPUnit_Framework_TestCase
{
    protected function createRegistryMock($entityManagerName, $em)
    {
        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $registry->expects($this->any())
                 ->method('getManager')
                 ->with($this->equalTo($entityManagerName))
                 ->will($this->returnValue($em));

        return $registry;
    }

    protected function createRepositoryMock()
    {
        $repository = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectRepository')
            ->setMethods(array('findByCustom', 'find', 'findAll', 'findOneBy', 'findBy', 'getClassName'))
            ->getMock()
        ;

        return $repository;
    }

    protected function createEntityManagerMock($repositoryMock)
    {
        $em = $this->getMockBuilder('Doctrine\Common\Persistence\ObjectManager')
            ->getMock()
        ;
        $em->expects($this->any())
             ->method('getRepository')
             ->will($this->returnValue($repositoryMock))
        ;

        $classMetadata = $this->getMock('Doctrine\Common\Persistence\Mapping\ClassMetadata');
        $classMetadata
            ->expects($this->any())
            ->method('hasField')
            ->will($this->returnValue(true))
        ;
        $refl = $this->getMockBuilder('Doctrine\Common\Reflection\StaticReflectionProperty')
            ->disableOriginalConstructor()
            ->setMethods(array('getValue'))
            ->getMock()
        ;
        $refl
            ->expects($this->any())
            ->method('getValue')
            ->will($this->returnValue(true))
        ;
        $classMetadata->reflFields = array('name' => $refl);
        $em->expects($this->any())
             ->method('getClassMetadata')
             ->will($this->returnValue($classMetadata))
        ;

        return $em;
    }

    protected function createValidatorFactory($uniqueValidator)
    {
        $validatorFactory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
        $validatorFactory->expects($this->any())
                         ->method('getInstance')
                         ->with($this->isInstanceOf('Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity'))
                         ->will($this->returnValue($uniqueValidator));

        return $validatorFactory;
    }

    public function createValidator($entityManagerName, $em, $validateClass = null, $uniqueFields = null, $errorPath = null, $repositoryMethod = 'findBy', $ignoreNull = true)
    {
        if (!$validateClass) {
            $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity';
        }
        if (!$uniqueFields) {
            $uniqueFields = array('name');
        }

        $registry = $this->createRegistryMock($entityManagerName, $em);

        $uniqueValidator = new UniqueEntityValidator($registry);

        $metadata = new ClassMetadata($validateClass);
        $constraint = new UniqueEntity(array(
            'fields' => $uniqueFields,
            'em' => $entityManagerName,
            'errorPath' => $errorPath,
            'repositoryMethod' => $repositoryMethod,
            'ignoreNull' => $ignoreNull
        ));
        $metadata->addConstraint($constraint);

        $metadataFactory = new FakeMetadataFactory();
        $metadataFactory->addMetadata($metadata);
        $validatorFactory = $this->createValidatorFactory($uniqueValidator);

        return new Validator($metadataFactory, $validatorFactory, new DefaultTranslator());
    }

    private function createSchema($em)
    {
        $schemaTool = new SchemaTool($em);
        $schemaTool->createSchema(array(
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity'),
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity'),
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\CompositeIntIdEntity'),
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity'),
        ));
    }

    /**
     * This is a functional test as there is a large integration necessary to get the validator working.
     */
    public function testValidateUniqueness()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em);

        $entity1 = new SingleIntIdEntity(1, 'Foo');
        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database.");

        $em->persist($entity1);
        $em->flush();

        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database.");

        $entity2 = new SingleIntIdEntity(2, 'Foo');

        $violationsList = $validator->validate($entity2);
        $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database.");

        $violation = $violationsList[0];
        $this->assertEquals('This value is already used.', $violation->getMessage());
        $this->assertEquals('name', $violation->getPropertyPath());
        $this->assertEquals('Foo', $violation->getInvalidValue());
    }

    public function testValidateCustomErrorPath()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em, null, null, 'bar');

        $entity1 = new SingleIntIdEntity(1, 'Foo');

        $em->persist($entity1);
        $em->flush();

        $entity2 = new SingleIntIdEntity(2, 'Foo');

        $violationsList = $validator->validate($entity2);
        $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database.");

        $violation = $violationsList[0];
        $this->assertEquals('This value is already used.', $violation->getMessage());
        $this->assertEquals('bar', $violation->getPropertyPath());
        $this->assertEquals('Foo', $violation->getInvalidValue());
    }

    public function testValidateUniquenessWithNull()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em);

        $entity1 = new SingleIntIdEntity(1, null);
        $entity2 = new SingleIntIdEntity(2, null);

        $em->persist($entity1);
        $em->persist($entity2);
        $em->flush();

        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), "No violations found on entity having a null value.");
    }

    public function testValidateUniquenessWithIgnoreNull()
    {
        $entityManagerName = "foo";
        $validateClass = 'Symfony\Bridge\Doctrine\Tests\Fixtures\DoubleNameEntity';
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em, $validateClass, array('name', 'name2'), 'bar', 'findby', false);

        $entity1 = new DoubleNameEntity(1, 'Foo', null);
        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), "No violations found on entity before it is saved to the database.");

        $em->persist($entity1);
        $em->flush();

        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), "No violations found on entity after it was saved to the database.");

        $entity2 = new DoubleNameEntity(2, 'Foo', null);

        $violationsList = $validator->validate($entity2);
        $this->assertEquals(1, $violationsList->count(), "Violation found on entity with conflicting entity existing in the database.");

        $violation = $violationsList[0];
        $this->assertEquals('This value is already used.', $violation->getMessage());
        $this->assertEquals('bar', $violation->getPropertyPath());
        $this->assertEquals('Foo', $violation->getInvalidValue());
    }

    public function testValidateUniquenessAfterConsideringMultipleQueryResults()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em);

        $entity1 = new SingleIntIdEntity(1, 'foo');
        $entity2 = new SingleIntIdEntity(2, 'foo');

        $em->persist($entity1);
        $em->persist($entity2);
        $em->flush();

        $violationsList = $validator->validate($entity1);
        $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.');

        $violationsList = $validator->validate($entity2);
        $this->assertEquals(1, $violationsList->count(), 'Violation found on entity with conflicting entity existing in the database.');
    }

    public function testValidateUniquenessUsingCustomRepositoryMethod()
    {
        $entityManagerName = 'foo';
        $repository = $this->createRepositoryMock();
        $repository->expects($this->once())
             ->method('findByCustom')
             ->will($this->returnValue(array()))
        ;
        $em = $this->createEntityManagerMock($repository);
        $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom');

        $entity1 = new SingleIntIdEntity(1, 'foo');

        $violationsList = $validator->validate($entity1);
        $this->assertEquals(0, $violationsList->count(), 'Violation is using custom repository method.');
    }

    public function testValidateUniquenessWithUnrewoundArray()
    {
        $entity = new SingleIntIdEntity(1, 'foo');

        $entityManagerName = 'foo';
        $repository = $this->createRepositoryMock();
        $repository->expects($this->once())
            ->method('findByCustom')
            ->will(
                $this->returnCallback(function () use ($entity) {
                    $returnValue = array(
                        $entity,
                    );
                    next($returnValue);

                    return $returnValue;
                })
            )
        ;
        $em = $this->createEntityManagerMock($repository);
        $validator = $this->createValidator($entityManagerName, $em, null, array(), null, 'findByCustom');

        $violationsList = $validator->validate($entity);
        $this->assertCount(0, $violationsList, 'Violation is using unrewound array as return value in the repository method.');
    }

    /**
     * @group GH-1635
     */
    public function testAssociatedEntity()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single'));

        $entity1 = new SingleIntIdEntity(1, 'foo');
        $associated = new AssociationEntity();
        $associated->single = $entity1;

        $em->persist($entity1);
        $em->persist($associated);
        $em->flush();

        $violationsList = $validator->validate($associated);
        $this->assertEquals(0, $violationsList->count());

        $associated2 = new AssociationEntity();
        $associated2->single = $entity1;

        $em->persist($associated2);
        $em->flush();

        $violationsList = $validator->validate($associated2);
        $this->assertEquals(1, $violationsList->count());
    }

    public function testAssociatedEntityWithNull()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('single'), null, 'findBy', false);

        $associated = new AssociationEntity();
        $associated->single = null;

        $em->persist($associated);
        $em->flush();

        $violationsList = $validator->validate($associated);
        $this->assertEquals(0, $violationsList->count());
    }

    /**
     * @group GH-1635
     */
    public function testAssociatedCompositeEntity()
    {
        $entityManagerName = "foo";
        $em = DoctrineTestHelper::createTestEntityManager();
        $this->createSchema($em);
        $validator = $this->createValidator($entityManagerName, $em, 'Symfony\Bridge\Doctrine\Tests\Fixtures\AssociationEntity', array('composite'));

        $composite = new CompositeIntIdEntity(1, 1, "test");
        $associated = new AssociationEntity();
        $associated->composite = $composite;

        $em->persist($composite);
        $em->persist($associated);
        $em->flush();

        $this->setExpectedException(
            'Symfony\Component\Validator\Exception\ConstraintDefinitionException',
            'Associated entities are not allowed to have more than one identifier field'
        );
        $violationsList = $validator->validate($associated);
    }

    public function testDedicatedEntityManagerNullObject()
    {
        $uniqueFields = array('name');
        $entityManagerName = 'foo';

        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');

        $constraint = new UniqueEntity(array(
            'fields' => $uniqueFields,
            'em' => $entityManagerName,
        ));

        $uniqueValidator = new UniqueEntityValidator($registry);

        $entity = new SingleIntIdEntity(1, null);

        $this->setExpectedException(
            'Symfony\Component\Validator\Exception\ConstraintDefinitionException',
            'Object manager "foo" does not exist.'
        );

        $uniqueValidator->validate($entity, $constraint);
    }

    public function testEntityManagerNullObject()
    {
        $uniqueFields = array('name');

        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');

        $constraint = new UniqueEntity(array(
            'fields' => $uniqueFields,
        ));

        $uniqueValidator = new UniqueEntityValidator($registry);

        $entity = new SingleIntIdEntity(1, null);

        $this->setExpectedException(
            'Symfony\Component\Validator\Exception\ConstraintDefinitionException',
            'Unable to find the object manager associated with an entity of class "Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity"'
        );

        $uniqueValidator->validate($entity, $constraint);
    }
}
PK91[���,��[DoctrineBridge/Symfony/Bridge/Doctrine/Tests/ExpressionLanguage/DoctrineParserCacheTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\ExpressionLanguage;

use Symfony\Bridge\Doctrine\ExpressionLanguage\DoctrineParserCache;

class DoctrineParserCacheTest extends \PHPUnit_Framework_TestCase
{
    public function testFetch()
    {
        $doctrineCacheMock = $this->getMock('Doctrine\Common\Cache\Cache');
        $parserCache = new DoctrineParserCache($doctrineCacheMock);

        $doctrineCacheMock->expects($this->once())
            ->method('fetch')
            ->will($this->returnValue('bar'));

        $result = $parserCache->fetch('foo');

        $this->assertEquals('bar', $result);
    }

    public function testFetchUnexisting()
    {
        $doctrineCacheMock = $this->getMock('Doctrine\Common\Cache\Cache');
        $parserCache = new DoctrineParserCache($doctrineCacheMock);

        $doctrineCacheMock
            ->expects($this->once())
            ->method('fetch')
            ->will($this->returnValue(false));

        $this->assertNull($parserCache->fetch(''));
    }

    public function testSave()
    {
        $doctrineCacheMock = $this->getMock('Doctrine\Common\Cache\Cache');
        $parserCache = new DoctrineParserCache($doctrineCacheMock);

        $expression = $this->getMockBuilder('Symfony\Component\ExpressionLanguage\ParsedExpression')
            ->disableOriginalConstructor()
            ->getMock();

        $doctrineCacheMock->expects($this->once())
            ->method('save')
            ->with('foo', $expression);

        $parserCache->save('foo', $expression);
    }
}
PK91[�$K�BBODoctrineBridge/Symfony/Bridge/Doctrine/Tests/ContainerAwareEventManagerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests;

use Symfony\Bridge\Doctrine\ContainerAwareEventManager;
use Symfony\Component\DependencyInjection\Container;

class ContainerAwareEventManagerTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $this->container = new Container();
        $this->evm = new ContainerAwareEventManager($this->container);
    }

    public function testDispatchEvent()
    {
        $this->container->set('foobar', $listener1 = new MyListener());
        $this->evm->addEventListener('foo', 'foobar');
        $this->evm->addEventListener('foo', $listener2 = new MyListener());

        $this->evm->dispatchEvent('foo');

        $this->assertTrue($listener1->called);
        $this->assertTrue($listener2->called);
    }

    public function testRemoveEventListener()
    {
        $this->evm->addEventListener('foo', 'bar');
        $this->evm->addEventListener('foo', $listener = new MyListener());

        $listeners = array('foo' => array('_service_bar' => 'bar', spl_object_hash($listener) => $listener));
        $this->assertSame($listeners, $this->evm->getListeners());
        $this->assertSame($listeners['foo'], $this->evm->getListeners('foo'));

        $this->evm->removeEventListener('foo', $listener);
        $this->assertSame(array('_service_bar' => 'bar'), $this->evm->getListeners('foo'));

        $this->evm->removeEventListener('foo', 'bar');
        $this->assertSame(array(), $this->evm->getListeners('foo'));
    }
}

class MyListener
{
    public $called = false;

    public function foo()
    {
        $this->called = true;
    }
}
PK91[�9qqVDoctrineBridge/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\DataFixtures;

use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bridge\Doctrine\Tests\Fixtures\ContainerAwareFixture;

class ContainerAwareLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldSetContainerOnContainerAwareFixture()
    {
        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $loader    = new ContainerAwareLoader($container);
        $fixture   = new ContainerAwareFixture();

        $loader->addFixture($fixture);

        $this->assertSame($container, $fixture->container);
    }
}
PK91[C�IIVDoctrineBridge/Symfony/Bridge/Doctrine/Tests/HttpFoundation/DbalSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\HttpFoundation;

use Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler;

/**
 * Test class for DbalSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 */
class DbalSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $this->connection = $this->getMock('Doctrine\DBAL\Driver\Connection');
        $mock = $this->getMockBuilder('Symfony\Bridge\Doctrine\HttpFoundation\DbalSessionHandler');
        $mock->setConstructorArgs(array($this->connection));
        $this->driver = $mock->getMock();
    }
}
PK91[�l��XDoctrineBridge/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Doctrine\Tests\DataCollector;

use Doctrine\DBAL\Platforms\MySqlPlatform;
use Symfony\Bridge\Doctrine\DataCollector\DoctrineDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DoctrineDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollectConnections()
    {
        $c = $this->createCollector(array());
        $c->collect(new Request(), new Response());
        $this->assertEquals(array('default' => 'doctrine.dbal.default_connection'), $c->getConnections());
    }

    public function testCollectManagers()
    {
        $c = $this->createCollector(array());
        $c->collect(new Request(), new Response());
        $this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $c->getManagers());
    }

    public function testCollectQueryCount()
    {
        $c = $this->createCollector(array());
        $c->collect(new Request(), new Response());
        $this->assertEquals(0, $c->getQueryCount());

        $queries = array(
            array('sql' => "SELECT * FROM table1", 'params' => array(), 'types' => array(), 'executionMS' => 0)
        );
        $c = $this->createCollector($queries);
        $c->collect(new Request(), new Response());
        $this->assertEquals(1, $c->getQueryCount());
    }

    public function testCollectTime()
    {
        $c = $this->createCollector(array());
        $c->collect(new Request(), new Response());
        $this->assertEquals(0, $c->getTime());

        $queries = array(
            array('sql' => "SELECT * FROM table1", 'params' => array(), 'types' => array(), 'executionMS' => 1)
        );
        $c = $this->createCollector($queries);
        $c->collect(new Request(), new Response());
        $this->assertEquals(1, $c->getTime());

        $queries = array(
            array('sql' => "SELECT * FROM table1", 'params' => array(), 'types' => array(), 'executionMS' => 1),
            array('sql' => "SELECT * FROM table2", 'params' => array(), 'types' => array(), 'executionMS' => 2)
        );
        $c = $this->createCollector($queries);
        $c->collect(new Request(), new Response());
        $this->assertEquals(3, $c->getTime());
    }

    /**
     * @dataProvider paramProvider
     */
    public function testCollectQueries($param, $types, $expected, $explainable)
    {
        $queries = array(
            array('sql' => "SELECT * FROM table1 WHERE field1 = ?1", 'params' => array($param), 'types' => $types, 'executionMS' => 1)
        );
        $c = $this->createCollector($queries);
        $c->collect(new Request(), new Response());

        $collected_queries = $c->getQueries();
        $this->assertEquals($expected, $collected_queries['default'][0]['params'][0]);
        $this->assertEquals($explainable, $collected_queries['default'][0]['explainable']);
    }

    /**
     * @dataProvider paramProvider
     */
    public function testSerialization($param, $types, $expected, $explainable)
    {
        $queries = array(
            array('sql' => "SELECT * FROM table1 WHERE field1 = ?1", 'params' => array($param), 'types' => $types, 'executionMS' => 1)
        );
        $c = $this->createCollector($queries);
        $c->collect(new Request(), new Response());
        $c = unserialize(serialize($c));

        $collected_queries = $c->getQueries();
        $this->assertEquals($expected, $collected_queries['default'][0]['params'][0]);
        $this->assertEquals($explainable, $collected_queries['default'][0]['explainable']);
    }

    public function paramProvider()
    {
        return array(
            array('some value', array(), 'some value', true),
            array(1, array(), 1, true),
            array(true, array(), true, true),
            array(null, array(), null, true),
            array(new \DateTime('2011-09-11'), array('date'), '2011-09-11', true),
            array(fopen(__FILE__, 'r'), array(), 'Resource(stream)', false),
            array(new \SplFileInfo(__FILE__), array(), 'Object(SplFileInfo)', false),
        );
    }

    private function createCollector($queries)
    {
        $connection = $this->getMockBuilder('Doctrine\DBAL\Connection')
            ->disableOriginalConstructor()
            ->getMock();
        $connection->expects($this->any())
            ->method('getDatabasePlatform')
            ->will($this->returnValue(new MySqlPlatform()));

        $registry = $this->getMock('Doctrine\Common\Persistence\ManagerRegistry');
        $registry
                ->expects($this->any())
                ->method('getConnectionNames')
                ->will($this->returnValue(array('default' => 'doctrine.dbal.default_connection')));
        $registry
                ->expects($this->any())
                ->method('getManagerNames')
                ->will($this->returnValue(array('default' => 'doctrine.orm.default_entity_manager')));
        $registry->expects($this->any())
            ->method('getConnection')
            ->will($this->returnValue($connection));

        $logger = $this->getMock('Doctrine\DBAL\Logging\DebugStack');
        $logger->queries = $queries;

        $collector = new DoctrineDataCollector($registry);
        $collector->addLogger('default', $logger);

        return $collector;
    }
}
PK91[O���~DoctrineBridge/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bridge\Doctrine\Tests\DependencyInjection\CompilerPass;

use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class RegisterEventListenersAndSubscribersPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcessEventListenersWithPriorities()
    {
        $container = $this->createBuilder();

        $container
            ->register('a', 'stdClass')
            ->addTag('doctrine.event_listener', array(
                'event' => 'foo',
                'priority' => -5,
            ))
            ->addTag('doctrine.event_listener', array(
                'event' => 'bar',
            ))
        ;
        $container
            ->register('b', 'stdClass')
            ->addTag('doctrine.event_listener', array(
                'event' => 'foo',
            ))
        ;

        $this->process($container);
        $this->assertEquals(array('b', 'a'), $this->getServiceOrder($container, 'addEventListener'));

        $calls = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls();
        $this->assertEquals(array('foo', 'bar'), $calls[1][1][0]);
    }

    public function testProcessEventListenersWithMultipleConnections()
    {
        $container = $this->createBuilder(true);

        $container
            ->register('a', 'stdClass')
            ->addTag('doctrine.event_listener', array(
                'event' => 'onFlush',
            ))
        ;
        $this->process($container);

        $callsDefault = $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls();

        $this->assertEquals('addEventListener', $callsDefault[0][0]);
        $this->assertEquals(array('onFlush'), $callsDefault[0][1][0]);

        $callsSecond = $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls();
        $this->assertEquals($callsDefault, $callsSecond);
    }

    public function testProcessEventSubscribersWithPriorities()
    {
        $container = $this->createBuilder();

        $container
            ->register('a', 'stdClass')
            ->addTag('doctrine.event_subscriber')
        ;
        $container
            ->register('b', 'stdClass')
            ->addTag('doctrine.event_subscriber', array(
                'priority' => 5,
            ))
        ;
        $container
            ->register('c', 'stdClass')
            ->addTag('doctrine.event_subscriber', array(
                'priority' => 10,
            ))
        ;
        $container
            ->register('d', 'stdClass')
            ->addTag('doctrine.event_subscriber', array(
                'priority' => 10,
            ))
        ;
        $container
            ->register('e', 'stdClass')
            ->addTag('doctrine.event_subscriber', array(
                'priority' => 10,
            ))
        ;

        $this->process($container);
        $this->assertEquals(array('c', 'd', 'e', 'b', 'a'), $this->getServiceOrder($container, 'addEventSubscriber'));
    }

    public function testProcessNoTaggedServices()
    {
        $container = $this->createBuilder(true);

        $this->process($container);

        $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls());

        $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.second_connection.event_manager')->getMethodCalls());
    }

    private function process(ContainerBuilder $container)
    {
        $pass = new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine');
        $pass->process($container);
    }

    private function getServiceOrder(ContainerBuilder $container, $method)
    {
        $order = array();
        foreach ($container->getDefinition('doctrine.dbal.default_connection.event_manager')->getMethodCalls() as $call) {
            list($name, $arguments) = $call;
            if ($method !== $name) {
                continue;
            }

            if ('addEventListener' === $name) {
                $order[] = (string) $arguments[1];
                continue;
            }

            $order[] = (string) $arguments[0];
        }

        return $order;
    }

    private function createBuilder($multipleConnections = false)
    {
        $container = new ContainerBuilder();

        $connections = array('default' => 'doctrine.dbal.default_connection');

        $container->register('doctrine.dbal.default_connection.event_manager', 'stdClass');
        $container->register('doctrine.dbal.default_connection', 'stdClass');

        if ($multipleConnections) {
            $container->register('doctrine.dbal.second_connection.event_manager', 'stdClass');
            $container->register('doctrine.dbal.second_connection', 'stdClass');
            $connections['second'] = 'doctrine.dbal.second_connection';
        }

        $container->setParameter('doctrine.connections', $connections);

        return $container;
    }
}
PK91[�ޠ�777DoctrineBridge/Symfony/Bridge/Doctrine/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="Tests/bootstrap.php"
>
    <testsuites>
        <testsuite name="Symfony Doctrine Bridge Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK:1[&�ǦGGIMonologBridge/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Monolog\Tests\Handler;

use Monolog\Logger;
use Symfony\Bridge\Monolog\Handler\ConsoleHandler;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Tests the ConsoleHandler and also the ConsoleFormatter.
 *
 * @author Tobias Schultze <http://tobion.de>
 */
class ConsoleHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $handler = new ConsoleHandler(null, false);
        $this->assertFalse($handler->getBubble(), 'the bubble parameter gets propagated');
    }

    public function testIsHandling()
    {
        $handler = new ConsoleHandler();
        $this->assertFalse($handler->isHandling(array()), '->isHandling returns false when no output is set');
    }

    /**
     * @dataProvider provideVerbosityMappingTests
     */
    public function testVerbosityMapping($verbosity, $level, $isHandling, array $map = array())
    {
        $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
        $output
            ->expects($this->atLeastOnce())
            ->method('getVerbosity')
            ->will($this->returnValue($verbosity))
        ;
        $handler = new ConsoleHandler($output, true, $map);
        $this->assertSame($isHandling, $handler->isHandling(array('level' => $level)),
            '->isHandling returns correct value depending on console verbosity and log level'
        );
    }

    public function provideVerbosityMappingTests()
    {
        return array(
            array(OutputInterface::VERBOSITY_QUIET, Logger::ERROR, false),
            array(OutputInterface::VERBOSITY_NORMAL, Logger::WARNING, true),
            array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, false),
            array(OutputInterface::VERBOSITY_VERBOSE, Logger::NOTICE, true),
            array(OutputInterface::VERBOSITY_VERBOSE, Logger::INFO, false),
            array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::INFO, true),
            array(OutputInterface::VERBOSITY_VERY_VERBOSE, Logger::DEBUG, false),
            array(OutputInterface::VERBOSITY_DEBUG, Logger::DEBUG, true),
            array(OutputInterface::VERBOSITY_DEBUG, Logger::EMERGENCY, true),
            array(OutputInterface::VERBOSITY_NORMAL, Logger::NOTICE, true, array(
                OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE
            )),
            array(OutputInterface::VERBOSITY_DEBUG, Logger::NOTICE, true, array(
                OutputInterface::VERBOSITY_NORMAL => Logger::NOTICE
            )),
        );
    }

    public function testVerbosityChanged()
    {
        $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
        $output
            ->expects($this->at(0))
            ->method('getVerbosity')
            ->will($this->returnValue(OutputInterface::VERBOSITY_QUIET))
        ;
        $output
            ->expects($this->at(1))
            ->method('getVerbosity')
            ->will($this->returnValue(OutputInterface::VERBOSITY_DEBUG))
        ;
        $handler = new ConsoleHandler($output);
        $this->assertFalse($handler->isHandling(array('level' => Logger::NOTICE)),
            'when verbosity is set to quiet, the handler does not handle the log'
        );
        $this->assertTrue($handler->isHandling(array('level' => Logger::NOTICE)),
            'since the verbosity of the output increased externally, the handler is now handling the log'
        );
    }

    public function testGetFormatter()
    {
        $handler = new ConsoleHandler();
        $this->assertInstanceOf('Symfony\Bridge\Monolog\Formatter\ConsoleFormatter', $handler->getFormatter(),
            '-getFormatter returns ConsoleFormatter by default'
        );
    }

    public function testWritingAndFormatting()
    {
        $output = $this->getMock('Symfony\Component\Console\Output\ConsoleOutputInterface');
        $output
            ->expects($this->any())
            ->method('getVerbosity')
            ->will($this->returnValue(OutputInterface::VERBOSITY_DEBUG))
        ;
        $output
            ->expects($this->once())
            ->method('write')
            ->with('<info>[2013-05-29 16:21:54] app.INFO:</info> My info message [] []'."\n")
        ;

        $errorOutput = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
        $errorOutput
            ->expects($this->once())
            ->method('write')
            ->with('<error>[2013-05-29 16:21:54] app.ERROR:</error> My error message [] []'."\n")
        ;

        $output
            ->expects($this->any())
            ->method('getErrorOutput')
            ->will($this->returnValue($errorOutput))
        ;

        $handler = new ConsoleHandler(null, false);
        $handler->setOutput($output);

        $infoRecord = array(
            'message' => 'My info message',
            'context' => array(),
            'level' => Logger::INFO,
            'level_name' => Logger::getLevelName(Logger::INFO),
            'channel' => 'app',
            'datetime' => new \DateTime('2013-05-29 16:21:54'),
            'extra' => array(),
        );

        $this->assertTrue($handler->handle($infoRecord), 'The handler finished handling the log as bubble is false.');

        $errorRecord = array(
            'message' => 'My error message',
            'context' => array(),
            'level' => Logger::ERROR,
            'level_name' => Logger::getLevelName(Logger::ERROR),
            'channel' => 'app',
            'datetime' => new \DateTime('2013-05-29 16:21:54'),
            'extra' => array(),
        );

        $this->assertTrue($handler->handle($errorRecord), 'The handler finished handling the log as bubble is false.');
    }
}
PK:1[�o.���IMonologBridge/Symfony/Bridge/Monolog/Tests/Processor/WebProcessorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Bridge\Monolog\Tests\Processor;

use Monolog\Logger;
use Symfony\Bridge\Monolog\Processor\WebProcessor;
use Symfony\Component\HttpFoundation\Request;

class WebProcessorTest extends \PHPUnit_Framework_TestCase
{
    public function testUsesRequestServerData()
    {
        $server = array(
            'REQUEST_URI'    => 'A',
            'REMOTE_ADDR'    => 'B',
            'REQUEST_METHOD' => 'C',
            'SERVER_NAME'    => 'D',
            'HTTP_REFERER'   => 'E'
        );

        $request = new Request();
        $request->server->replace($server);

        $event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
            ->disableOriginalConstructor()
            ->getMock();
        $event->expects($this->any())
            ->method('isMasterRequest')
            ->will($this->returnValue(true));
        $event->expects($this->any())
            ->method('getRequest')
            ->will($this->returnValue($request));

        $processor = new WebProcessor();
        $processor->onKernelRequest($event);
        $record = $processor($this->getRecord());

        $this->assertEquals($server['REQUEST_URI'], $record['extra']['url']);
        $this->assertEquals($server['REMOTE_ADDR'], $record['extra']['ip']);
        $this->assertEquals($server['REQUEST_METHOD'], $record['extra']['http_method']);
        $this->assertEquals($server['SERVER_NAME'], $record['extra']['server']);
        $this->assertEquals($server['HTTP_REFERER'], $record['extra']['referrer']);
    }

    /**
     * @param integer $level
     * @param string  $message
     *
     * @return array Record
     */
    protected function getRecord($level = Logger::WARNING, $message = 'test')
    {
        return array(
            'message' => $message,
            'context' => array(),
            'level' => $level,
            'level_name' => Logger::getLevelName($level),
            'channel' => 'test',
            'datetime' => new \DateTime(),
            'extra' => array(),
        );
    }
}
PK:1[��Ki665MonologBridge/Symfony/Bridge/Monolog/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Monolog Bridge Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK:1[}/�66HTemplating/Symfony/Component/Templating/Tests/TemplateNameParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests;

use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Component\Templating\TemplateReference;

class TemplateNameParserTest extends \PHPUnit_Framework_TestCase
{
    protected $parser;

    protected function setUp()
    {
        $this->parser = new TemplateNameParser();
    }

    protected function tearDown()
    {
        $this->parser = null;
    }

    /**
     * @dataProvider getLogicalNameToTemplateProvider
     */
    public function testParse($name, $ref)
    {
        $template = $this->parser->parse($name);

        $this->assertEquals($template->getLogicalName(), $ref->getLogicalName());
        $this->assertEquals($template->getLogicalName(), $name);
    }

    public function getLogicalNameToTemplateProvider()
    {
        return array(
            array('/path/to/section/name.engine', new TemplateReference('/path/to/section/name.engine', 'engine')),
            array('name.engine', new TemplateReference('name.engine', 'engine')),
            array('name', new TemplateReference('name')),
        );
    }
}
PK:1[���xxGTemplating/Symfony/Component/Templating/Tests/Fixtures/SimpleHelper.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Fixtures;

use Symfony\Component\Templating\Helper\Helper;

class SimpleHelper extends Helper
{
    protected $value = '';

    public function __construct($value)
    {
        $this->value = $value;
    }

    public function __toString()
    {
        return $this->value;
    }

    public function getName()
    {
        return 'foo';
    }
}
PK:1[�`�2HTemplating/Symfony/Component/Templating/Tests/Fixtures/templates/foo.phpnu�[���<?php echo $foo ?>
PK;1[=D����ITemplating/Symfony/Component/Templating/Tests/Storage/FileStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Storage;

use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\FileStorage;

class FileStorageTest extends \PHPUnit_Framework_TestCase
{
    public function testGetContent()
    {
        $storage = new FileStorage('foo');
        $this->assertInstanceOf('Symfony\Component\Templating\Storage\Storage', $storage, 'FileStorage is an instance of Storage');
        $storage = new FileStorage(__DIR__.'/../Fixtures/templates/foo.php');
        $this->assertEquals('<?php echo $foo ?>'."\n", $storage->getContent(), '->getContent() returns the content of the template');
    }
}
PK;1[`7�SSKTemplating/Symfony/Component/Templating/Tests/Storage/StringStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Storage;

use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\StringStorage;

class StringStorageTest extends \PHPUnit_Framework_TestCase
{
    public function testGetContent()
    {
        $storage = new StringStorage('foo');
        $this->assertInstanceOf('Symfony\Component\Templating\Storage\Storage', $storage, 'StringStorage is an instance of Storage');
        $storage = new StringStorage('foo');
        $this->assertEquals('foo', $storage->getContent(), '->getContent() returns the content of the template');
    }
}
PK;1[S	�٦�ETemplating/Symfony/Component/Templating/Tests/Storage/StorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Storage;

use Symfony\Component\Templating\Storage\Storage;

class StorageTest extends \PHPUnit_Framework_TestCase
{
    public function testMagicToString()
    {
        $storage = new TestStorage('foo');
        $this->assertEquals('foo', (string) $storage, '__toString() returns the template name');
    }
}

class TestStorage extends Storage
{
    public function getContent()
    {
    }
}
PK;1[��7���CTemplating/Symfony/Component/Templating/Tests/Loader/LoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Loader;

use Symfony\Component\Templating\Loader\Loader;
use Symfony\Component\Templating\TemplateReferenceInterface;

class LoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSetLogger()
    {
        $loader = new ProjectTemplateLoader4();
        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $loader->setLogger($logger);
        $this->assertSame($logger, $loader->getLogger(), '->setLogger() sets the logger instance');
    }

    public function testGetSetDebugger()
    {
        $loader = new ProjectTemplateLoader4();
        $debugger = $this->getMock('Symfony\Component\Templating\DebuggerInterface');
        $loader->setDebugger($debugger);
        $this->assertSame($debugger, $loader->getDebugger(), '->setDebugger() sets the debugger instance');
    }
}

class ProjectTemplateLoader4 extends Loader
{
    public function load(TemplateReferenceInterface $template)
    {
    }

    public function getLogger()
    {
        return $this->logger;
    }

    public function getDebugger()
    {
        return $this->debugger;
    }

    public function isFresh(TemplateReferenceInterface $template, $time)
    {
        return false;
    }
}
PK;1[Wl�‡�MTemplating/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Loader;

use Symfony\Component\Templating\Loader\FilesystemLoader;
use Symfony\Component\Templating\Storage\FileStorage;
use Symfony\Component\Templating\TemplateReference;

class FilesystemLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    public function testConstructor()
    {
        $pathPattern = self::$fixturesPath.'/templates/%name%.%engine%';
        $path = self::$fixturesPath.'/templates';
        $loader = new ProjectTemplateLoader2($pathPattern);
        $this->assertEquals(array($pathPattern), $loader->getTemplatePathPatterns(), '__construct() takes a path as its second argument');
        $loader = new ProjectTemplateLoader2(array($pathPattern));
        $this->assertEquals(array($pathPattern), $loader->getTemplatePathPatterns(), '__construct() takes an array of paths as its second argument');
    }

    public function testIsAbsolutePath()
    {
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('/foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('c:\\\\foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('c:/foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('\\server\\foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('https://server/foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
        $this->assertTrue(ProjectTemplateLoader2::isAbsolutePath('phar://server/foo.xml'), '->isAbsolutePath() returns true if the path is an absolute path');
    }

    public function testLoad()
    {
        $pathPattern = self::$fixturesPath.'/templates/%name%';
        $path = self::$fixturesPath.'/templates';
        $loader = new ProjectTemplateLoader2($pathPattern);
        $storage = $loader->load(new TemplateReference($path.'/foo.php', 'php'));
        $this->assertInstanceOf('Symfony\Component\Templating\Storage\FileStorage', $storage, '->load() returns a FileStorage if you pass an absolute path');
        $this->assertEquals($path.'/foo.php', (string) $storage, '->load() returns a FileStorage pointing to the passed absolute path');

        $this->assertFalse($loader->load(new TemplateReference('bar', 'php')), '->load() returns false if the template is not found');

        $storage = $loader->load(new TemplateReference('foo.php', 'php'));
        $this->assertInstanceOf('Symfony\Component\Templating\Storage\FileStorage', $storage, '->load() returns a FileStorage if you pass a relative template that exists');
        $this->assertEquals($path.'/foo.php', (string) $storage, '->load() returns a FileStorage pointing to the absolute path of the template');

        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->exactly(2))->method('debug');

        $loader = new ProjectTemplateLoader2($pathPattern);
        $loader->setLogger($logger);
        $this->assertFalse($loader->load(new TemplateReference('foo.xml', 'php')), '->load() returns false if the template does not exist for the given engine');

        $loader = new ProjectTemplateLoader2(array(self::$fixturesPath.'/null/%name%', $pathPattern));
        $loader->setLogger($logger);
        $loader->load(new TemplateReference('foo.php', 'php'));
    }
}

class ProjectTemplateLoader2 extends FilesystemLoader
{
    public function getTemplatePathPatterns()
    {
        return $this->templatePathPatterns;
    }

    public static function isAbsolutePath($path)
    {
        return parent::isAbsolutePath($path);
    }
}
PK;1[���
�
HTemplating/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Loader;

use Symfony\Component\Templating\Loader\Loader;
use Symfony\Component\Templating\Loader\CacheLoader;
use Symfony\Component\Templating\Storage\StringStorage;
use Symfony\Component\Templating\TemplateReferenceInterface;
use Symfony\Component\Templating\TemplateReference;

class CacheLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $loader = new ProjectTemplateLoader($varLoader = new ProjectTemplateLoaderVar(), sys_get_temp_dir());
        $this->assertTrue($loader->getLoader() === $varLoader, '__construct() takes a template loader as its first argument');
        $this->assertEquals(sys_get_temp_dir(), $loader->getDir(), '__construct() takes a directory where to store the cache as its second argument');
    }

    public function testLoad()
    {
        $dir = sys_get_temp_dir().DIRECTORY_SEPARATOR.rand(111111, 999999);
        mkdir($dir, 0777, true);

        $loader = new ProjectTemplateLoader($varLoader = new ProjectTemplateLoaderVar(), $dir);
        $this->assertFalse($loader->load(new TemplateReference('foo', 'php')), '->load() returns false if the embed loader is not able to load the template');

        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->once())->method('debug')->with('Storing template "index" in cache');
        $loader->setLogger($logger);
        $loader->load(new TemplateReference('index'));

        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->once())->method('debug')->with('Fetching template "index" from cache');
        $loader->setLogger($logger);
        $loader->load(new TemplateReference('index'));
    }
}

class ProjectTemplateLoader extends CacheLoader
{
    public function getDir()
    {
        return $this->dir;
    }

    public function getLoader()
    {
        return $this->loader;
    }
}

class ProjectTemplateLoaderVar extends Loader
{
    public function getIndexTemplate()
    {
        return 'Hello World';
    }

    public function getSpecialTemplate()
    {
        return 'Hello {{ name }}';
    }

    public function load(TemplateReferenceInterface $template)
    {
        if (method_exists($this, $method = 'get'.ucfirst($template->get('name')).'Template')) {
            return new StringStorage($this->$method());
        }

        return false;
    }

    public function isFresh(TemplateReferenceInterface $template, $time)
    {
        return false;
    }
}
PK;1[ˡA`��HTemplating/Symfony/Component/Templating/Tests/Loader/ChainLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Loader;

use Symfony\Component\Templating\Loader\ChainLoader;
use Symfony\Component\Templating\Loader\FilesystemLoader;
use Symfony\Component\Templating\Storage\FileStorage;
use Symfony\Component\Templating\TemplateReference;

class ChainLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected $loader1;
    protected $loader2;

    protected function setUp()
    {
        $fixturesPath = realpath(__DIR__.'/../Fixtures/');
        $this->loader1 = new FilesystemLoader($fixturesPath.'/null/%name%');
        $this->loader2 = new FilesystemLoader($fixturesPath.'/templates/%name%');
    }

    public function testConstructor()
    {
        $loader = new ProjectTemplateLoader1(array($this->loader1, $this->loader2));
        $this->assertEquals(array($this->loader1, $this->loader2), $loader->getLoaders(), '__construct() takes an array of template loaders as its second argument');
    }

    public function testAddLoader()
    {
        $loader = new ProjectTemplateLoader1(array($this->loader1));
        $loader->addLoader($this->loader2);
        $this->assertEquals(array($this->loader1, $this->loader2), $loader->getLoaders(), '->addLoader() adds a template loader at the end of the loaders');
    }

    public function testLoad()
    {
        $loader = new ProjectTemplateLoader1(array($this->loader1, $this->loader2));
        $this->assertFalse($loader->load(new TemplateReference('bar', 'php')), '->load() returns false if the template is not found');
        $this->assertFalse($loader->load(new TemplateReference('foo', 'php')), '->load() returns false if the template does not exist for the given renderer');
        $this->assertInstanceOf(
            'Symfony\Component\Templating\Storage\FileStorage',
            $loader->load(new TemplateReference('foo.php', 'php')),
            '->load() returns a FileStorage if the template exists'
        );
    }
}

class ProjectTemplateLoader1 extends ChainLoader
{
    public function getLoaders()
    {
        return $this->loaders;
    }
}
PK;1[�`n}�
�
ITemplating/Symfony/Component/Templating/Tests/Helper/AssetsHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Helper;

use Symfony\Component\Templating\Helper\AssetsHelper;

class AssetsHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testGetVersion()
    {
        $helper = new AssetsHelper(null, array(), 'foo');
        $this->assertEquals('foo', $helper->getVersion(), '->getVersion() returns the version');
    }

    public function testGetUrl()
    {
        $helper = new AssetsHelper();
        $this->assertEquals('http://example.com/foo.js', $helper->getUrl('http://example.com/foo.js'), '->getUrl() does nothing if an absolute URL is given');

        $helper = new AssetsHelper();
        $this->assertEquals('/foo.js', $helper->getUrl('foo.js'), '->getUrl() appends a / on relative paths');
        $this->assertEquals('/foo.js', $helper->getUrl('/foo.js'), '->getUrl() does nothing on absolute paths');

        $helper = new AssetsHelper('/foo');
        $this->assertEquals('/foo/foo.js', $helper->getUrl('foo.js'), '->getUrl() appends the basePath on relative paths');
        $this->assertEquals('/foo.js', $helper->getUrl('/foo.js'), '->getUrl() does not append the basePath on absolute paths');

        $helper = new AssetsHelper(null, 'http://assets.example.com/');
        $this->assertEquals('http://assets.example.com/foo.js', $helper->getUrl('foo.js'), '->getUrl() prepends the base URL');
        $this->assertEquals('http://assets.example.com/foo.js', $helper->getUrl('/foo.js'), '->getUrl() prepends the base URL');

        $helper = new AssetsHelper(null, 'http://www.example.com/foo');
        $this->assertEquals('http://www.example.com/foo/foo.js', $helper->getUrl('foo.js'), '->getUrl() prepends the base URL with a path');
        $this->assertEquals('http://www.example.com/foo/foo.js', $helper->getUrl('/foo.js'), '->getUrl() prepends the base URL with a path');

        $helper = new AssetsHelper('/foo', 'http://www.example.com/');
        $this->assertEquals('http://www.example.com/foo.js', $helper->getUrl('foo.js'), '->getUrl() prepends the base URL and the base path if defined');
        $this->assertEquals('http://www.example.com/foo.js', $helper->getUrl('/foo.js'), '->getUrl() prepends the base URL but not the base path on absolute paths');

        $helper = new AssetsHelper('/bar', 'http://www.example.com/foo');
        $this->assertEquals('http://www.example.com/foo/foo.js', $helper->getUrl('foo.js'), '->getUrl() prepends the base URL and the base path if defined');
        $this->assertEquals('http://www.example.com/foo/foo.js', $helper->getUrl('/foo.js'), '->getUrl() prepends the base URL but not the base path on absolute paths');

        $helper = new AssetsHelper('/bar', 'http://www.example.com/foo', 'abcd');
        $this->assertEquals('http://www.example.com/foo/foo.js?abcd', $helper->getUrl('foo.js'), '->getUrl() appends the version if defined');

        $helper = new AssetsHelper();
        $this->assertEquals('/', $helper->getUrl(''), '->getUrl() with empty arg returns the prefix alone');
    }

    public function testGetUrlLeavesProtocolRelativePathsUntouched()
    {
        $helper = new AssetsHelper(null, 'http://foo.com');
        $this->assertEquals('//bar.com/asset', $helper->getUrl('//bar.com/asset'));
    }
}
PK;1[�q=R

CTemplating/Symfony/Component/Templating/Tests/Helper/HelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Helper;

use Symfony\Component\Templating\Helper\Helper;

class HelperTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSetCharset()
    {
        $helper = new ProjectTemplateHelper();
        $helper->setCharset('ISO-8859-1');
        $this->assertTrue('ISO-8859-1' === $helper->getCharset(), '->setCharset() sets the charset set related to this helper');
    }
}

class ProjectTemplateHelper extends Helper
{
    public function getName()
    {
        return 'foo';
    }
}
PK;1[M<��MTemplating/Symfony/Component/Templating/Tests/Helper/CoreAssetsHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Helper;

use Symfony\Component\Templating\Helper\CoreAssetsHelper;

class CoreAssetsHelperTest extends \PHPUnit_Framework_TestCase
{
    protected $package;

    protected function setUp()
    {
        $this->package = $this->getMock('Symfony\Component\Templating\Asset\PackageInterface');
    }

    protected function tearDown()
    {
        $this->package = null;
    }

    public function testAddGetPackage()
    {
        $helper = new CoreAssetsHelper($this->package);

        $helper->addPackage('foo', $this->package);

        $this->assertSame($this->package, $helper->getPackage('foo'));
    }

    public function testGetNonexistingPackage()
    {
        $helper = new CoreAssetsHelper($this->package);

        $this->setExpectedException('\InvalidArgumentException');

        $helper->getPackage('foo');
    }

    public function testGetHelperName()
    {
        $helper = new CoreAssetsHelper($this->package);

        $this->assertEquals('assets', $helper->getName());
    }
}
PK;1[0�nl

HTemplating/Symfony/Component/Templating/Tests/Helper/SlotsHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests\Helper;

use Symfony\Component\Templating\Helper\SlotsHelper;

class SlotsHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testHasGetSet()
    {
        $helper = new SlotsHelper();
        $helper->set('foo', 'bar');
        $this->assertEquals('bar', $helper->get('foo'), '->set() sets a slot value');
        $this->assertEquals('bar', $helper->get('bar', 'bar'), '->get() takes a default value to return if the slot does not exist');

        $this->assertTrue($helper->has('foo'), '->has() returns true if the slot exists');
        $this->assertFalse($helper->has('bar'), '->has() returns false if the slot does not exist');
    }

    public function testOutput()
    {
        $helper = new SlotsHelper();
        $helper->set('foo', 'bar');
        ob_start();
        $ret = $helper->output('foo');
        $output = ob_get_clean();
        $this->assertEquals('bar', $output, '->output() outputs the content of a slot');
        $this->assertTrue($ret, '->output() returns true if the slot exists');

        ob_start();
        $ret = $helper->output('bar', 'bar');
        $output = ob_get_clean();
        $this->assertEquals('bar', $output, '->output() takes a default value to return if the slot does not exist');
        $this->assertTrue($ret, '->output() returns true if the slot does not exist but a default value is provided');

        ob_start();
        $ret = $helper->output('bar');
        $output = ob_get_clean();
        $this->assertEquals('', $output, '->output() outputs nothing if the slot does not exist');
        $this->assertFalse($ret, '->output() returns false if the slot does not exist');
    }

    public function testStartStop()
    {
        $helper = new SlotsHelper();
        $helper->start('bar');
        echo 'foo';
        $helper->stop();
        $this->assertEquals('foo', $helper->get('bar'), '->start() starts a slot');
        $this->assertTrue($helper->has('bar'), '->starts() starts a slot');

        $helper->start('bar');
        try {
            $helper->start('bar');
            $helper->stop();
            $this->fail('->start() throws an InvalidArgumentException if a slot with the same name is already started');
        } catch (\Exception $e) {
            $helper->stop();
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->start() throws an InvalidArgumentException if a slot with the same name is already started');
            $this->assertEquals('A slot named "bar" is already started.', $e->getMessage(), '->start() throws an InvalidArgumentException if a slot with the same name is already started');
        }

        try {
            $helper->stop();
            $this->fail('->stop() throws an LogicException if no slot is started');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\LogicException', $e, '->stop() throws an LogicException if no slot is started');
            $this->assertEquals('No slot started.', $e->getMessage(), '->stop() throws an LogicException if no slot is started');
        }
    }
}
PK;1[��`#`#?Templating/Symfony/Component/Templating/Tests/PhpEngineTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests;

use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Templating\Loader\Loader;
use Symfony\Component\Templating\Storage\Storage;
use Symfony\Component\Templating\Storage\StringStorage;
use Symfony\Component\Templating\Helper\SlotsHelper;
use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Component\Templating\TemplateReferenceInterface;
use Symfony\Component\Templating\TemplateReference;

class PhpEngineTest extends \PHPUnit_Framework_TestCase
{
    protected $loader;

    protected function setUp()
    {
        $this->loader = new ProjectTemplateLoader();
    }

    protected function tearDown()
    {
        $this->loader = null;
    }

    public function testConstructor()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $this->assertEquals($this->loader, $engine->getLoader(), '__construct() takes a loader instance as its second first argument');
    }

    public function testOffsetGet()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $engine->set($helper = new \Symfony\Component\Templating\Tests\Fixtures\SimpleHelper('bar'), 'foo');
        $this->assertEquals($helper, $engine['foo'], '->offsetGet() returns the value of a helper');

        try {
            $engine['bar'];
            $this->fail('->offsetGet() throws an InvalidArgumentException if the helper is not defined');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->offsetGet() throws an InvalidArgumentException if the helper is not defined');
            $this->assertEquals('The helper "bar" is not defined.', $e->getMessage(), '->offsetGet() throws an InvalidArgumentException if the helper is not defined');
        }
    }

    public function testGetSetHas()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $foo = new \Symfony\Component\Templating\Tests\Fixtures\SimpleHelper('foo');
        $engine->set($foo);
        $this->assertEquals($foo, $engine->get('foo'), '->set() sets a helper');

        $engine[$foo] = 'bar';
        $this->assertEquals($foo, $engine->get('bar'), '->set() takes an alias as a second argument');

        $this->assertTrue(isset($engine['bar']));

        try {
            $engine->get('foobar');
            $this->fail('->get() throws an InvalidArgumentException if the helper is not defined');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws an InvalidArgumentException if the helper is not defined');
            $this->assertEquals('The helper "foobar" is not defined.', $e->getMessage(), '->get() throws an InvalidArgumentException if the helper is not defined');
        }

        $this->assertTrue(isset($engine['bar']));
        $this->assertTrue($engine->has('foo'), '->has() returns true if the helper exists');
        $this->assertFalse($engine->has('foobar'), '->has() returns false if the helper does not exist');
    }

    public function testUnsetHelper()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $foo = new \Symfony\Component\Templating\Tests\Fixtures\SimpleHelper('foo');
        $engine->set($foo);

        $this->setExpectedException('\LogicException');

        unset($engine['foo']);
    }

    public function testExtendRender()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader, array(), array(new SlotsHelper()));
        try {
            $engine->render('name');
            $this->fail('->render() throws an InvalidArgumentException if the template does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->render() throws an InvalidArgumentException if the template does not exist');
            $this->assertEquals('The template "name" does not exist.', $e->getMessage(), '->render() throws an InvalidArgumentException if the template does not exist');
        }

        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader, array(new SlotsHelper()));
        $engine->set(new \Symfony\Component\Templating\Tests\Fixtures\SimpleHelper('bar'));
        $this->loader->setTemplate('foo.php', '<?php $view->extend("layout.php"); echo $view[\'foo\'].$foo ?>');
        $this->loader->setTemplate('layout.php', '-<?php echo $view[\'slots\']->get("_content") ?>-');
        $this->assertEquals('-barfoo-', $engine->render('foo.php', array('foo' => 'foo')), '->render() uses the decorator to decorate the template');

        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader, array(new SlotsHelper()));
        $engine->set(new \Symfony\Component\Templating\Tests\Fixtures\SimpleHelper('bar'));
        $this->loader->setTemplate('bar.php', 'bar');
        $this->loader->setTemplate('foo.php', '<?php $view->extend("layout.php"); echo $foo ?>');
        $this->loader->setTemplate('layout.php', '<?php echo $view->render("bar.php") ?>-<?php echo $view[\'slots\']->get("_content") ?>-');
        $this->assertEquals('bar-foo-', $engine->render('foo.php', array('foo' => 'foo', 'bar' => 'bar')), '->render() supports render() calls in templates');
    }

    public function testRenderParameter()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $this->loader->setTemplate('foo.php', '<?php echo $template . $parameters ?>');
        $this->assertEquals('foobar', $engine->render('foo.php', array('template' => 'foo', 'parameters' => 'bar')), '->render() extract variables');
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider forbiddenParameterNames
     */
    public function testRenderForbiddenParameter($name)
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $this->loader->setTemplate('foo.php', 'bar');
        $engine->render('foo.php', array($name => 'foo'));
    }

    public function forbiddenParameterNames()
    {
        return array(
            array('this'),
            array('view'),
        );
    }

    public function testEscape()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $this->assertEquals('&lt;br /&gt;', $engine->escape('<br />'), '->escape() escapes strings');
        $foo = new \stdClass();
        $this->assertEquals($foo, $engine->escape($foo), '->escape() does nothing on non strings');
    }

    public function testGetSetCharset()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $this->assertEquals('UTF-8', $engine->getCharset(), '->getCharset() returns UTF-8 by default');
        $engine->setCharset('ISO-8859-1');
        $this->assertEquals('ISO-8859-1', $engine->getCharset(), '->setCharset() changes the default charset to use');
    }

    public function testGlobalVariables()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $engine->addGlobal('global_variable', 'lorem ipsum');

        $this->assertEquals(array(
            'global_variable' => 'lorem ipsum',
        ), $engine->getGlobals());
    }

    public function testGlobalsGetPassedToTemplate()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);
        $engine->addGlobal('global', 'global variable');

        $this->loader->setTemplate('global.php', '<?php echo $global; ?>');

        $this->assertEquals($engine->render('global.php'), 'global variable');

        $this->assertEquals($engine->render('global.php', array('global' => 'overwritten')), 'overwritten');
    }

    public function testGetLoader()
    {
        $engine = new ProjectTemplateEngine(new TemplateNameParser(), $this->loader);

        $this->assertSame($this->loader, $engine->getLoader());
    }
}

class ProjectTemplateEngine extends PhpEngine
{
    public function getLoader()
    {
        return $this->loader;
    }
}

class ProjectTemplateLoader extends Loader
{
    public $templates = array();

    public function setTemplate($name, $content)
    {
        $template = new TemplateReference($name, 'php');
        $this->templates[$template->getLogicalName()] = $content;
    }

    public function load(TemplateReferenceInterface $template)
    {
        if (isset($this->templates[$template->getLogicalName()])) {
            return new StringStorage($this->templates[$template->getLogicalName()]);
        }

        return false;
    }

    public function isFresh(TemplateReferenceInterface $template, $time)
    {
        return false;
    }
}
PK;1[�氵�FTemplating/Symfony/Component/Templating/Tests/DelegatingEngineTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Templating\Tests;

use Symfony\Component\Templating\DelegatingEngine;
use Symfony\Component\Templating\StreamingEngineInterface;
use Symfony\Component\Templating\EngineInterface;

class DelegatingEngineTest extends \PHPUnit_Framework_TestCase
{
    public function testRenderDelegatesToSupportedEngine()
    {
        $firstEngine = $this->getEngineMock('template.php', false);
        $secondEngine = $this->getEngineMock('template.php', true);

        $secondEngine->expects($this->once())
            ->method('render')
            ->with('template.php', array('foo' => 'bar'))
            ->will($this->returnValue('<html />'));

        $delegatingEngine = new DelegatingEngine(array($firstEngine, $secondEngine));
        $result = $delegatingEngine->render('template.php', array('foo' => 'bar'));

        $this->assertSame('<html />', $result);
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage No engine is able to work with the template "template.php"
     */
    public function testRenderWithNoSupportedEngine()
    {
        $firstEngine = $this->getEngineMock('template.php', false);
        $secondEngine = $this->getEngineMock('template.php', false);

        $delegatingEngine = new DelegatingEngine(array($firstEngine, $secondEngine));
        $delegatingEngine->render('template.php', array('foo' => 'bar'));
    }

    public function testStreamDelegatesToSupportedEngine()
    {
        $streamingEngine = $this->getStreamingEngineMock('template.php', true);
        $streamingEngine->expects($this->once())
            ->method('stream')
            ->with('template.php', array('foo' => 'bar'))
            ->will($this->returnValue('<html />'));

        $delegatingEngine = new DelegatingEngine(array($streamingEngine));
        $result = $delegatingEngine->stream('template.php', array('foo' => 'bar'));

        $this->assertNull($result);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Template "template.php" cannot be streamed as the engine supporting it does not implement StreamingEngineInterface
     */
    public function testStreamRequiresStreamingEngine()
    {
        $engine = $this->getEngineMock('template.php', true);
        $engine->expects($this->never())->method('stream');

        $delegatingEngine = new DelegatingEngine(array($engine));
        $delegatingEngine->stream('template.php', array('foo' => 'bar'));
    }

    public function testExists()
    {
        $engine = $this->getEngineMock('template.php', true);
        $engine->expects($this->once())
            ->method('exists')
            ->with('template.php')
            ->will($this->returnValue(true));

        $delegatingEngine = new DelegatingEngine(array($engine));

        $this->assertTrue($delegatingEngine->exists('template.php'));
    }

    public function testSupports()
    {
        $engine = $this->getEngineMock('template.php', true);

        $delegatingEngine = new DelegatingEngine(array($engine));

        $this->assertTrue($delegatingEngine->supports('template.php'));
    }

    public function testSupportsWithNoSupportedEngine()
    {
        $engine = $this->getEngineMock('template.php', false);

        $delegatingEngine = new DelegatingEngine(array($engine));

        $this->assertFalse($delegatingEngine->supports('template.php'));
    }

    public function testGetExistingEngine()
    {
        $firstEngine = $this->getEngineMock('template.php', false);
        $secondEngine = $this->getEngineMock('template.php', true);

        $delegatingEngine = new DelegatingEngine(array($firstEngine, $secondEngine));

        $this->assertSame($secondEngine, $delegatingEngine->getEngine('template.php'));
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage No engine is able to work with the template "template.php"
     */
    public function testGetInvalidEngine()
    {
        $firstEngine = $this->getEngineMock('template.php', false);
        $secondEngine = $this->getEngineMock('template.php', false);

        $delegatingEngine = new DelegatingEngine(array($firstEngine, $secondEngine));
        $delegatingEngine->getEngine('template.php', array('foo' => 'bar'));
    }

    private function getEngineMock($template, $supports)
    {
        $engine = $this->getMock('Symfony\Component\Templating\EngineInterface');

        $engine->expects($this->once())
            ->method('supports')
            ->with($template)
            ->will($this->returnValue($supports));

        return $engine;
    }

    private function getStreamingEngineMock($template, $supports)
    {
        $engine = $this->getMockForAbstractClass('Symfony\Component\Templating\Tests\MyStreamingEngine');

        $engine->expects($this->once())
            ->method('supports')
            ->with($template)
            ->will($this->returnValue($supports));

        return $engine;
    }
}

interface MyStreamingEngine extends StreamingEngineInterface, EngineInterface
{
}
PK;1[�%�D998Templating/Symfony/Component/Templating/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Templating Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK<1[��Q��0Yaml/Symfony/Component/Yaml/Tests/DumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Dumper;

class DumperTest extends \PHPUnit_Framework_TestCase
{
    protected $parser;
    protected $dumper;
    protected $path;

    protected $array = array(
        '' => 'bar',
        'foo' => '#bar',
        'foo\'bar' => array(),
        'bar' => array(1, 'foo'),
        'foobar' => array(
            'foo' => 'bar',
            'bar' => array(1, 'foo'),
            'foobar' => array(
                'foo' => 'bar',
                'bar' => array(1, 'foo'),
            ),
        ),
    );

    protected function setUp()
    {
        $this->parser = new Parser();
        $this->dumper = new Dumper();
        $this->path = __DIR__.'/Fixtures';
    }

    protected function tearDown()
    {
        $this->parser = null;
        $this->dumper = null;
        $this->path = null;
        $this->array = null;
    }

    public function testSetIndentation()
    {
        $this->dumper->setIndentation(7);

$expected = <<<EOF
'': bar
foo: '#bar'
'foo''bar': {  }
bar:
       - 1
       - foo
foobar:
       foo: bar
       bar:
              - 1
              - foo
       foobar:
              foo: bar
              bar:
                     - 1
                     - foo

EOF;
        $this->assertEquals($expected, $this->dumper->dump($this->array, 4, 0));
    }

    public function testSpecifications()
    {
        $files = $this->parser->parse(file_get_contents($this->path.'/index.yml'));
        foreach ($files as $file) {
            $yamls = file_get_contents($this->path.'/'.$file.'.yml');

            // split YAMLs documents
            foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) {
                if (!$yaml) {
                    continue;
                }

                $test = $this->parser->parse($yaml);
                if (isset($test['dump_skip']) && $test['dump_skip']) {
                    continue;
                } elseif (isset($test['todo']) && $test['todo']) {
                    // TODO
                } else {
                    eval('$expected = '.trim($test['php']).';');

                    $this->assertEquals($expected, $this->parser->parse($this->dumper->dump($expected, 10)), $test['test']);
                }
            }
        }
    }

    public function testInlineLevel()
    {
        $expected = <<<EOF
{ '': bar, foo: '#bar', 'foo''bar': {  }, bar: [1, foo], foobar: { foo: bar, bar: [1, foo], foobar: { foo: bar, bar: [1, foo] } } }
EOF;
$this->assertEquals($expected, $this->dumper->dump($this->array, -10), '->dump() takes an inline level argument');
$this->assertEquals($expected, $this->dumper->dump($this->array, 0), '->dump() takes an inline level argument');

$expected = <<<EOF
'': bar
foo: '#bar'
'foo''bar': {  }
bar: [1, foo]
foobar: { foo: bar, bar: [1, foo], foobar: { foo: bar, bar: [1, foo] } }

EOF;
        $this->assertEquals($expected, $this->dumper->dump($this->array, 1), '->dump() takes an inline level argument');

        $expected = <<<EOF
'': bar
foo: '#bar'
'foo''bar': {  }
bar:
    - 1
    - foo
foobar:
    foo: bar
    bar: [1, foo]
    foobar: { foo: bar, bar: [1, foo] }

EOF;
        $this->assertEquals($expected, $this->dumper->dump($this->array, 2), '->dump() takes an inline level argument');

        $expected = <<<EOF
'': bar
foo: '#bar'
'foo''bar': {  }
bar:
    - 1
    - foo
foobar:
    foo: bar
    bar:
        - 1
        - foo
    foobar:
        foo: bar
        bar: [1, foo]

EOF;
        $this->assertEquals($expected, $this->dumper->dump($this->array, 3), '->dump() takes an inline level argument');

        $expected = <<<EOF
'': bar
foo: '#bar'
'foo''bar': {  }
bar:
    - 1
    - foo
foobar:
    foo: bar
    bar:
        - 1
        - foo
    foobar:
        foo: bar
        bar:
            - 1
            - foo

EOF;
        $this->assertEquals($expected, $this->dumper->dump($this->array, 4), '->dump() takes an inline level argument');
        $this->assertEquals($expected, $this->dumper->dump($this->array, 10), '->dump() takes an inline level argument');
    }

    public function testObjectSupportEnabled()
    {
        $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, false, true);

        $this->assertEquals('{ foo: !!php/object:O:30:"Symfony\Component\Yaml\Tests\A":1:{s:1:"a";s:3:"foo";}, bar: 1 }', $dump, '->dump() is able to dump objects');
    }

    public function testObjectSupportDisabledButNoExceptions()
    {
        $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1));

        $this->assertEquals('{ foo: null, bar: 1 }', $dump, '->dump() does not dump objects when disabled');
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\DumpException
     */
    public function testObjectSupportDisabledWithExceptions()
    {
        $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, true, false);
    }
}

class A
{
    public $a = 'foo';
}
PK<1[�����>Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBlockMapping.ymlnu�[���---
test: One Element Mapping
brief: |
    A mapping with one key/value pair
yaml: |
    foo: bar
php: |
    array('foo' => 'bar')
---
test: Multi Element Mapping
brief: |
    More than one key/value pair
yaml: |
    red: baron
    white: walls
    blue: berries
php: |
    array(
     'red' => 'baron',
     'white' => 'walls',
     'blue' => 'berries',
    )
---
test: Values aligned
brief: |
    Often times human editors of documents will align the values even
    though YAML emitters generally don't.
yaml: |
    red:   baron
    white: walls
    blue:  berries
php: |
    array(
     'red' => 'baron',
     'white' => 'walls',
     'blue' => 'berries',
    )
---
test: Colons aligned
brief: |
    Spaces can come before the ': ' key/value separator.
yaml: |
    red   : baron
    white : walls
    blue  : berries
php: |
    array(
     'red' => 'baron',
     'white' => 'walls',
     'blue' => 'berries',
    )
PK<1[��UU8Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfCompact.ymlnu�[���--- %YAML:1.0
test: Compact notation
brief: |
    Compact notation for sets of mappings with single element
yaml: |
  ---
  # products purchased
  - item    : Super Hoop
  - item    : Basketball
    quantity: 1
  - item:
      name: Big Shoes
      nick: Biggies
    quantity: 1
php: |
  array (
    array (
      'item' => 'Super Hoop',
    ),
    array (
      'item' => 'Basketball',
      'quantity' => 1,
    ),
    array (
      'item' => array(
        'name' => 'Big Shoes',
        'nick' => 'Biggies'
      ),
      'quantity' => 1
    )
  )
---
test: Compact notation combined with inline notation
brief: |
    Combinations of compact and inline notation are allowed
yaml: |
  ---
  items:
    - { item: Super Hoop, quantity: 1 }
    - [ Basketball, Big Shoes ]
php: |
  array (
    'items' => array (
      array (
        'item' => 'Super Hoop',
        'quantity' => 1,
      ),
      array (
        'Basketball',
        'Big Shoes'
      )
    )
  )
--- %YAML:1.0
test: Compact notation
brief: |
    Compact notation for sets of mappings with single element
yaml: |
  ---
  # products purchased
  - item    : Super Hoop
  - item    : Basketball
    quantity: 1
  - item:
      name: Big Shoes
      nick: Biggies
    quantity: 1
php: |
  array (
    array (
      'item' => 'Super Hoop',
    ),
    array (
      'item' => 'Basketball',
      'quantity' => 1,
    ),
    array (
      'item' => array(
        'name' => 'Big Shoes',
        'nick' => 'Biggies'
      ),
      'quantity' => 1
    )
  )
---
test: Compact notation combined with inline notation
brief: |
    Combinations of compact and inline notation are allowed
yaml: |
  ---
  items:
    - { item: Super Hoop, quantity: 1 }
    - [ Basketball, Big Shoes ]
php: |
  array (
    'items' => array (
      array (
        'item' => 'Super Hoop',
        'quantity' => 1,
      ),
      array (
        'Basketball',
        'Big Shoes'
      )
    )
  )
--- %YAML:1.0
test: Compact notation
brief: |
    Compact notation for sets of mappings with single element
yaml: |
  ---
  # products purchased
  - item    : Super Hoop
  - item    : Basketball
    quantity: 1
  - item:
      name: Big Shoes
      nick: Biggies
    quantity: 1
php: |
  array (
    array (
      'item' => 'Super Hoop',
    ),
    array (
      'item' => 'Basketball',
      'quantity' => 1,
    ),
    array (
      'item' => array(
        'name' => 'Big Shoes',
        'nick' => 'Biggies'
      ),
      'quantity' => 1
    )
  )
---
test: Compact notation combined with inline notation
brief: |
    Combinations of compact and inline notation are allowed
yaml: |
  ---
  items:
    - { item: Super Hoop, quantity: 1 }
    - [ Basketball, Big Shoes ]
php: |
  array (
    'items' => array (
      array (
        'item' => 'Super Hoop',
        'quantity' => 1,
      ),
      array (
        'Basketball',
        'Big Shoes'
      )
    )
  )
PK<1[�5�R[[=Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsAnchorAlias.ymlnu�[���--- %YAML:1.0
test: Simple Alias Example
brief: >
    If you need to refer to the same item of data twice,
    you can give that item an alias.  The alias is a plain
    string, starting with an ampersand.  The item may then
    be referred to by the alias throughout your document
    by using an asterisk before the name of the alias.
    This is called an anchor.
yaml: |
    - &showell Steve
    - Clark
    - Brian
    - Oren
    - *showell
php: |
    array('Steve', 'Clark', 'Brian', 'Oren', 'Steve')

---
test: Alias of a Mapping
brief: >
    An alias can be used on any item of data, including
    sequences, mappings, and other complex data types.
yaml: |
    - &hello
        Meat: pork
        Starch: potato
    - banana
    - *hello
php: |
    array(array('Meat'=>'pork', 'Starch'=>'potato'), 'banana', array('Meat'=>'pork', 'Starch'=>'potato'))
PK<1[U���6Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfTests.ymlnu�[���--- %YAML:1.0
test: Multiple quoted string on one line
brief: >
    Multiple quoted string on one line
yaml: |
    stripped_title: { name: "foo bar", help: "bar foo" }
php: |
    array('stripped_title' => array('name' => 'foo bar', 'help' => 'bar foo'))
---
test: Empty sequence
yaml: |
    foo: [ ]
php: |
    array('foo' => array())
---
test: Empty value
yaml: |
    foo:
php: |
    array('foo' => null)
---
test: Inline string parsing
brief: >
    Inline string parsing
yaml: |
    test: ['complex: string', 'another [string]']
php: |
    array('test' => array('complex: string', 'another [string]'))
---
test: Boolean
brief: >
    Boolean
yaml: |
    - false
    - true
    - null
    - ~
    - 'false'
    - 'true'
    - 'null'
    - '~'
php: |
    array(
      false,
      true,
      null,
      null,
      'false',
      'true',
      'null',
      '~',
    )
---
test: Empty lines in folded blocks
brief: >
  Empty lines in folded blocks
yaml: |
  foo:
    bar: |
      foo


        
      bar
php: |
  array('foo' => array('bar' => "foo\n\n\n  \nbar\n"))
---
test: IP addresses
brief: >
  IP addresses
yaml: |
  foo: 10.0.0.2
php: |
  array('foo' => '10.0.0.2')
---
test: A sequence with an embedded mapping
brief: >
  A sequence with an embedded mapping
yaml: |
  - foo
  - bar: { bar: foo }
php: |
  array('foo', array('bar' => array('bar' => 'foo')))
---
test: A sequence with an unordered array
brief: >
  A sequence with an unordered array
yaml: |
  1: foo
  0: bar
php: |
  array(1 => 'foo', 0 => 'bar')
---
test: Octal
brief: as in spec example 2.19, octal value is converted
yaml: |
  foo: 0123
php: |
  array('foo' => 83)
---
test: Octal strings
brief: Octal notation in a string must remain a string
yaml: |
  foo: "0123"
php: |
  array('foo' => '0123')
---
test: Octal strings
brief: Octal notation in a string must remain a string
yaml: |
  foo: '0123'
php: |
  array('foo' => '0123')
---
test: Octal strings
brief: Octal notation in a string must remain a string
yaml: |
  foo: |
    0123
php: |
  array('foo' => "0123\n")
---
test: Document as a simple hash
brief: Document as a simple hash
yaml: |
  { foo: bar }
php: |
  array('foo' => 'bar')
---
test: Document as a simple array
brief: Document as a simple array
yaml: |
  [ foo, bar ]
php: |
  array('foo', 'bar')
PK<1[�@�UU9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfComments.ymlnu�[���--- %YAML:1.0
test: Comments at the end of a line
brief: >
    Comments at the end of a line
yaml: |
    ex1: "foo # bar"
    ex2: "foo # bar" # comment
    ex3: 'foo # bar' # comment
    ex4: foo # comment
php: |
    array('ex1' => 'foo # bar', 'ex2' => 'foo # bar', 'ex3' => 'foo # bar', 'ex4' => 'foo')
---
test: Comments in the middle
brief: >
  Comments in the middle
yaml: |
    foo:
    # some comment
    # some comment
      bar: foo
    # some comment
    # some comment
php: |
    array('foo' => array('bar' => 'foo'))
---
test: Comments on a hash line
brief: >
  Comments on a hash line
yaml: |
    foo:   # a comment
      foo: bar # a comment
php: |
    array('foo' => array('foo' => 'bar'))
---
test: 'Value starting with a #'
brief: >
  'Value starting with a #'
yaml: |
    foo:   '#bar'
php: |
    array('foo' => '#bar')
---
test: Document starting with a comment and a separator
brief: >
  Commenting before document start is allowed
yaml: |
    # document comment
    ---
    foo: bar # a comment
php: |
    array('foo' => 'bar')
---
test: Comment containing a colon on a hash line
brief: >
    Comment containing a colon on a scalar line
yaml: 'foo # comment: this is also part of the comment'
php: |
    'foo'
---
test: 'Hash key containing a #'
brief: >
    'Hash key containing a #'
yaml: 'foo#bar: baz'
php: |
    array('foo#bar' => 'baz')
PK<1[��--DYaml/Symfony/Component/Yaml/Tests/Fixtures/unindentedCollections.ymlnu�[���--- %YAML:1.0
test: Unindented collection
brief: >
    Unindented collection
yaml: |
    collection:
    - item1
    - item2
    - item3
php: |
    array('collection' => array('item1', 'item2', 'item3'))
---
test: Nested unindented collection (two levels)
brief: >
    Nested unindented collection
yaml: |
    collection:
        key:
        - a
        - b
        - c
php: |
    array('collection' => array('key' => array('a', 'b', 'c')))
---
test: Nested unindented collection (three levels)
brief: >
    Nested unindented collection
yaml: |
    collection:
        key:
            subkey:
            - one
            - two
            - three
php: |
    array('collection' => array('key' => array('subkey' => array('one', 'two', 'three'))))
---
test: Key/value after unindented collection (1)
brief: >
    Key/value after unindented collection (1)
yaml: |
    collection:
        key:
        - a
        - b
        - c
    foo: bar
php: |
    array('collection' => array('key' => array('a', 'b', 'c')), 'foo' => 'bar')
---
test: Key/value after unindented collection (at the same level)
brief: >
    Key/value after unindented collection
yaml: |
    collection:
        key:
        - a
        - b
        - c
        foo: bar
php: |
    array('collection' => array('key' => array('a', 'b', 'c'), 'foo' => 'bar'))
PK<1[�>;���AYaml/Symfony/Component/Yaml/Tests/Fixtures/YtsNullsAndEmpties.ymlnu�[���--- %YAML:1.0
test: Empty Sequence
brief: >
    You can represent the empty sequence
    with an empty inline sequence.
yaml: |
    empty: []
php: |
    array('empty' => array())
---
test: Empty Mapping
brief: >
    You can represent the empty mapping
    with an empty inline mapping.
yaml: |
    empty: {}
php: |
    array('empty' => array())
---
test: Empty Sequence as Entire Document
yaml: |
    []
php: |
    array()
---
test: Empty Mapping as Entire Document
yaml: |
    {}
php: |
    array()
---
test: Null as Document
yaml: |
    ~
php: |
    null
---
test: Empty String
brief: >
    You can represent an empty string
    with a pair of quotes.
yaml: |
    ''
php: |
    ''
PK<1[t��rqq<Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsErrorTests.ymlnu�[���---
test: Missing value for hash item
todo: true
brief: |
    Third item in this hash doesn't have a value
yaml: |
    okay: value
    also okay: ~
    causes error because no value specified
    last key: value okay here too
python-error: causes error because no value specified

---
test: Not indenting enough
brief: |
    There was a bug in PyYaml where it was off by one
    in the indentation check.  It was allowing the YAML
    below.
# This is actually valid YAML now. Someone should tell showell.
yaml: |
    foo:
    firstline: 1
    secondline: 2
php: |
  array('foo' => null, 'firstline' => 1, 'secondline' => 2)
PK<1[Z{k�XXAYaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFlowCollections.ymlnu�[���---
test: Simple Inline Array
brief: >
    Sequences can be contained on a
    single line, using the inline syntax.
    Separate each entry with commas and
    enclose in square brackets.
yaml: |
    seq: [ a, b, c ]
php: |
    array('seq' => array('a', 'b', 'c'))
---
test: Simple Inline Hash
brief: >
    Mapping can also be contained on
    a single line, using the inline
    syntax.  Each key-value pair is
    separated by a colon, with a comma
    between each entry in the mapping.
    Enclose with curly braces.
yaml: |
    hash: { name: Steve, foo: bar }
php: |
    array('hash' => array('name' => 'Steve', 'foo' => 'bar'))
---
test: Multi-line Inline Collections
todo: true
brief: >
    Both inline sequences and inline mappings
    can span multiple lines, provided that you
    indent the additional lines.
yaml: |
    languages: [ Ruby,
                 Perl,
                 Python ]
    websites: { YAML: yaml.org,
                Ruby: ruby-lang.org,
                Python: python.org,
                Perl: use.perl.org }
php: |
    array(
      'languages' => array('Ruby', 'Perl', 'Python'),
      'websites' => array(
        'YAML' => 'yaml.org',
        'Ruby' => 'ruby-lang.org',
        'Python' => 'python.org',
        'Perl' => 'use.perl.org'
      )
    )
---
test: Commas in Values (not in the spec!)
todo: true
brief: >
    List items in collections are delimited by commas, but
    there must be a space after each comma.  This allows you
    to add numbers without quoting.
yaml: |
    attendances: [ 45,123, 70,000, 17,222 ]
php: |
    array('attendances' => array(45123, 70000, 17222))
PK<1[�*���@Yaml/Symfony/Component/Yaml/Tests/Fixtures/escapedCharacters.ymlnu�[���test: outside double quotes
yaml: |
    \0 \ \a \b \n
php: |
    "\\0 \\ \\a \\b \\n"
---
test: null
yaml: |
    "\0"
php: |
    "\x00"
---
test: bell
yaml: |
    "\a"
php: |
    "\x07"
---
test: backspace
yaml: |
    "\b"
php: |
    "\x08"
---
test: horizontal tab (1)
yaml: |
    "\t"
php: |
    "\x09"
---
test: horizontal tab (2)
yaml: |
    "\	"
php: |
    "\x09"
---
test: line feed
yaml: |
    "\n"
php: |
    "\x0a"
---
test: vertical tab
yaml: |
    "\v"
php: |
    "\x0b"
---
test: form feed
yaml: |
    "\f"
php: |
    "\x0c"
---
test: carriage return
yaml: |
    "\r"
php: |
    "\x0d"
---
test: escape
yaml: |
    "\e"
php: |
   "\x1b"
---
test: space
yaml: |
    "\ "
php: |
    "\x20"
---
test: slash
yaml: |
    "\/"
php: |
    "\x2f"
---
test: backslash
yaml: |
    "\\"
php: |
    "\\"
---
test: Unicode next line
yaml: |
    "\N"
php: |
    "\xc2\x85"
---
test: Unicode non-breaking space
yaml: |
    "\_"
php: |
    "\xc2\xa0"
---
test: Unicode line separator
yaml: |
    "\L"
php: |
    "\xe2\x80\xa8"
---
test: Unicode paragraph separator
yaml: |
    "\P"
php: |
    "\xe2\x80\xa9"
---
test: Escaped 8-bit Unicode
yaml: |
    "\x42"
php: |
    "B"
---
test: Escaped 16-bit Unicode
yaml: |
    "\u20ac"
php: |
    "\xe2\x82\xac"
---
test: Escaped 32-bit Unicode
yaml: |
    "\U00000043"
php: |
    "C"
---
test: Example 5.13 Escaped Characters
note: |
    Currently throws an error parsing first line. Maybe Symfony Yaml doesn't support
    continuation of string across multiple lines? Keeping test here but disabled.
todo: true
yaml: |
    "Fun with \\
    \" \a \b \e \f \
    \n \r \t \v \0 \
    \  \_ \N \L \P \
    \x41 \u0041 \U00000041"
php: |
    "Fun with \x5C\n\x22 \x07 \x08 \x1B \x0C\n\x0A \x0D \x09 \x0B \x00\n\x20 \xA0 \x85 \xe2\x80\xa8 \xe2\x80\xa9\nA A A"
---
test: Double quotes with a line feed
yaml: |
   { double: "some value\n \"some quoted string\" and 'some single quotes one'" }
php: |
    array(
        'double' => "some value\n \"some quoted string\" and 'some single quotes one'"
    )
PK<1[֋�O��<Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBasicTests.ymlnu�[���--- %YAML:1.0
test: Simple Sequence
brief: |
    You can specify a list in YAML by placing each
    member of the list on a new line with an opening
    dash. These lists are called sequences.
yaml: |
    - apple
    - banana
    - carrot
php: |
    array('apple', 'banana', 'carrot')
---
test: Nested Sequences
brief: |
    You can include a sequence within another
    sequence by giving the sequence an empty
    dash, followed by an indented list.
yaml: |
    -
     - foo
     - bar
     - baz
php: |
    array(array('foo', 'bar', 'baz'))
---
test: Mixed Sequences
brief: |
    Sequences can contain any YAML data,
    including strings and other sequences.
yaml: |
    - apple
    -
     - foo
     - bar
     - x123
    - banana
    - carrot
php: |
    array('apple', array('foo', 'bar', 'x123'), 'banana', 'carrot')
---
test: Deeply Nested Sequences
brief: |
    Sequences can be nested even deeper, with each
    level of indentation representing a level of
    depth.
yaml: |
    -
     -
      - uno
      - dos
php: |
    array(array(array('uno', 'dos')))
---
test: Simple Mapping
brief: |
    You can add a keyed list (also known as a dictionary or
    hash) to your document by placing each member of the
    list on a new line, with a colon separating the key
    from its value.  In YAML, this type of list is called
    a mapping.
yaml: |
    foo: whatever
    bar: stuff
php: |
    array('foo' => 'whatever', 'bar' => 'stuff')
---
test: Sequence in a Mapping
brief: |
    A value in a mapping can be a sequence.
yaml: |
    foo: whatever
    bar:
     - uno
     - dos
php: |
    array('foo' => 'whatever', 'bar' => array('uno', 'dos'))
---
test: Nested Mappings
brief: |
    A value in a mapping can be another mapping.
yaml: |
    foo: whatever
    bar:
     fruit: apple
     name: steve
     sport: baseball
php: |
    array(
      'foo' => 'whatever',
      'bar' => array(
         'fruit' => 'apple',
         'name' => 'steve',
         'sport' => 'baseball'
       )
    )
---
test: Mixed Mapping
brief: |
    A mapping can contain any assortment
    of mappings and sequences as values.
yaml: |
    foo: whatever
    bar:
     -
       fruit: apple
       name: steve
       sport: baseball
     - more
     -
       python: rocks
       perl: papers
       ruby: scissorses
php: |
    array(
      'foo' => 'whatever',
      'bar' => array(
        array(
            'fruit' => 'apple',
            'name' => 'steve',
            'sport' => 'baseball'
        ),
        'more',
        array(
            'python' => 'rocks',
            'perl' => 'papers',
            'ruby' => 'scissorses'
        )
      )
    )
---
test: Mapping-in-Sequence Shortcut
todo: true
brief: |
     If you are adding a mapping to a sequence, you
     can place the mapping on the same line as the
     dash as a shortcut.
yaml: |
     - work on YAML.py:
        - work on Store
php: |
    array(array('work on YAML.py' => array('work on Store')))
---
test: Sequence-in-Mapping Shortcut
todo: true
brief: |
     The dash in a sequence counts as indentation, so
     you can add a sequence inside of a mapping without
     needing spaces as indentation.
yaml: |
     allow:
     - 'localhost'
     - '%.sourceforge.net'
     - '%.freepan.org'
php: |
     array('allow' => array('localhost', '%.sourceforge.net', '%.freepan.org'))
---
todo: true
test: Merge key
brief: |
     A merge key ('<<') can be used in a mapping to insert other mappings.  If
     the value associated with the merge key is a mapping, each of its key/value
     pairs is inserted into the current mapping.
yaml: |
     mapping:
       name: Joe
       job: Accountant
       <<:
         age: 38
php: |
     array(
       'mapping' =>
       array(
         'name' => 'Joe',
         'job' => 'Accountant',
         'age' => 38
       )
     )
PK<1[ګغzz?Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFoldedScalars.ymlnu�[���--- %YAML:1.0
test: Single ending newline
brief: >
    A pipe character, followed by an indented
    block of text is treated as a literal
    block, in which newlines are preserved
    throughout the block, including the final
    newline.
yaml: |
    ---
    this: |
        Foo
        Bar
php: |
    array('this' => "Foo\nBar\n")
---
test: The '+' indicator
brief: >
    The '+' indicator says to keep newlines at the end of text
    blocks.
yaml: |
    normal: |
      extra new lines not kept

    preserving: |+
      extra new lines are kept


    dummy: value
php: |
    array(
        'normal' => "extra new lines not kept\n",
        'preserving' => "extra new lines are kept\n\n\n",
        'dummy' => 'value'
    )
---
test: Three trailing newlines in literals
brief: >
    To give you more control over how space
    is preserved in text blocks, YAML has
    the keep '+' and chomp '-' indicators.
    The keep indicator will preserve all
    ending newlines, while the chomp indicator
    will strip all ending newlines.
yaml: |
    clipped: |
        This has one newline.



    same as "clipped" above: "This has one newline.\n"

    stripped: |-
        This has no newline.



    same as "stripped" above: "This has no newline."

    kept: |+
        This has four newlines.



    same as "kept" above: "This has four newlines.\n\n\n\n"
php: |
    array(
      'clipped' => "This has one newline.\n",
      'same as "clipped" above' => "This has one newline.\n",
      'stripped' => 'This has no newline.',
      'same as "stripped" above' => 'This has no newline.',
      'kept' => "This has four newlines.\n\n\n\n",
      'same as "kept" above' => "This has four newlines.\n\n\n\n"
    )
---
test: Extra trailing newlines with spaces
todo: true
brief: >
    Normally, only a single newline is kept
    from the end of a literal block, unless the
    keep '+' character is used in combination
    with the pipe.  The following example
    will preserve all ending whitespace
    since the last line of both literal blocks
    contains spaces which extend past the indentation
    level.
yaml: |
    ---
    this: |
        Foo


    kept: |+
        Foo


php: |
    array('this' => "Foo\n\n  \n",
      'kept' => "Foo\n\n  \n" )

---
test: Folded Block in a Sequence
brief: >
    A greater-then character, followed by an indented
    block of text is treated as a folded block, in
    which lines of text separated by a single newline
    are concatenated as a single line.
yaml: |
    ---
    - apple
    - banana
    - >
        can't you see
        the beauty of yaml?
        hmm
    - dog
php: |
    array(
        'apple',
        'banana',
        "can't you see the beauty of yaml? hmm\n",
        'dog'
    )
---
test: Folded Block as a Mapping Value
brief: >
    Both literal and folded blocks can be
    used in collections, as values in a
    sequence or a mapping.
yaml: |
    ---
    quote: >
        Mark McGwire's
        year was crippled
        by a knee injury.
    source: espn
php: |
    array(
        'quote' => "Mark McGwire's year was crippled by a knee injury.\n",
        'source' => 'espn'
    )
---
test: Three trailing newlines in folded blocks
brief: >
    The keep and chomp indicators can also
    be applied to folded blocks.
yaml: |
    clipped: >
        This has one newline.



    same as "clipped" above: "This has one newline.\n"

    stripped: >-
        This has no newline.



    same as "stripped" above: "This has no newline."

    kept: >+
        This has four newlines.



    same as "kept" above: "This has four newlines.\n\n\n\n"
php: |
    array(
      'clipped' => "This has one newline.\n",
      'same as "clipped" above' => "This has one newline.\n",
      'stripped' => 'This has no newline.',
      'same as "stripped" above' => 'This has no newline.',
      'kept' => "This has four newlines.\n\n\n\n",
      'same as "kept" above' => "This has four newlines.\n\n\n\n"
    )
PK<1[���884Yaml/Symfony/Component/Yaml/Tests/Fixtures/index.ymlnu�[���- escapedCharacters
- sfComments
- sfCompact
- sfTests
- sfObjects
- sfMergeKey
- sfQuotes
- YtsAnchorAlias
- YtsBasicTests
- YtsBlockMapping
- YtsDocumentSeparator
- YtsErrorTests
- YtsFlowCollections
- YtsFoldedScalars
- YtsNullsAndEmpties
- YtsSpecificationExamples
- YtsTypeTransfers
- unindentedCollections
PK<1[%MC��CYaml/Symfony/Component/Yaml/Tests/Fixtures/YtsDocumentSeparator.ymlnu�[���--- %YAML:1.0
test: Trailing Document Separator
todo: true
brief: >
    You can separate YAML documents
    with a string of three dashes.
yaml: |
    - foo: 1
      bar: 2
    ---
    more: stuff
python: |
    [
        [ { 'foo': 1, 'bar': 2 } ],
        { 'more': 'stuff' }
    ]
ruby: |
    [ { 'foo' => 1, 'bar' => 2 } ]

---
test: Leading Document Separator
todo: true
brief: >
    You can explicity give an opening
    document separator to your YAML stream.
yaml: |
    ---
    - foo: 1
      bar: 2
    ---
    more: stuff
python: |
    [
        [ {'foo': 1, 'bar': 2}],
        {'more': 'stuff'}
    ]
ruby: |
    [ { 'foo' => 1, 'bar' => 2 } ]

---
test: YAML Header
todo: true
brief: >
    The opening separator can contain directives
    to the YAML parser, such as the version
    number.
yaml: |
    --- %YAML:1.0
    foo: 1
    bar: 2
php: |
    array('foo' => 1, 'bar' => 2)
documents: 1

---
test: Red Herring Document Separator
brief: >
    Separators included in blocks or strings
    are treated as blocks or strings, as the
    document separator should have no indentation
    preceding it.
yaml: |
    foo: |
        ---
php: |
    array('foo' => "---\n")

---
test: Multiple Document Separators in Block
brief: >
    This technique allows you to embed other YAML
    documents within literal blocks.
yaml: |
    foo: |
        ---
        foo: bar
        ---
        yo: baz
    bar: |
        fooness
php: |
    array(
       'foo' => "---\nfoo: bar\n---\nyo: baz\n",
       'bar' => "fooness\n"
    )
PK<1[;:�QJJ9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfMergeKey.ymlnu�[���--- %YAML:1.0
test: Simple In Place Substitution
brief: >
    If you want to reuse an entire alias, only overwriting what is different
    you can use a << in place substitution. This is not part of the official
    YAML spec, but a widely implemented extension. See the following URL for
    details: http://yaml.org/type/merge.html
yaml: |
    foo: &foo
        a: Steve
        b: Clark
        c: Brian
    bar: &bar
        <<: *foo
        x: Oren
    foo2: &foo2
        a: Ballmer
    ding: &dong [ fi, fei, fo, fam]
    check:
        <<:
            - *foo
            - *dong
        isit: tested
    head:
        <<: [ *foo , *dong , *foo2 ]
php: |
    array('foo' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian'), 'bar' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'x' => 'Oren'), 'foo2' => array('a' => 'Ballmer'), 'ding' => array('fi', 'fei', 'fo', 'fam'), 'check' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'fi', 'fei', 'fo', 'fam', 'isit' => 'tested'), 'head' => array('a' => 'Ballmer', 'b' => 'Clark', 'c' => 'Brian', 'fi', 'fei', 'fo', 'fam'))
PK<1[Z��9Yaml/Symfony/Component/Yaml/Tests/Fixtures/embededPhp.ymlnu�[���value: <?php echo 1 + 2 + 3 ?>
PK<1[�<�8Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfObjects.ymlnu�[���--- %YAML:1.0
test: Objects
brief: >
    Comments at the end of a line
yaml: |
    ex1: "foo # bar"
    ex2: "foo # bar" # comment
    ex3: 'foo # bar' # comment
    ex4: foo # comment
php: |
    array('ex1' => 'foo # bar', 'ex2' => 'foo # bar', 'ex3' => 'foo # bar', 'ex4' => 'foo')
PK<1[�$R��?Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsTypeTransfers.ymlnu�[���--- %YAML:1.0
test: Strings
brief: >
    Any group of characters beginning with an
    alphabetic or numeric character is a string,
    unless it belongs to one of the groups below
    (such as an Integer or Time).
yaml: |
    String
php: |
    'String'
---
test: String characters
brief: >
    A string can contain any alphabetic or
    numeric character, along with many
    punctuation characters, including the
    period, dash, space, quotes, exclamation, and
    question mark.
yaml: |
    - What's Yaml?
    - It's for writing data structures in plain text.
    - And?
    - And what? That's not good enough for you?
    - No, I mean, "And what about Yaml?"
    - Oh, oh yeah. Uh.. Yaml for Ruby.
php: |
    array(
      "What's Yaml?",
      "It's for writing data structures in plain text.",
      "And?",
      "And what? That's not good enough for you?",
      "No, I mean, \"And what about Yaml?\"",
      "Oh, oh yeah. Uh.. Yaml for Ruby."
    )
---
test: Indicators in Strings
brief: >
    Be careful using indicators in strings.  In particular,
    the comma, colon, and pound sign must be used carefully.
yaml: |
    the colon followed by space is an indicator: but is a string:right here
    same for the pound sign: here we have it#in a string
    the comma can, honestly, be used in most cases: [ but not in, inline collections ]
php: |
    array(
      'the colon followed by space is an indicator' => 'but is a string:right here',
      'same for the pound sign' => 'here we have it#in a string',
      'the comma can, honestly, be used in most cases' => array('but not in', 'inline collections')
    )
---
test: Forcing Strings
brief: >
    Any YAML type can be forced into a string using the
    explicit !str method.
yaml: |
    date string: !str 2001-08-01
    number string: !str 192
php: |
    array(
      'date string' => '2001-08-01',
      'number string' => '192'
    )
---
test: Single-quoted Strings
brief: >
    You can also enclose your strings within single quotes,
    which allows use of slashes, colons, and other indicators
    freely.  Inside single quotes, you can represent a single
    quote in your string by using two single quotes next to
    each other.
yaml: |
    all my favorite symbols: '#:!/%.)'
    a few i hate: '&(*'
    why do i hate them?: 'it''s very hard to explain'
    entities: '&pound; me'
php: |
    array(
      'all my favorite symbols' => '#:!/%.)',
      'a few i hate' => '&(*',
      'why do i hate them?' => 'it\'s very hard to explain',
      'entities' => '&pound; me'
    )
---
test: Double-quoted Strings
brief: >
    Enclosing strings in double quotes allows you
    to use escapings to represent ASCII and
    Unicode characters.
yaml: |
    i know where i want my line breaks: "one here\nand another here\n"
php: |
    array(
      'i know where i want my line breaks' => "one here\nand another here\n"
    )
---
test: Multi-line Quoted Strings
todo: true
brief: >
    Both single- and double-quoted strings may be
    carried on to new lines in your YAML document.
    They must be indented a step and indentation
    is interpreted as a single space.
yaml: |
    i want a long string: "so i'm going to
      let it go on and on to other lines
      until i end it with a quote."
php: |
    array('i want a long string' => "so i'm going to ".
         "let it go on and on to other lines ".
         "until i end it with a quote."
    )

---
test: Plain scalars
todo: true
brief: >
    Unquoted strings may also span multiple lines, if they
    are free of YAML space indicators and indented.
yaml: |
    - My little toe is broken in two places;
    - I'm crazy to have skied this way;
    - I'm not the craziest he's seen, since there was always the German guy
      who skied for 3 hours on a broken shin bone (just below the kneecap);
    - Nevertheless, second place is respectable, and he doesn't
      recommend going for the record;
    - He's going to put my foot in plaster for a month;
    - This would impair my skiing ability somewhat for the
      duration, as can be imagined.
php: |
    array(
      "My little toe is broken in two places;",
      "I'm crazy to have skied this way;",
      "I'm not the craziest he's seen, since there was always ".
         "the German guy who skied for 3 hours on a broken shin ".
         "bone (just below the kneecap);",
      "Nevertheless, second place is respectable, and he doesn't ".
         "recommend going for the record;",
      "He's going to put my foot in plaster for a month;",
      "This would impair my skiing ability somewhat for the duration, ".
         "as can be imagined."
    )
---
test: 'Null'
brief: >
    You can use the tilde '~' character for a null value.
yaml: |
    name: Mr. Show
    hosted by: Bob and David
    date of next season: ~
php: |
    array(
      'name' => 'Mr. Show',
      'hosted by' => 'Bob and David',
      'date of next season' => null
    )
---
test: Boolean
brief: >
    You can use 'true' and 'false' for Boolean values.
yaml: |
    Is Gus a Liar?: true
    Do I rely on Gus for Sustenance?: false
php: |
    array(
      'Is Gus a Liar?' => true,
      'Do I rely on Gus for Sustenance?' => false
    )
---
test: Integers
dump_skip: true
brief: >
    An integer is a series of numbers, optionally
    starting with a positive or negative sign.  Integers
    may also contain commas for readability.
yaml: |
    zero: 0
    simple: 12
    one-thousand: 1,000
    negative one-thousand: -1,000
php: |
    array(
      'zero' => 0,
      'simple' => 12,
      'one-thousand' => 1000,
      'negative one-thousand' => -1000
    )
---
test: Integers as Map Keys
brief: >
    An integer can be used a dictionary key.
yaml: |
    1: one
    2: two
    3: three
php: |
    array(
        1 => 'one',
        2 => 'two',
        3 => 'three'
    )
---
test: Floats
dump_skip: true
brief: >
     Floats are represented by numbers with decimals,
     allowing for scientific notation, as well as
     positive and negative infinity and "not a number."
yaml: |
     a simple float: 2.00
     larger float: 1,000.09
     scientific notation: 1.00009e+3
php: |
     array(
       'a simple float' => 2.0,
       'larger float' => 1000.09,
       'scientific notation' => 1000.09
     )
---
test: Time
todo: true
brief: >
    You can represent timestamps by using
    ISO8601 format, or a variation which
    allows spaces between the date, time and
    time zone.
yaml: |
    iso8601: 2001-12-14t21:59:43.10-05:00
    space separated: 2001-12-14 21:59:43.10 -05:00
php: |
    array(
      'iso8601' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
      'space separated' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" )
    )
---
test: Date
todo: true
brief: >
    A date can be represented by its year,
    month and day in ISO8601 order.
yaml: |
    1976-07-31
php: |
    date( 1976, 7, 31 )
PK<1[����7Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfQuotes.ymlnu�[���--- %YAML:1.0
test: Some characters at the beginning of a string must be escaped
brief: >
    Some characters at the beginning of a string must be escaped
yaml: |
    foo: | bar
php: |
    array('foo' => '| bar')
---
test: A key can be a quoted string
brief: >
  A key can be a quoted string
yaml: |
    "foo1": bar
    'foo2': bar
    "foo \" bar": bar
    'foo '' bar': bar
    'foo3: ': bar
    "foo4: ": bar
    foo5: { "foo \" bar: ": bar, 'foo '' bar: ': bar }
php: |
    array(
      'foo1' => 'bar',
      'foo2' => 'bar',
      'foo " bar' => 'bar',
      'foo \' bar' => 'bar',
      'foo3: ' => 'bar',
      'foo4: ' => 'bar',
      'foo5' => array(
        'foo " bar: ' => 'bar',
        'foo \' bar: ' => 'bar',
      ),
    )
PK<1[ܷU�1�1�GYaml/Symfony/Component/Yaml/Tests/Fixtures/YtsSpecificationExamples.ymlnu�[���--- %YAML:1.0
test: Sequence of scalars
spec: 2.1
yaml: |
  - Mark McGwire
  - Sammy Sosa
  - Ken Griffey
php: |
  array('Mark McGwire', 'Sammy Sosa', 'Ken Griffey')
---
test: Mapping of scalars to scalars
spec: 2.2
yaml: |
  hr:  65
  avg: 0.278
  rbi: 147
php: |
  array('hr' => 65, 'avg' => 0.278, 'rbi' => 147)
---
test: Mapping of scalars to sequences
spec: 2.3
yaml: |
    american:
       - Boston Red Sox
       - Detroit Tigers
       - New York Yankees
    national:
       - New York Mets
       - Chicago Cubs
       - Atlanta Braves
php: |
    array('american' =>
        array( 'Boston Red Sox', 'Detroit Tigers',
          'New York Yankees' ),
      'national' =>
        array( 'New York Mets', 'Chicago Cubs',
          'Atlanta Braves' )
    )
---
test: Sequence of mappings
spec: 2.4
yaml: |
    -
      name: Mark McGwire
      hr:   65
      avg:  0.278
    -
      name: Sammy Sosa
      hr:   63
      avg:  0.288
php: |
    array(
      array('name' => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278),
      array('name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288)
    )
---
test: Legacy A5
todo: true
spec: legacy_A5
yaml: |
    ?
        - New York Yankees
        - Atlanta Braves
    :
      - 2001-07-02
      - 2001-08-12
      - 2001-08-14
    ?
        - Detroit Tigers
        - Chicago Cubs
    :
      - 2001-07-23
perl-busted: >
    YAML.pm will be able to emulate this behavior soon. In this regard
    it may be somewhat more correct than Python's native behaviour which
    can only use tuples as mapping keys. PyYAML will also need to figure
    out some clever way to roundtrip structured keys.
python: |
    [
    {
        ('New York Yankees', 'Atlanta Braves'):
            [yaml.timestamp('2001-07-02'),
             yaml.timestamp('2001-08-12'),
             yaml.timestamp('2001-08-14')],
        ('Detroit Tigers', 'Chicago Cubs'):
        [yaml.timestamp('2001-07-23')]
    }
    ]
ruby: |
    {
      [ 'New York Yankees', 'Atlanta Braves' ] =>
        [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ],
      [ 'Detroit Tigers', 'Chicago Cubs' ] =>
        [ Date.new( 2001, 7, 23 ) ]
    }
syck: |
  struct test_node seq1[] = {
      { T_STR, 0, "New York Yankees" },
      { T_STR, 0, "Atlanta Braves" },
      end_node
  };
  struct test_node seq2[] = {
      { T_STR, 0, "2001-07-02" },
      { T_STR, 0, "2001-08-12" },
      { T_STR, 0, "2001-08-14" },
      end_node
  };
  struct test_node seq3[] = {
      { T_STR, 0, "Detroit Tigers" },
      { T_STR, 0, "Chicago Cubs" },
      end_node
  };
  struct test_node seq4[] = {
      { T_STR, 0, "2001-07-23" },
      end_node
  };
  struct test_node map[] = {
      { T_SEQ, 0, 0, seq1 },
      { T_SEQ, 0, 0, seq2 },
      { T_SEQ, 0, 0, seq3 },
      { T_SEQ, 0, 0, seq4 },
      end_node
  };
  struct test_node stream[] = {
      { T_MAP, 0, 0, map },
      end_node
  };

---
test: Sequence of sequences
spec: 2.5
yaml: |
  - [ name         , hr , avg   ]
  - [ Mark McGwire , 65 , 0.278 ]
  - [ Sammy Sosa   , 63 , 0.288 ]
php: |
  array(
    array( 'name', 'hr', 'avg' ),
    array( 'Mark McGwire', 65, 0.278 ),
    array( 'Sammy Sosa', 63, 0.288 )
  )
---
test: Mapping of mappings
todo: true
spec: 2.6
yaml: |
  Mark McGwire: {hr: 65, avg: 0.278}
  Sammy Sosa: {
      hr: 63,
      avg: 0.288
    }
php: |
  array(
    'Mark McGwire' =>
      array( 'hr' => 65, 'avg' => 0.278 ),
    'Sammy Sosa' =>
      array( 'hr' => 63, 'avg' => 0.288 )
  )
---
test: Two documents in a stream each with a leading comment
todo: true
spec: 2.7
yaml: |
  # Ranking of 1998 home runs
  ---
  - Mark McGwire
  - Sammy Sosa
  - Ken Griffey

  # Team ranking
  ---
  - Chicago Cubs
  - St Louis Cardinals
ruby: |
  y = YAML::Stream.new
  y.add( [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ] )
  y.add( [ 'Chicago Cubs', 'St Louis Cardinals' ] )
documents: 2

---
test: Play by play feed from a game
todo: true
spec: 2.8
yaml: |
  ---
  time: 20:03:20
  player: Sammy Sosa
  action: strike (miss)
  ...
  ---
  time: 20:03:47
  player: Sammy Sosa
  action: grand slam
  ...
perl: |
  [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ]
documents: 2

---
test: Single document with two comments
spec: 2.9
yaml: |
  hr: # 1998 hr ranking
    - Mark McGwire
    - Sammy Sosa
  rbi:
    # 1998 rbi ranking
    - Sammy Sosa
    - Ken Griffey
php: |
  array(
    'hr' => array( 'Mark McGwire', 'Sammy Sosa' ),
    'rbi' => array( 'Sammy Sosa', 'Ken Griffey' )
  )
---
test: Node for Sammy Sosa appears twice in this document
spec: 2.10
yaml: |
   ---
   hr:
      - Mark McGwire
      # Following node labeled SS
      - &SS Sammy Sosa
   rbi:
      - *SS # Subsequent occurrence
      - Ken Griffey
php: |
   array(
      'hr' =>
         array('Mark McGwire', 'Sammy Sosa'),
      'rbi' =>
         array('Sammy Sosa', 'Ken Griffey')
   )
---
test: Mapping between sequences
todo: true
spec: 2.11
yaml: |
   ? # PLAY SCHEDULE
     - Detroit Tigers
     - Chicago Cubs
   :
     - 2001-07-23

   ? [ New York Yankees,
       Atlanta Braves ]
   : [ 2001-07-02, 2001-08-12,
       2001-08-14 ]
ruby: |
   {
      [ 'Detroit Tigers', 'Chicago Cubs' ] => [ Date.new( 2001, 7, 23 ) ],
      [ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ]
   }
syck: |
  struct test_node seq1[] = {
      { T_STR, 0, "New York Yankees" },
      { T_STR, 0, "Atlanta Braves" },
      end_node
  };
  struct test_node seq2[] = {
      { T_STR, 0, "2001-07-02" },
      { T_STR, 0, "2001-08-12" },
      { T_STR, 0, "2001-08-14" },
      end_node
  };
  struct test_node seq3[] = {
      { T_STR, 0, "Detroit Tigers" },
      { T_STR, 0, "Chicago Cubs" },
      end_node
  };
  struct test_node seq4[] = {
      { T_STR, 0, "2001-07-23" },
      end_node
  };
  struct test_node map[] = {
      { T_SEQ, 0, 0, seq3 },
      { T_SEQ, 0, 0, seq4 },
      { T_SEQ, 0, 0, seq1 },
      { T_SEQ, 0, 0, seq2 },
      end_node
  };
  struct test_node stream[] = {
      { T_MAP, 0, 0, map },
      end_node
  };

---
test: Sequence key shortcut
spec: 2.12
yaml: |
  ---
  # products purchased
  - item    : Super Hoop
    quantity: 1
  - item    : Basketball
    quantity: 4
  - item    : Big Shoes
    quantity: 1
php: |
  array (
    array (
      'item' => 'Super Hoop',
      'quantity' => 1,
    ),
    array (
      'item' => 'Basketball',
      'quantity' => 4,
    ),
    array (
      'item' => 'Big Shoes',
      'quantity' => 1,
    )
  )
perl: |
  [
     { item => 'Super Hoop', quantity => 1 },
     { item => 'Basketball', quantity => 4 },
     { item => 'Big Shoes',  quantity => 1 }
  ]

ruby: |
  [
     { 'item' => 'Super Hoop', 'quantity' => 1 },
     { 'item' => 'Basketball', 'quantity' => 4 },
     { 'item' => 'Big Shoes', 'quantity' => 1 }
  ]
python: |
  [
       { 'item': 'Super Hoop', 'quantity': 1 },
       { 'item': 'Basketball', 'quantity': 4 },
       { 'item': 'Big Shoes',  'quantity': 1 }
  ]
syck: |
  struct test_node map1[] = {
      { T_STR, 0, "item" },
          { T_STR, 0, "Super Hoop" },
      { T_STR, 0, "quantity" },
          { T_STR, 0, "1" },
      end_node
  };
  struct test_node map2[] = {
      { T_STR, 0, "item" },
          { T_STR, 0, "Basketball" },
      { T_STR, 0, "quantity" },
          { T_STR, 0, "4" },
      end_node
  };
  struct test_node map3[] = {
      { T_STR, 0, "item" },
          { T_STR, 0, "Big Shoes" },
      { T_STR, 0, "quantity" },
          { T_STR, 0, "1" },
      end_node
  };
  struct test_node seq[] = {
      { T_MAP, 0, 0, map1 },
      { T_MAP, 0, 0, map2 },
      { T_MAP, 0, 0, map3 },
      end_node
  };
  struct test_node stream[] = {
      { T_SEQ, 0, 0, seq },
      end_node
  };


---
test: Literal perserves newlines
todo: true
spec: 2.13
yaml: |
  # ASCII Art
  --- |
    \//||\/||
    // ||  ||_
perl: |
  "\\//||\\/||\n// ||  ||_\n"
ruby: |
  "\\//||\\/||\n// ||  ||_\n"
python: |
    [
        flushLeft(
        """
        \//||\/||
        // ||  ||_
        """
        )
    ]
syck: |
  struct test_node stream[] = {
      { T_STR, 0, "\\//||\\/||\n// ||  ||_\n" },
      end_node
  };

---
test: Folded treats newlines as a space
todo: true
spec: 2.14
yaml: |
  ---
    Mark McGwire's
    year was crippled
    by a knee injury.
perl: |
  "Mark McGwire's year was crippled by a knee injury."
ruby: |
  "Mark McGwire's year was crippled by a knee injury."
python: |
    [ "Mark McGwire's year was crippled by a knee injury." ]
syck: |
  struct test_node stream[] = {
      { T_STR, 0, "Mark McGwire's year was crippled by a knee injury." },
      end_node
  };

---
test: Newlines preserved for indented and blank lines
todo: true
spec: 2.15
yaml: |
  --- >
   Sammy Sosa completed another
   fine season with great stats.

     63 Home Runs
     0.288 Batting Average

   What a year!
perl: |
  "Sammy Sosa completed another fine season with great stats.\n\n  63 Home Runs\n  0.288 Batting Average\n\nWhat a year!\n"
ruby: |
  "Sammy Sosa completed another fine season with great stats.\n\n  63 Home Runs\n  0.288 Batting Average\n\nWhat a year!\n"
python: |
    [
        flushLeft(
        """
        Sammy Sosa completed another fine season with great stats.

          63 Home Runs
          0.288 Batting Average

        What a year!
        """
        )
    ]
syck: |
  struct test_node stream[] = {
      { T_STR, 0, "Sammy Sosa completed another fine season with great stats.\n\n  63 Home Runs\n  0.288 Batting Average\n\nWhat a year!\n" },
      end_node
  };


---
test: Indentation determines scope
spec: 2.16
yaml: |
  name: Mark McGwire
  accomplishment: >
     Mark set a major league
     home run record in 1998.
  stats: |
     65 Home Runs
     0.278 Batting Average
php: |
  array(
    'name'           => 'Mark McGwire',
    'accomplishment' => "Mark set a major league home run record in 1998.\n",
    'stats'          => "65 Home Runs\n0.278 Batting Average\n"
  )
---
test: Quoted scalars
todo: true
spec: 2.17
yaml: |
  unicode: "Sosa did fine.\u263A"
  control: "\b1998\t1999\t2000\n"
  hexesc:  "\x0D\x0A is \r\n"

  single: '"Howdy!" he cried.'
  quoted: ' # not a ''comment''.'
  tie-fighter: '|\-*-/|'
ruby: |
  {
    "tie-fighter" => "|\\-*-/|",
    "control"=>"\0101998\t1999\t2000\n",
    "unicode"=>"Sosa did fine." + ["263A".hex ].pack('U*'),
    "quoted"=>" # not a 'comment'.",
    "single"=>"\"Howdy!\" he cried.",
    "hexesc"=>"\r\n is \r\n"
  }
---
test: Multiline flow scalars
todo: true
spec: 2.18
yaml: |
  plain:
    This unquoted scalar
    spans many lines.

  quoted: "So does this
    quoted scalar.\n"
ruby: |
  {
    'plain' => 'This unquoted scalar spans many lines.',
    'quoted' => "So does this quoted scalar.\n"
  }
---
test: Integers
spec: 2.19
yaml: |
  canonical: 12345
  decimal: +12,345
  octal: 014
  hexadecimal: 0xC
php: |
  array(
    'canonical' => 12345,
    'decimal' => 12345,
    'octal' => 014,
    'hexadecimal' => 0xC
  )
---
# FIX: spec shows parens around -inf and NaN
test: Floating point
spec: 2.20
yaml: |
  canonical: 1.23015e+3
  exponential: 12.3015e+02
  fixed: 1,230.15
  negative infinity: -.inf
  not a number: .NaN
php: |
  array(
    'canonical' => 1230.15,
    'exponential' => 1230.15,
    'fixed' => 1230.15,
    'negative infinity' => log(0),
    'not a number' => -log(0),
  )
---
test: Miscellaneous
spec: 2.21
yaml: |
  null: ~
  true: true
  false: false
  string: '12345'
php: |
  array(
    '' => null,
    1 => true,
    0 => false,
    'string' => '12345'
  )
---
test: Timestamps
todo: true
spec: 2.22
yaml: |
  canonical: 2001-12-15T02:59:43.1Z
  iso8601:  2001-12-14t21:59:43.10-05:00
  spaced:  2001-12-14 21:59:43.10 -05:00
  date:   2002-12-14 # Time is noon UTC
php: |
  array(
    'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ),
    'iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
    'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
    'date' => Date.new( 2002, 12, 14 )
  )
---
test: legacy Timestamps test
todo: true
spec: legacy D4
yaml: |
    canonical: 2001-12-15T02:59:43.00Z
    iso8601:  2001-02-28t21:59:43.00-05:00
    spaced:  2001-12-14 21:59:43.00 -05:00
    date:   2002-12-14
php: |
   array(
     'canonical' => Time::utc( 2001, 12, 15, 2, 59, 43, 0 ),
     'iso8601' => YAML::mktime( 2001, 2, 28, 21, 59, 43, 0, "-05:00" ),
     'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0, "-05:00" ),
     'date' => Date.new( 2002, 12, 14 )
   )
---
test: Various explicit families
todo: true
spec: 2.23
yaml: |
  not-date: !str 2002-04-28
  picture: !binary |
   R0lGODlhDAAMAIQAAP//9/X
   17unp5WZmZgAAAOfn515eXv
   Pz7Y6OjuDg4J+fn5OTk6enp
   56enmleECcgggoBADs=

  application specific tag: !!something |
   The semantics of the tag
   above may be different for
   different documents.

ruby-setup: |
  YAML.add_private_type( "something" ) do |type, val|
    "SOMETHING: #{val}"
  end
ruby: |
  {
    'not-date' => '2002-04-28',
    'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;",
    'application specific tag' => "SOMETHING: The semantics of the tag\nabove may be different for\ndifferent documents.\n"
  }
---
test: Application specific family
todo: true
spec: 2.24
yaml: |
  # Establish a tag prefix
  --- !clarkevans.com,2002/graph/^shape
    # Use the prefix: shorthand for
    # !clarkevans.com,2002/graph/circle
  - !^circle
    center: &ORIGIN {x: 73, 'y': 129}
    radius: 7
  - !^line # !clarkevans.com,2002/graph/line
    start: *ORIGIN
    finish: { x: 89, 'y': 102 }
  - !^label
    start: *ORIGIN
    color: 0xFFEEBB
    value: Pretty vector drawing.
ruby-setup: |
  YAML.add_domain_type( "clarkevans.com,2002", 'graph/shape' ) { |type, val|
    if Array === val
      val << "Shape Container"
      val
    else
      raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect
    end
  }
  one_shape_proc = Proc.new { |type, val|
    scheme, domain, type = type.split( /:/, 3 )
    if val.is_a? ::Hash
      val['TYPE'] = "Shape: #{type}"
      val
    else
      raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect
    end
  }
  YAML.add_domain_type( "clarkevans.com,2002", 'graph/circle', &one_shape_proc )
  YAML.add_domain_type( "clarkevans.com,2002", 'graph/line', &one_shape_proc )
  YAML.add_domain_type( "clarkevans.com,2002", 'graph/label', &one_shape_proc )
ruby: |
  [
    {
      "radius" => 7,
      "center"=>
      {
        "x" => 73,
        "y" => 129
      },
      "TYPE" => "Shape: graph/circle"
    }, {
      "finish" =>
      {
        "x" => 89,
        "y" => 102
      },
      "TYPE" => "Shape: graph/line",
      "start" =>
      {
        "x" => 73,
        "y" => 129
      }
    }, {
      "TYPE" => "Shape: graph/label",
      "value" => "Pretty vector drawing.",
      "start" =>
      {
        "x" => 73,
        "y" => 129
      },
      "color" => 16772795
    },
    "Shape Container"
  ]
# ---
# test: Unordered set
# spec: 2.25
# yaml: |
#   # sets are represented as a
#   # mapping where each key is
#   # associated with the empty string
#   --- !set
#   ? Mark McGwire
#   ? Sammy Sosa
#   ? Ken Griff
---
test: Ordered mappings
todo: true
spec: 2.26
yaml: |
  # ordered maps are represented as
  # a sequence of mappings, with
  # each mapping having one key
  --- !omap
  - Mark McGwire: 65
  - Sammy Sosa: 63
  - Ken Griffy: 58
ruby: |
  YAML::Omap[
    'Mark McGwire', 65,
    'Sammy Sosa', 63,
    'Ken Griffy', 58
  ]
---
test: Invoice
dump_skip: true
spec: 2.27
yaml: |
  --- !clarkevans.com,2002/^invoice
  invoice: 34843
  date   : 2001-01-23
  bill-to: &id001
      given  : Chris
      family : Dumars
      address:
          lines: |
              458 Walkman Dr.
              Suite #292
          city    : Royal Oak
          state   : MI
          postal  : 48046
  ship-to: *id001
  product:
      -
        sku         : BL394D
        quantity    : 4
        description : Basketball
        price       : 450.00
      -
        sku         : BL4438H
        quantity    : 1
        description : Super Hoop
        price       : 2392.00
  tax  : 251.42
  total: 4443.52
  comments: >
    Late afternoon is best.
    Backup contact is Nancy
    Billsmer @ 338-4338.
php: |
  array(
     'invoice' => 34843, 'date' => mktime(0, 0, 0, 1, 23, 2001),
     'bill-to' =>
      array( 'given' => 'Chris', 'family' => 'Dumars', 'address' => array( 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak', 'state' => 'MI', 'postal' => 48046 ) )
     , 'ship-to' =>
      array( 'given' => 'Chris', 'family' => 'Dumars', 'address' => array( 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak', 'state' => 'MI', 'postal' => 48046 ) )
     , 'product' =>
       array(
        array( 'sku' => 'BL394D', 'quantity' => 4, 'description' => 'Basketball', 'price' => 450.00 ),
        array( 'sku' => 'BL4438H', 'quantity' => 1, 'description' => 'Super Hoop', 'price' => 2392.00 )
      ),
     'tax' => 251.42, 'total' => 4443.52,
     'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n"
  )
---
test: Log file
todo: true
spec: 2.28
yaml: |
  ---
  Time: 2001-11-23 15:01:42 -05:00
  User: ed
  Warning: >
    This is an error message
    for the log file
  ---
  Time: 2001-11-23 15:02:31 -05:00
  User: ed
  Warning: >
    A slightly different error
    message.
  ---
  Date: 2001-11-23 15:03:17 -05:00
  User: ed
  Fatal: >
    Unknown variable "bar"
  Stack:
    - file: TopClass.py
      line: 23
      code: |
        x = MoreObject("345\n")
    - file: MoreClass.py
      line: 58
      code: |-
        foo = bar
ruby: |
  y = YAML::Stream.new
  y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ),
           'User' => 'ed', 'Warning' => "This is an error message for the log file\n" } )
  y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ),
           'User' => 'ed', 'Warning' => "A slightly different error message.\n" } )
  y.add( { 'Date' => YAML::mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ),
           'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n",
           'Stack' => [
           { 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" },
           { 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] } )
documents: 3

---
test: Throwaway comments
yaml: |
   ### These are four throwaway comment  ###

   ### lines (the second line is empty). ###
   this: |   # Comments may trail lines.
      contains three lines of text.
      The third one starts with a
      # character. This isn't a comment.

   # These are three throwaway comment
   # lines (the first line is empty).
php: |
   array(
     'this' => "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n"
   )
---
test: Document with a single value
todo: true
yaml: |
   --- >
   This YAML stream contains a single text value.
   The next stream is a log file - a sequence of
   log entries. Adding an entry to the log is a
   simple matter of appending it at the end.
ruby: |
   "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n"
---
test: Document stream
todo: true
yaml: |
   ---
   at: 2001-08-12 09:25:00.00 Z
   type: GET
   HTTP: '1.0'
   url: '/index.html'
   ---
   at: 2001-08-12 09:25:10.00 Z
   type: GET
   HTTP: '1.0'
   url: '/toc.html'
ruby: |
   y = YAML::Stream.new
   y.add( {
      'at' => Time::utc( 2001, 8, 12, 9, 25, 00 ),
      'type' => 'GET',
      'HTTP' => '1.0',
      'url' => '/index.html'
   } )
   y.add( {
      'at' => Time::utc( 2001, 8, 12, 9, 25, 10 ),
      'type' => 'GET',
      'HTTP' => '1.0',
      'url' => '/toc.html'
   } )
documents: 2

---
test: Top level mapping
yaml: |
   # This stream is an example of a top-level mapping.
   invoice : 34843
   date    : 2001-01-23
   total   : 4443.52
php: |
   array(
      'invoice' => 34843,
      'date' => mktime(0, 0, 0, 1, 23, 2001),
      'total' => 4443.52
   )
---
test: Single-line documents
todo: true
yaml: |
  # The following is a sequence of three documents.
  # The first contains an empty mapping, the second
  # an empty sequence, and the last an empty string.
  --- {}
  --- [ ]
  --- ''
ruby: |
  y = YAML::Stream.new
  y.add( {} )
  y.add( [] )
  y.add( '' )
documents: 3

---
test: Document with pause
todo: true
yaml: |
  # A communication channel based on a YAML stream.
  ---
  sent at: 2002-06-06 11:46:25.10 Z
  payload: Whatever
  # Receiver can process this as soon as the following is sent:
  ...
  # Even if the next message is sent long after:
  ---
  sent at: 2002-06-06 12:05:53.47 Z
  payload: Whatever
  ...
ruby: |
  y = YAML::Stream.new
  y.add(
    { 'sent at' => YAML::mktime( 2002, 6, 6, 11, 46, 25, 0.10 ),
      'payload' => 'Whatever' }
  )
  y.add(
    { "payload" => "Whatever", "sent at" => YAML::mktime( 2002, 6, 6, 12, 5, 53, 0.47 ) }
  )
documents: 2

---
test: Explicit typing
yaml: |
   integer: 12
   also int: ! "12"
   string: !str 12
php: |
   array( 'integer' => 12, 'also int' => 12, 'string' => '12' )
---
test: Private types
todo: true
yaml: |
  # Both examples below make use of the 'x-private:ball'
  # type family URI, but with different semantics.
  ---
  pool: !!ball
    number: 8
    color: black
  ---
  bearing: !!ball
    material: steel
ruby: |
  y = YAML::Stream.new
  y.add( { 'pool' =>
    YAML::PrivateType.new( 'ball',
      { 'number' => 8, 'color' => 'black' } ) }
  )
  y.add( { 'bearing' =>
    YAML::PrivateType.new( 'ball',
      { 'material' => 'steel' } ) }
  )
documents: 2

---
test: Type family under yaml.org
yaml: |
  # The URI is 'tag:yaml.org,2002:str'
  - !str a Unicode string
php: |
  array( 'a Unicode string' )
---
test: Type family under perl.yaml.org
todo: true
yaml: |
  # The URI is 'tag:perl.yaml.org,2002:Text::Tabs'
  - !perl/Text::Tabs {}
ruby: |
  [ YAML::DomainType.new( 'perl.yaml.org,2002', 'Text::Tabs', {} ) ]
---
test: Type family under clarkevans.com
todo: true
yaml: |
  # The URI is 'tag:clarkevans.com,2003-02:timesheet'
  - !clarkevans.com,2003-02/timesheet {}
ruby: |
  [ YAML::DomainType.new( 'clarkevans.com,2003-02', 'timesheet', {} ) ]
---
test: URI Escaping
todo: true
yaml: |
  same:
    - !domain.tld,2002/type\x30 value
    - !domain.tld,2002/type0 value
  different: # As far as the YAML parser is concerned
    - !domain.tld,2002/type%30 value
    - !domain.tld,2002/type0 value
ruby-setup: |
  YAML.add_domain_type( "domain.tld,2002", "type0" ) { |type, val|
    "ONE: #{val}"
  }
  YAML.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val|
    "TWO: #{val}"
  }
ruby: |
  { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value', 'ONE: value' ] }
---
test: URI Prefixing
todo: true
yaml: |
  # 'tag:domain.tld,2002:invoice' is some type family.
  invoice: !domain.tld,2002/^invoice
    # 'seq' is shorthand for 'tag:yaml.org,2002:seq'.
    # This does not effect '^customer' below
    # because it is does not specify a prefix.
    customers: !seq
      # '^customer' is shorthand for the full
      # notation 'tag:domain.tld,2002:customer'.
      - !^customer
        given : Chris
        family : Dumars
ruby-setup: |
  YAML.add_domain_type( "domain.tld,2002", /(invoice|customer)/ ) { |type, val|
    if val.is_a? ::Hash
      scheme, domain, type = type.split( /:/, 3 )
      val['type'] = "domain #{type}"
      val
    else
      raise YAML::Error, "Not a Hash in domain.tld/invoice: " + val.inspect
    end
  }
ruby: |
  { "invoice"=> { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } }

---
test: Overriding anchors
yaml: |
  anchor : &A001 This scalar has an anchor.
  override : &A001 >
   The alias node below is a
   repeated use of this value.
  alias : *A001
php: |
  array( 'anchor' => 'This scalar has an anchor.',
    'override' => "The alias node below is a repeated use of this value.\n",
    'alias' => "The alias node below is a repeated use of this value.\n" )
---
test: Flow and block formatting
todo: true
yaml: |
  empty: []
  flow: [ one, two, three # May span lines,
           , four,           # indentation is
             five ]          # mostly ignored.
  block:
   - First item in top sequence
   -
    - Subordinate sequence entry
   - >
     A folded sequence entry
   - Sixth item in top sequence
ruby: |
  { 'empty' => [], 'flow' => [ 'one', 'two', 'three', 'four', 'five' ],
    'block' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ],
    "A folded sequence entry\n", 'Sixth item in top sequence' ] }
---
test: Complete mapping test
todo: true
yaml: |
 empty: {}
 flow: { one: 1, two: 2 }
 spanning: { one: 1,
    two: 2 }
 block:
  first : First entry
  second:
   key: Subordinate mapping
  third:
   - Subordinate sequence
   - { }
   - Previous mapping is empty.
   - A key: value pair in a sequence.
     A second: key:value pair.
   - The previous entry is equal to the following one.
   -
     A key: value pair in a sequence.
     A second: key:value pair.
  !float 12 : This key is a float.
  ? >
   ?
  : This key had to be protected.
  "\a" : This key had to be escaped.
  ? >
   This is a
   multi-line
   folded key
  : Whose value is
    also multi-line.
  ? this also works as a key
  : with a value at the next line.
  ?
   - This key
   - is a sequence
  :
   - With a sequence value.
  ?
   This: key
   is a: mapping
  :
   with a: mapping value.
ruby: |
  { 'empty' => {}, 'flow' => { 'one' => 1, 'two' => 2 },
    'spanning' => { 'one' => 1, 'two' => 2 },
    'block' => { 'first' => 'First entry', 'second' =>
    { 'key' => 'Subordinate mapping' }, 'third' =>
      [ 'Subordinate sequence', {}, 'Previous mapping is empty.',
        { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' },
        'The previous entry is equal to the following one.',
        { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ],
    12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.',
    "\a" => 'This key had to be escaped.',
    "This is a multi-line folded key\n" => "Whose value is also multi-line.",
    'this also works as a key' => 'with a value at the next line.',
    [ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } }
  # Couldn't recreate map exactly, so we'll do a detailed check to be sure it's entact
  obj_y['block'].keys.each { |k|
    if Hash === k
      v = obj_y['block'][k]
      if k['This'] == 'key' and k['is a'] == 'mapping' and v['with a'] == 'mapping value.'
         obj_r['block'][k] = v
      end
    end
  }
---
test: Literal explicit indentation
yaml: |
   # Explicit indentation must
   # be given in all the three
   # following cases.
   leading spaces: |2
         This value starts with four spaces.

   leading line break: |2

     This value starts with a line break.

   leading comment indicator: |2
     # first line starts with a
     # character.

   # Explicit indentation may
   # also be given when it is
   # not required.
   redundant: |2
     This value is indented 2 spaces.
php: |
   array(
      'leading spaces' => "    This value starts with four spaces.\n",
      'leading line break' => "\nThis value starts with a line break.\n",
      'leading comment indicator' => "# first line starts with a\n# character.\n",
      'redundant' => "This value is indented 2 spaces.\n"
   )
---
test: Chomping and keep modifiers
yaml: |
    clipped: |
        This has one newline.

    same as "clipped" above: "This has one newline.\n"

    stripped: |-
        This has no newline.

    same as "stripped" above: "This has no newline."

    kept: |+
        This has two newlines.

    same as "kept" above: "This has two newlines.\n\n"
php: |
    array(
      'clipped' => "This has one newline.\n",
      'same as "clipped" above' => "This has one newline.\n",
      'stripped' => 'This has no newline.',
      'same as "stripped" above' => 'This has no newline.',
      'kept' => "This has two newlines.\n\n",
      'same as "kept" above' => "This has two newlines.\n\n"
    )
---
test: Literal combinations
todo: true
yaml: |
   empty: |

   literal: |
    The \ ' " characters may be
    freely used. Leading white
       space is significant.

    Line breaks are significant.
    Thus this value contains one
    empty line and ends with a
    single line break, but does
    not start with one.

   is equal to: "The \\ ' \" characters may \
    be\nfreely used. Leading white\n   space \
    is significant.\n\nLine breaks are \
    significant.\nThus this value contains \
    one\nempty line and ends with a\nsingle \
    line break, but does\nnot start with one.\n"

   # Comments may follow a block
   # scalar value. They must be
   # less indented.

   # Modifiers may be combined in any order.
   indented and chomped: |2-
       This has no newline.

   also written as: |-2
       This has no newline.

   both are equal to: "  This has no newline."
php: |
   array(
     'empty' => '',
     'literal' => "The \\ ' \" characters may be\nfreely used. Leading white\n   space " +
       "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" +
       "empty line and ends with a\nsingle line break, but does\nnot start with one.\n",
     'is equal to' => "The \\ ' \" characters may be\nfreely used. Leading white\n   space " +
       "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" +
       "empty line and ends with a\nsingle line break, but does\nnot start with one.\n",
     'indented and chomped' => '  This has no newline.',
     'also written as' => '  This has no newline.',
     'both are equal to' => '  This has no newline.'
   )
---
test: Folded combinations
todo: true
yaml: |
   empty: >

   one paragraph: >
    Line feeds are converted
    to spaces, so this value
    contains no line breaks
    except for the final one.

   multiple paragraphs: >2

     An empty line, either
     at the start or in
     the value:

     Is interpreted as a
     line break. Thus this
     value contains three
     line breaks.

   indented text: >
       This is a folded
       paragraph followed
       by a list:
        * first entry
        * second entry
       Followed by another
       folded paragraph,
       another list:

        * first entry

        * second entry

       And a final folded
       paragraph.

   above is equal to: |
       This is a folded paragraph followed by a list:
        * first entry
        * second entry
       Followed by another folded paragraph, another list:

        * first entry

        * second entry

       And a final folded paragraph.

   # Explicit comments may follow
   # but must be less indented.
php: |
   array(
     'empty' => '',
     'one paragraph' => 'Line feeds are converted to spaces, so this value'.
       " contains no line breaks except for the final one.\n",
     'multiple paragraphs' => "\nAn empty line, either at the start or in the value:\n".
       "Is interpreted as a line break. Thus this value contains three line breaks.\n",
     'indented text' => "This is a folded paragraph followed by a list:\n".
       " * first entry\n * second entry\nFollowed by another folded paragraph, ".
       "another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n",
     'above is equal to' => "This is a folded paragraph followed by a list:\n".
       " * first entry\n * second entry\nFollowed by another folded paragraph, ".
       "another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n"
   )
---
test: Single quotes
todo: true
yaml: |
   empty: ''
   second: '! : \ etc. can be used freely.'
   third: 'a single quote '' must be escaped.'
   span: 'this contains
         six spaces

         and one
         line break'
   is same as: "this contains six spaces\nand one line break"
php: |
   array(
     'empty' => '',
     'second' => '! : \\ etc. can be used freely.',
     'third' => "a single quote ' must be escaped.",
     'span' => "this contains six spaces\nand one line break",
     'is same as' => "this contains six spaces\nand one line break"
   )
---
test: Double quotes
todo: true
yaml: |
   empty: ""
   second: "! : etc. can be used freely."
   third: "a \" or a \\ must be escaped."
   fourth: "this value ends with an LF.\n"
   span: "this contains
     four  \
         spaces"
   is equal to: "this contains four  spaces"
php: |
   array(
     'empty' => '',
     'second' => '! : etc. can be used freely.',
     'third' => 'a " or a \\ must be escaped.',
     'fourth' => "this value ends with an LF.\n",
     'span' => "this contains four  spaces",
     'is equal to' => "this contains four  spaces"
   )
---
test: Unquoted strings
todo: true
yaml: |
   first: There is no unquoted empty string.

   second: 12          ## This is an integer.

   third: !str 12      ## This is a string.

   span: this contains
         six spaces

         and one
         line break

   indicators: this has no comments.
               #:foo and bar# are
               both text.

   flow: [ can span
              lines, # comment
              like
              this ]

   note: { one-line keys: but multi-line values }

php: |
   array(
     'first' => 'There is no unquoted empty string.',
     'second' => 12,
     'third' => '12',
     'span' => "this contains six spaces\nand one line break",
     'indicators' => "this has no comments. #:foo and bar# are both text.",
     'flow' => [ 'can span lines', 'like this' ],
     'note' => { 'one-line keys' => 'but multi-line values' }
   )
---
test: Spanning sequences
todo: true
yaml: |
   # The following are equal seqs
   # with different identities.
   flow: [ one, two ]
   spanning: [ one,
        two ]
   block:
     - one
     - two
php: |
   array(
     'flow' => [ 'one', 'two' ],
     'spanning' => [ 'one', 'two' ],
     'block' => [ 'one', 'two' ]
   )
---
test: Flow mappings
yaml: |
   # The following are equal maps
   # with different identities.
   flow: { one: 1, two: 2 }
   block:
       one: 1
       two: 2
php: |
   array(
     'flow' => array( 'one' => 1, 'two' => 2 ),
     'block' => array( 'one' => 1, 'two' => 2 )
   )
---
test: Representations of 12
todo: true
yaml: |
   - 12 # An integer
   # The following scalars
   # are loaded to the
   # string value '1' '2'.
   - !str 12
   - '12'
   - "12"
   - "\
     1\
     2\
     "
   # Strings containing paths and regexps can be unquoted:
   - /foo/bar
   - d:/foo/bar
   - foo/bar
   - /a.*b/
php: |
   array( 12, '12', '12', '12', '12', '/foo/bar', 'd:/foo/bar', 'foo/bar', '/a.*b/' )
---
test: "Null"
todo: true
yaml: |
   canonical: ~

   english: null

   # This sequence has five
   # entries, two with values.
   sparse:
     - ~
     - 2nd entry
     - Null
     - 4th entry
     -

   four: This mapping has five keys,
         only two with values.

php: |
   array (
     'canonical' => null,
     'english' => null,
     'sparse' => array( null, '2nd entry', null, '4th entry', null ]),
     'four' => 'This mapping has five keys, only two with values.'
   )
---
test: Omap
todo: true
yaml: |
   # Explicitly typed dictionary.
   Bestiary: !omap
     - aardvark: African pig-like ant eater. Ugly.
     - anteater: South-American ant eater. Two species.
     - anaconda: South-American constrictor snake. Scary.
     # Etc.
ruby: |
   {
     'Bestiary' => YAML::Omap[
       'aardvark', 'African pig-like ant eater. Ugly.',
       'anteater', 'South-American ant eater. Two species.',
       'anaconda', 'South-American constrictor snake. Scary.'
     ]
   }

---
test: Pairs
todo: true
yaml: |
  # Explicitly typed pairs.
  tasks: !pairs
    - meeting: with team.
    - meeting: with boss.
    - break: lunch.
    - meeting: with client.
ruby: |
  {
    'tasks' => YAML::Pairs[
      'meeting', 'with team.',
      'meeting', 'with boss.',
      'break', 'lunch.',
      'meeting', 'with client.'
    ]
  }

---
test: Set
todo: true
yaml: |
  # Explicitly typed set.
  baseball players: !set
    Mark McGwire:
    Sammy Sosa:
    Ken Griffey:
ruby: |
  {
    'baseball players' => YAML::Set[
      'Mark McGwire', nil,
      'Sammy Sosa', nil,
      'Ken Griffey', nil
    ]
  }

---
test: Boolean
yaml: |
   false: used as key
   logical:  true
   answer: false
php: |
   array(
     false => 'used as key',
     'logical' => true,
     'answer' => false
   )
---
test: Integer
yaml: |
   canonical: 12345
   decimal: +12,345
   octal: 014
   hexadecimal: 0xC
php: |
   array(
     'canonical' => 12345,
     'decimal' => 12345,
     'octal' => 12,
     'hexadecimal' => 12
   )
---
test: Float
yaml: |
   canonical: 1.23015e+3
   exponential: 12.3015e+02
   fixed: 1,230.15
   negative infinity: -.inf
   not a number: .NaN
php: |
  array(
    'canonical' => 1230.15,
    'exponential' => 1230.15,
    'fixed' => 1230.15,
    'negative infinity' => log(0),
    'not a number' => -log(0)
  )
---
test: Timestamp
todo: true
yaml: |
   canonical:       2001-12-15T02:59:43.1Z
   valid iso8601:   2001-12-14t21:59:43.10-05:00
   space separated: 2001-12-14 21:59:43.10 -05:00
   date (noon UTC): 2002-12-14
ruby: |
   array(
     'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ),
     'valid iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
     'space separated' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ),
     'date (noon UTC)' => Date.new( 2002, 12, 14 )
   )
---
test: Binary
todo: true
yaml: |
   canonical: !binary "\
    R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\
    OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\
    +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\
    AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="
   base64: !binary |
    R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
    OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
    +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
    AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
   description: >
    The binary value above is a tiny arrow
    encoded as a gif image.
ruby-setup: |
   arrow_gif = "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236iiiccc\243\243\243\204\204\204\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371!\376\016Made with GIMP\000,\000\000\000\000\f\000\f\000\000\005,  \216\2010\236\343@\024\350i\020\304\321\212\010\034\317\200M$z\357\3770\205p\270\2601f\r\e\316\001\303\001\036\020' \202\n\001\000;"
ruby: |
   {
     'canonical' => arrow_gif,
     'base64' => arrow_gif,
     'description' => "The binary value above is a tiny arrow encoded as a gif image.\n"
   }

---
test: Merge key
todo: true
yaml: |
  ---
  - &CENTER { x: 1, y: 2 }
  - &LEFT { x: 0, y: 2 }
  - &BIG { r: 10 }
  - &SMALL { r: 1 }

  # All the following maps are equal:

  - # Explicit keys
    x: 1
    y: 2
    r: 10
    label: center/big

  - # Merge one map
    << : *CENTER
    r: 10
    label: center/big

  - # Merge multiple maps
    << : [ *CENTER, *BIG ]
    label: center/big

  - # Override
    << : [ *BIG, *LEFT, *SMALL ]
    x: 1
    label: center/big

ruby-setup: |
  center = { 'x' => 1, 'y' => 2 }
  left = { 'x' => 0, 'y' => 2 }
  big = { 'r' => 10 }
  small = { 'r' => 1 }
  node1 = { 'x' => 1, 'y' => 2, 'r' => 10, 'label' => 'center/big' }
  node2 = center.dup
  node2.update( { 'r' => 10, 'label' => 'center/big' } )
  node3 = big.dup
  node3.update( center )
  node3.update( { 'label' => 'center/big' } )
  node4 = small.dup
  node4.update( left )
  node4.update( big )
  node4.update( { 'x' => 1, 'label' => 'center/big' } )

ruby: |
  [
    center, left, big, small, node1, node2, node3, node4
  ]

---
test: Default key
todo: true
yaml: |
   ---     # Old schema
   link with:
     - library1.dll
     - library2.dll
   ---     # New schema
   link with:
     - = : library1.dll
       version: 1.2
     - = : library2.dll
       version: 2.3
ruby: |
   y = YAML::Stream.new
   y.add( { 'link with' => [ 'library1.dll', 'library2.dll' ] } )
   obj_h = Hash[ 'version' => 1.2 ]
   obj_h.default = 'library1.dll'
   obj_h2 = Hash[ 'version' => 2.3 ]
   obj_h2.default = 'library2.dll'
   y.add( { 'link with' => [ obj_h, obj_h2 ] } )
documents: 2

---
test: Special keys
todo: true
yaml: |
   "!": These three keys
   "&": had to be quoted
   "=": and are normal strings.
   # NOTE: the following node should NOT be serialized this way.
   encoded node :
    !special '!' : '!type'
    !special|canonical '&' : 12
    = : value
   # The proper way to serialize the above node is as follows:
   node : !!type &12 value
ruby: |
   { '!' => 'These three keys', '&' => 'had to be quoted',
     '=' => 'and are normal strings.',
     'encoded node' => YAML::PrivateType.new( 'type', 'value' ),
     'node' => YAML::PrivateType.new( 'type', 'value' ) }
PK<1[~;�p2p20Yaml/Symfony/Component/Yaml/Tests/ParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Yaml\Parser;

class ParserTest extends \PHPUnit_Framework_TestCase
{
    protected $parser;

    protected function setUp()
    {
        $this->parser = new Parser();
    }

    protected function tearDown()
    {
        $this->parser = null;
    }

    /**
     * @dataProvider getDataFormSpecifications
     */
    public function testSpecifications($file, $expected, $yaml, $comment)
    {
        if ('escapedCharacters' == $file) {
            if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) {
                $this->markTestSkipped('The iconv and mbstring extensions are not available.');
            }
        }

        $this->assertEquals($expected, var_export($this->parser->parse($yaml), true), $comment);
    }

    public function getDataFormSpecifications()
    {
        $parser = new Parser();
        $path = __DIR__.'/Fixtures';

        $tests = array();
        $files = $parser->parse(file_get_contents($path.'/index.yml'));
        foreach ($files as $file) {
            $yamls = file_get_contents($path.'/'.$file.'.yml');

            // split YAMLs documents
            foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) {
                if (!$yaml) {
                    continue;
                }

                $test = $parser->parse($yaml);
                if (isset($test['todo']) && $test['todo']) {
                    // TODO
                } else {
                    eval('$expected = '.trim($test['php']).';');

                    $tests[] = array($file, var_export($expected, true), $test['yaml'], $test['test']);
                }
            }
        }

        return $tests;
    }

    public function testTabsInYaml()
    {
        // test tabs in YAML
        $yamls = array(
            "foo:\n	bar",
            "foo:\n 	bar",
            "foo:\n	 bar",
            "foo:\n 	 bar",
        );

        foreach ($yamls as $yaml) {
            try {
                $content = $this->parser->parse($yaml);

                $this->fail('YAML files must not contain tabs');
            } catch (\Exception $e) {
                $this->assertInstanceOf('\Exception', $e, 'YAML files must not contain tabs');
                $this->assertEquals('A YAML file cannot contain tabs as indentation at line 2 (near "'.strpbrk($yaml, "\t").'").', $e->getMessage(), 'YAML files must not contain tabs');
            }
        }
    }

    public function testEndOfTheDocumentMarker()
    {
        $yaml = <<<EOF
--- %YAML:1.0
foo
...
EOF;

        $this->assertEquals('foo', $this->parser->parse($yaml));
    }

    public function getBlockChompingTests()
    {
        $tests = array();

        $yaml = <<<'EOF'
foo: |-
    one
    two
bar: |-
    one
    two

EOF;
        $expected = array(
            'foo' => "one\ntwo",
            'bar' => "one\ntwo",
        );
        $tests['Literal block chomping strip with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |-
    one
    two

bar: |-
    one
    two


EOF;
        $expected = array(
            'foo' => "one\ntwo",
            'bar' => "one\ntwo",
        );
        $tests['Literal block chomping strip with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |-
    one
    two
bar: |-
    one
    two
EOF;
        $expected = array(
            'foo' => "one\ntwo",
            'bar' => "one\ntwo",
        );
        $tests['Literal block chomping strip without trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |
    one
    two
bar: |
    one
    two

EOF;
        $expected = array(
            'foo' => "one\ntwo\n",
            'bar' => "one\ntwo\n",
        );
        $tests['Literal block chomping clip with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |
    one
    two

bar: |
    one
    two


EOF;
        $expected = array(
            'foo' => "one\ntwo\n",
            'bar' => "one\ntwo\n",
        );
        $tests['Literal block chomping clip with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |
    one
    two
bar: |
    one
    two
EOF;
        $expected = array(
            'foo' => "one\ntwo\n",
            'bar' => "one\ntwo",
        );
        $tests['Literal block chomping clip without trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |+
    one
    two
bar: |+
    one
    two

EOF;
        $expected = array(
            'foo' => "one\ntwo\n",
            'bar' => "one\ntwo\n",
        );
        $tests['Literal block chomping keep with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |+
    one
    two

bar: |+
    one
    two


EOF;
        $expected = array(
            'foo' => "one\ntwo\n\n",
            'bar' => "one\ntwo\n\n",
        );
        $tests['Literal block chomping keep with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: |+
    one
    two
bar: |+
    one
    two
EOF;
        $expected = array(
            'foo' => "one\ntwo\n",
            'bar' => "one\ntwo",
        );
        $tests['Literal block chomping keep without trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >-
    one
    two
bar: >-
    one
    two

EOF;
        $expected = array(
            'foo' => "one two",
            'bar' => "one two",
        );
        $tests['Folded block chomping strip with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >-
    one
    two

bar: >-
    one
    two


EOF;
        $expected = array(
            'foo' => "one two",
            'bar' => "one two",
        );
        $tests['Folded block chomping strip with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >-
    one
    two
bar: >-
    one
    two
EOF;
        $expected = array(
            'foo' => "one two",
            'bar' => "one two",
        );
        $tests['Folded block chomping strip without trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >
    one
    two
bar: >
    one
    two

EOF;
        $expected = array(
            'foo' => "one two\n",
            'bar' => "one two\n",
        );
        $tests['Folded block chomping clip with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >
    one
    two

bar: >
    one
    two


EOF;
        $expected = array(
            'foo' => "one two\n",
            'bar' => "one two\n",
        );
        $tests['Folded block chomping clip with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >
    one
    two
bar: >
    one
    two
EOF;
        $expected = array(
            'foo' => "one two\n",
            'bar' => "one two",
        );
        $tests['Folded block chomping clip without trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >+
    one
    two
bar: >+
    one
    two

EOF;
        $expected = array(
            'foo' => "one two\n",
            'bar' => "one two\n",
        );
        $tests['Folded block chomping keep with single trailing newline'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >+
    one
    two

bar: >+
    one
    two


EOF;
        $expected = array(
            'foo' => "one two\n\n",
            'bar' => "one two\n\n",
        );
        $tests['Folded block chomping keep with multiple trailing newlines'] = array($expected, $yaml);

        $yaml = <<<'EOF'
foo: >+
    one
    two
bar: >+
    one
    two
EOF;
        $expected = array(
            'foo' => "one two\n",
            'bar' => "one two",
        );
        $tests['Folded block chomping keep without trailing newline'] = array($expected, $yaml);

        return $tests;
    }

    /**
     * @dataProvider getBlockChompingTests
     */
    public function testBlockChomping($expected, $yaml)
    {
        $this->assertSame($expected, $this->parser->parse($yaml));
    }

    /**
     * Regression test for issue #7989.
     *
     * @see https://github.com/symfony/symfony/issues/7989
     */
    public function testBlockLiteralWithLeadingNewlines()
    {
        $yaml = <<<'EOF'
foo: |-


    bar

EOF;
        $expected = array(
            'foo' => "\n\nbar"
        );

        $this->assertSame($expected, $this->parser->parse($yaml));
    }

    public function testObjectSupportEnabled()
    {
        $input = <<<EOF
foo: !!php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";}
bar: 1
EOF;
        $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects');
    }

    public function testObjectSupportDisabledButNoExceptions()
    {
        $input = <<<EOF
foo: !!php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";}
bar: 1
EOF;

        $this->assertEquals(array('foo' => null, 'bar' => 1), $this->parser->parse($input), '->parse() does not parse objects');
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testObjectsSupportDisabledWithExceptions()
    {
        $this->parser->parse('foo: !!php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";}', true, false);
    }

    public function testNonUtf8Exception()
    {
        if (!function_exists('mb_detect_encoding') || !function_exists('iconv')) {
            $this->markTestSkipped('Exceptions for non-utf8 charsets require the mb_detect_encoding() and iconv() functions.');

            return;
        }

        $yamls = array(
            iconv("UTF-8", "ISO-8859-1", "foo: 'äöüß'"),
            iconv("UTF-8", "ISO-8859-15", "euro: '€'"),
            iconv("UTF-8", "CP1252", "cp1252: '©ÉÇáñ'")
        );

        foreach ($yamls as $yaml) {
            try {
                $this->parser->parse($yaml);

                $this->fail('charsets other than UTF-8 are rejected.');
            } catch (\Exception $e) {
                 $this->assertInstanceOf('Symfony\Component\Yaml\Exception\ParseException', $e, 'charsets other than UTF-8 are rejected.');
            }
        }
    }

    /**
     *
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     *
     */
    public function testUnindentedCollectionException()
    {
        $yaml = <<<EOF

collection:
-item1
-item2
-item3

EOF;

        $this->parser->parse($yaml);
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testSequenceInAMapping()
    {
        Yaml::parse(<<<EOF
yaml:
  hash: me
  - array stuff
EOF
        );
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testMappingInASequence()
    {
        Yaml::parse(<<<EOF
yaml:
  - array stuff
  hash: me
EOF
        );
    }

    public function testEmptyValue()
    {
        $input = <<<EOF
hash:
EOF;

        $this->assertEquals(array('hash' => null), Yaml::parse($input));
    }

    public function testStringBlockWithComments()
    {
        $this->assertEquals(array('content' => <<<EOT
# comment 1
header

    # comment 2
    <body>
        <h1>title</h1>
    </body>

footer # comment3
EOT
        ), Yaml::parse(<<<EOF
content: |
    # comment 1
    header

        # comment 2
        <body>
            <h1>title</h1>
        </body>

    footer # comment3
EOF
        ));
    }

    public function testFoldedStringBlockWithComments()
    {
        $this->assertEquals(array(array('content' => <<<EOT
# comment 1
header

    # comment 2
    <body>
        <h1>title</h1>
    </body>

footer # comment3
EOT
        )), Yaml::parse(<<<EOF
-
    content: |
        # comment 1
        header

            # comment 2
            <body>
                <h1>title</h1>
            </body>

        footer # comment3
EOF
        ));
    }

    public function testNestedFoldedStringBlockWithComments()
    {
        $this->assertEquals(array(array(
            'title'   => 'some title',
            'content' => <<<EOT
# comment 1
header

    # comment 2
    <body>
        <h1>title</h1>
    </body>

footer # comment3
EOT
        )), Yaml::parse(<<<EOF
-
    title: some title
    content: |
        # comment 1
        header

            # comment 2
            <body>
                <h1>title</h1>
            </body>

        footer # comment3
EOF
        ));
    }
}

class B
{
    public $b = 'foo';
}
PK<1[=a�o[%[%0Yaml/Symfony/Component/Yaml/Tests/InlineTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Inline;

class InlineTest extends \PHPUnit_Framework_TestCase
{
    public function testParse()
    {
        foreach ($this->getTestsForParse() as $yaml => $value) {
            $this->assertSame($value, Inline::parse($yaml), sprintf('::parse() converts an inline YAML to a PHP structure (%s)', $yaml));
        }
    }

    public function testDump()
    {
        $testsForDump = $this->getTestsForDump();

        foreach ($testsForDump as $yaml => $value) {
            $this->assertEquals($yaml, Inline::dump($value), sprintf('::dump() converts a PHP structure to an inline YAML (%s)', $yaml));
        }

        foreach ($this->getTestsForParse() as $value) {
            $this->assertEquals($value, Inline::parse(Inline::dump($value)), 'check consistency');
        }

        foreach ($testsForDump as $value) {
            $this->assertEquals($value, Inline::parse(Inline::dump($value)), 'check consistency');
        }
    }

    public function testDumpNumericValueWithLocale()
    {
        $locale = setlocale(LC_NUMERIC, 0);
        if (false === $locale) {
            $this->markTestSkipped('Your platform does not support locales.');
        }

        $required_locales = array('fr_FR.UTF-8', 'fr_FR.UTF8', 'fr_FR.utf-8', 'fr_FR.utf8', 'French_France.1252');
        if (false === setlocale(LC_ALL, $required_locales)) {
            $this->markTestSkipped('Could not set any of required locales: '.implode(", ", $required_locales));
        }

        $this->assertEquals('1.2', Inline::dump(1.2));
        $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0)));

        setlocale(LC_ALL, $locale);
    }

    public function testHashStringsResemblingExponentialNumericsShouldNotBeChangedToINF()
    {
        $value = '686e444';

        $this->assertSame($value, Inline::parse(Inline::dump($value)));
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException()
    {
        $value = "'don't do somthin' like that'";
        Inline::parse($value);
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException()
    {
        $value = '"don"t do somthin" like that"';
        Inline::parse($value);
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testParseInvalidMappingKeyShouldThrowException()
    {
        $value = '{ "foo " bar": "bar" }';
        Inline::parse($value);
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testParseInvalidMappingShouldThrowException()
    {
        Inline::parse('[foo] bar');
    }

    /**
     * @expectedException \Symfony\Component\Yaml\Exception\ParseException
     */
    public function testParseInvalidSequenceShouldThrowException()
    {
        Inline::parse('{ foo: bar } bar');
    }

    public function testParseScalarWithCorrectlyQuotedStringShouldReturnString()
    {
        $value = "'don''t do somthin'' like that'";
        $expect = "don't do somthin' like that";

        $this->assertSame($expect, Inline::parseScalar($value));
    }

    protected function getTestsForParse()
    {
        return array(
            '' => '',
            'null' => null,
            'false' => false,
            'true' => true,
            '12' => 12,
            '-12' => -12,
            '"quoted string"' => 'quoted string',
            "'quoted string'" => 'quoted string',
            '12.30e+02' => 12.30e+02,
            '0x4D2' => 0x4D2,
            '02333' => 02333,
            '.Inf' => -log(0),
            '-.Inf' => log(0),
            "'686e444'" => '686e444',
            '686e444' => 646e444,
            '123456789123456789123456789123456789' => '123456789123456789123456789123456789',
            '"foo\r\nbar"' => "foo\r\nbar",
            "'foo#bar'" => 'foo#bar',
            "'foo # bar'" => 'foo # bar',
            "'#cfcfcf'" => '#cfcfcf',
            '::form_base.html.twig' => '::form_base.html.twig',

            '2007-10-30' => mktime(0, 0, 0, 10, 30, 2007),
            '2007-10-30T02:59:43Z' => gmmktime(2, 59, 43, 10, 30, 2007),
            '2007-10-30 02:59:43 Z' => gmmktime(2, 59, 43, 10, 30, 2007),
            '1960-10-30 02:59:43 Z' => gmmktime(2, 59, 43, 10, 30, 1960),
            '1730-10-30T02:59:43Z' => gmmktime(2, 59, 43, 10, 30, 1730),

            '"a \\"string\\" with \'quoted strings inside\'"' => 'a "string" with \'quoted strings inside\'',
            "'a \"string\" with ''quoted strings inside'''" => 'a "string" with \'quoted strings inside\'',

            // sequences
            // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon
            '[foo, http://urls.are/no/mappings, false, null, 12]' => array('foo', 'http://urls.are/no/mappings', false, null, 12),
            '[  foo  ,   bar , false  ,  null     ,  12  ]' => array('foo', 'bar', false, null, 12),
            '[\'foo,bar\', \'foo bar\']' => array('foo,bar', 'foo bar'),

            // mappings
            '{foo:bar,bar:foo,false:false,null:null,integer:12}' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12),
            '{ foo  : bar, bar : foo,  false  :   false,  null  :   null,  integer :  12  }' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12),
            '{foo: \'bar\', bar: \'foo: bar\'}' => array('foo' => 'bar', 'bar' => 'foo: bar'),
            '{\'foo\': \'bar\', "bar": \'foo: bar\'}' => array('foo' => 'bar', 'bar' => 'foo: bar'),
            '{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}' => array('foo\'' => 'bar', "bar\"" => 'foo: bar'),
            '{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}' => array('foo: ' => 'bar', "bar: " => 'foo: bar'),

            // nested sequences and mappings
            '[foo, [bar, foo]]' => array('foo', array('bar', 'foo')),
            '[foo, {bar: foo}]' => array('foo', array('bar' => 'foo')),
            '{ foo: {bar: foo} }' => array('foo' => array('bar' => 'foo')),
            '{ foo: [bar, foo] }' => array('foo' => array('bar', 'foo')),

            '[  foo, [  bar, foo  ]  ]' => array('foo', array('bar', 'foo')),

            '[{ foo: {bar: foo} }]' => array(array('foo' => array('bar' => 'foo'))),

            '[foo, [bar, [foo, [bar, foo]], foo]]' => array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo')),

            '[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]' => array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo'))),

            '[foo, bar: { foo: bar }]' => array('foo', '1' => array('bar' => array('foo' => 'bar'))),
            '[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']' => array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%',), true, '@service_container',),
        );
    }

    protected function getTestsForDump()
    {
        return array(
            'null' => null,
            'false' => false,
            'true' => true,
            '12' => 12,
            "'quoted string'" => 'quoted string',
            '12.30e+02' => 12.30e+02,
            '1234' => 0x4D2,
            '1243' => 02333,
            '.Inf' => -log(0),
            '-.Inf' => log(0),
            "'686e444'" => '686e444',
            '"foo\r\nbar"' => "foo\r\nbar",
            "'foo#bar'" => 'foo#bar',
            "'foo # bar'" => 'foo # bar',
            "'#cfcfcf'" => '#cfcfcf',

            "'a \"string\" with ''quoted strings inside'''" => 'a "string" with \'quoted strings inside\'',

            "'-dash'" => '-dash',
            "'-'" => '-',

            // sequences
            '[foo, bar, false, null, 12]' => array('foo', 'bar', false, null, 12),
            '[\'foo,bar\', \'foo bar\']' => array('foo,bar', 'foo bar'),

            // mappings
            '{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }' => array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12),
            '{ foo: bar, bar: \'foo: bar\' }' => array('foo' => 'bar', 'bar' => 'foo: bar'),

            // nested sequences and mappings
            '[foo, [bar, foo]]' => array('foo', array('bar', 'foo')),

            '[foo, [bar, [foo, [bar, foo]], foo]]' => array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo')),

            '{ foo: { bar: foo } }' => array('foo' => array('bar' => 'foo')),

            '[foo, { bar: foo }]' => array('foo', array('bar' => 'foo')),

            '[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]' => array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo'))),

            '[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']' => array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%',), true, '@service_container',),
        );
    }
}
PK<1[`�@ee.Yaml/Symfony/Component/Yaml/Tests/YamlTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Yaml;

class YamlTest extends \PHPUnit_Framework_TestCase
{
    public function testParseAndDump()
    {
        $data = array('lorem' => 'ipsum', 'dolor' => 'sit');
        $yml = Yaml::dump($data);
        $parsed = Yaml::parse($yml);
        $this->assertEquals($data, $parsed);

        $filename = __DIR__.'/Fixtures/index.yml';
        $contents = file_get_contents($filename);
        $parsedByFilename = Yaml::parse($filename);
        $parsedByContents = Yaml::parse($contents);
        $this->assertEquals($parsedByFilename, $parsedByContents);
    }
}
PK<1[��?o��8Yaml/Symfony/Component/Yaml/Tests/ParseExceptionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Yaml\Tests;

use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

class ParseExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testGetMessage()
    {
        $exception = new ParseException('Error message', 42, 'foo: bar', '/var/www/app/config.yml');
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            $message = 'Error message in "/var/www/app/config.yml" at line 42 (near "foo: bar")';
        } else {
            $message = 'Error message in "\\/var\\/www\\/app\\/config.yml" at line 42 (near "foo: bar")';
        }

        $this->assertEquals($message, $exception->getMessage());
    }
}
PK<1[�>[33,Yaml/Symfony/Component/Yaml/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Yaml Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./vendor</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK<1[����$Console_Getopt/tests/001-getopt.phptnu�[���--TEST--
Console_Getopt
--FILE--
<?php
require_once 'Console/Getopt.php';
PEAR::setErrorHandling(PEAR_ERROR_PRINT, "%s\n\n");

function test($argstr, $optstr) {
    $argv = preg_split('/[[:space:]]+/', $argstr);
    if (PEAR::isError($options = Console_Getopt::getopt($argv, $optstr))) {
        return;
    }
    $opts = $options[0];
    $non_opts = $options[1];
    $i = 0;
    print "options: ";
    foreach ($opts as $o => $d) {
        if ($i++ > 0) {
            print ", ";
        }
        print $d[0] . '=' . $d[1];
    }
    print "\n";
    print "params: " . implode(", ", $non_opts) . "\n";
    print "\n";
}

test("-abc", "abc");
test("-abc foo", "abc");
test("-abc foo", "abc:");
test("-abc foo bar gazonk", "abc");
test("-abc foo bar gazonk", "abc:");
test("-a -b -c", "abc");
test("-a -b -c", "abc:");
test("-abc", "ab:c");
test("-abc foo -bar gazonk", "abc");
?>
--EXPECT--
options: a=, b=, c=
params: 

options: a=, b=, c=
params: foo

options: a=, b=, c=foo
params: 

options: a=, b=, c=
params: foo, bar, gazonk

options: a=, b=, c=foo
params: bar, gazonk

options: a=, b=, c=
params: 

Console_Getopt: option requires an argument --c

options: a=, b=c
params: 

options: a=, b=, c=
params: foo, -bar, gazonk
PK<1[��"Console_Getopt/tests/bug11068.phptnu�[���--TEST--
Console_Getopt [bug 11068]
--SKIPIF--
--FILE--
<?php
$_SERVER['argv'] =
$argv = array('hi', '-fjjohnston@mail.com', '--to', 'hi', '-');
require_once 'Console/Getopt.php';
$ret = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), 'f:t:',
array('from=','to=','mailpack=','direction=','verbose','debug'));
if(PEAR::isError($ret))
{
	echo $ret->getMessage()."\n";
	echo 'FATAL';
	exit;
}

print_r($ret);
?>
--EXPECT--
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => f
                    [1] => jjohnston@mail.com
                )

            [1] => Array
                (
                    [0] => --to
                    [1] => hi
                )

        )

    [1] => Array
        (
            [0] => -
        )

)PK<1[���"Console_Getopt/tests/bug10557.phptnu�[���--TEST--
Console_Getopt [bug 10557]
--SKIPIF--
--FILE--
<?php
$_SERVER['argv'] =
$argv = array('hi', '-fjjohnston@mail.com', '--to', '--mailpack', '--debug');
require_once 'Console/Getopt.php';
$ret = Console_Getopt::getopt(Console_Getopt::readPHPArgv(), 'f:t:',
array('from=','to=','mailpack=','direction=','verbose','debug'));
if(PEAR::isError($ret))
{
	echo $ret->getMessage()."\n";
	echo 'FATAL';
	exit;
}

print_r($ret);
?>
--EXPECT--
Console_Getopt: option requires an argument --to
FATALPK<1[��|EE"Console_Getopt/tests/bug13140.phptnu�[���--TEST--
Console_Getopt [bug 13140]
--SKIPIF--
--FILE--
<?php
$_SERVER['argv'] = $argv =
    array('--bob', '--foo' , '-bar', '--test', '-rq', 'thisshouldbehere');

require_once 'Console/Getopt.php';
$cg = new Console_GetOpt();

print_r($cg->getopt2($cg->readPHPArgv(), 't', array('test'), true));
print_r($cg->getopt2($cg->readPHPArgv(), 'bar', array('foo'), true));
?>
--EXPECT--
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => --test
                    [1] => 
                )

        )

    [1] => Array
        (
            [0] => thisshouldbehere
        )

)
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => --foo
                    [1] => 
                )

            [1] => Array
                (
                    [0] => b
                    [1] => 
                )

            [2] => Array
                (
                    [0] => a
                    [1] => 
                )

            [3] => Array
                (
                    [0] => r
                    [1] => 
                )

            [4] => Array
                (
                    [0] => r
                    [1] => 
                )

        )

    [1] => Array
        (
            [0] => thisshouldbehere
        )

)
PK<1[��mg�
�
EHttpFoundation/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\IpUtils;

class IpUtilsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider testIpv4Provider
     */
    public function testIpv4($matches, $remoteAddr, $cidr)
    {
        $this->assertSame($matches, IpUtils::checkIp($remoteAddr, $cidr));
    }

    public function testIpv4Provider()
    {
        return array(
            array(true, '192.168.1.1', '192.168.1.1'),
            array(true, '192.168.1.1', '192.168.1.1/1'),
            array(true, '192.168.1.1', '192.168.1.0/24'),
            array(false, '192.168.1.1', '1.2.3.4/1'),
            array(false, '192.168.1.1', '192.168.1/33'),
            array(true, '192.168.1.1', array('1.2.3.4/1', '192.168.1.0/24')),
            array(true, '192.168.1.1', array('192.168.1.0/24', '1.2.3.4/1')),
            array(false, '192.168.1.1', array('1.2.3.4/1', '4.3.2.1/1')),
        );
    }

    /**
     * @dataProvider testIpv6Provider
     */
    public function testIpv6($matches, $remoteAddr, $cidr)
    {
        if (!defined('AF_INET6')) {
            $this->markTestSkipped('Only works when PHP is compiled without the option "disable-ipv6".');
        }

        $this->assertSame($matches, IpUtils::checkIp($remoteAddr, $cidr));
    }

    public function testIpv6Provider()
    {
        return array(
            array(true, '2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
            array(false, '2a00:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65'),
            array(false, '2a01:198:603:0:396e:4789:8e99:890f', '::1'),
            array(true, '0:0:0:0:0:0:0:1', '::1'),
            array(false, '0:0:603:0:396e:4789:8e99:0001', '::1'),
            array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '2a01:198:603:0::/65')),
            array(true, '2a01:198:603:0:396e:4789:8e99:890f', array('2a01:198:603:0::/65', '::1')),
            array(false, '2a01:198:603:0:396e:4789:8e99:890f', array('::1', '1a01:198:603:0::/65')),
        );
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testAnIpv6WithOptionDisabledIpv6()
    {
        if (!extension_loaded('sockets')) {
            $this->markTestSkipped('Only works when the socket extension is enabled');
        }

        if (defined('AF_INET6')) {
            $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".');
        }

        IpUtils::checkIp('2a01:198:603:0:396e:4789:8e99:890f', '2a01:198:603:0::/65');
    }
}
PK<1[��JHttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestStackTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class RequestStackTest extends \PHPUnit_Framework_TestCase
{
    public function testGetCurrentRequest()
    {
        $requestStack = new RequestStack();
        $this->assertNull($requestStack->getCurrentRequest());

        $request = Request::create('/foo');

        $requestStack->push($request);
        $this->assertSame($request, $requestStack->getCurrentRequest());

        $this->assertSame($request, $requestStack->pop());
        $this->assertNull($requestStack->getCurrentRequest());

        $this->assertNull($requestStack->pop());
    }

    public function testGetMasterRequest()
    {
        $requestStack = new RequestStack();
        $this->assertNull($requestStack->getMasterRequest());

        $masterRequest = Request::create('/foo');
        $subRequest = Request::create('/bar');

        $requestStack->push($masterRequest);
        $requestStack->push($subRequest);

        $this->assertSame($masterRequest, $requestStack->getMasterRequest());
    }

    public function testGetParentRequest()
    {
        $requestStack = new RequestStack();
        $this->assertNull($requestStack->getParentRequest());

        $masterRequest = Request::create('/foo');

        $requestStack->push($masterRequest);
        $this->assertNull($requestStack->getParentRequest());

        $firstSubRequest = Request::create('/bar');

        $requestStack->push($firstSubRequest);
        $this->assertSame($masterRequest, $requestStack->getParentRequest());

        $secondSubRequest = Request::create('/baz');

        $requestStack->push($secondSubRequest);
        $this->assertSame($firstSubRequest, $requestStack->getParentRequest());
    }
}
PK<1[��lOD
D
JHttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Request;

abstract class ResponseTestCase extends \PHPUnit_Framework_TestCase
{
    public function testNoCacheControlHeaderOnAttachmentUsingHTTPSAndMSIE()
    {
        // Check for HTTPS and IE 8
        $request = new Request();
        $request->server->set('HTTPS', true);
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertFalse($response->headers->has('Cache-Control'));

        // Check for IE 10 and HTTPS
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));

        // Check for IE 9 and HTTPS
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));

        // Check for IE 9 and HTTP
        $request->server->set('HTTPS', false);

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));

        // Check for IE 8 and HTTP
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));

        // Check for non-IE and HTTPS
        $request->server->set('HTTPS', true);
        $request->server->set('HTTP_USER_AGENT', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.60 Safari/537.17');

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));

        // Check for non-IE and HTTP
        $request->server->set('HTTPS', false);

        $response = $this->provideResponse();
        $response->headers->set('Content-Disposition', 'attachment; filename="fname.ext"');
        $response->prepare($request);

        $this->assertTrue($response->headers->has('Cache-Control'));
    }

    abstract protected function provideResponse();
}
PK<1[�F�9bbDHttpFoundation/Symfony/Component/HttpFoundation/Tests/CookieTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Cookie;

/**
 * CookieTest
 *
 * @author John Kary <john@johnkary.net>
 * @author Hugo Hamon <hugo.hamon@sensio.com>
 */
class CookieTest extends \PHPUnit_Framework_TestCase
{
    public function invalidNames()
    {
        return array(
            array(''),
            array(",MyName"),
            array(";MyName"),
            array(" MyName"),
            array("\tMyName"),
            array("\rMyName"),
            array("\nMyName"),
            array("\013MyName"),
            array("\014MyName"),
        );
    }

    /**
     * @dataProvider invalidNames
     * @expectedException \InvalidArgumentException
     * @covers Symfony\Component\HttpFoundation\Cookie::__construct
     */
    public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name)
    {
        new Cookie($name);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidExpiration()
    {
        $cookie = new Cookie('MyCookie', 'foo', 'bar');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Cookie::getValue
     */
    public function testGetValue()
    {
        $value = 'MyValue';
        $cookie = new Cookie('MyCookie', $value);

        $this->assertSame($value, $cookie->getValue(), '->getValue() returns the proper value');
    }

    public function testGetPath()
    {
        $cookie = new Cookie('foo', 'bar');

        $this->assertSame('/', $cookie->getPath(), '->getPath() returns / as the default path');
    }

    public function testGetExpiresTime()
    {
        $cookie = new Cookie('foo', 'bar', 3600);

        $this->assertEquals(3600, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
    }

    public function testConstructorWithDateTime()
    {
        $expire = new \DateTime();
        $cookie = new Cookie('foo', 'bar', $expire);

        $this->assertEquals($expire->format('U'), $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
    }

    public function testGetExpiresTimeWithStringValue()
    {
        $value = "+1 day";
        $cookie = new Cookie('foo', 'bar', $value);
        $expire = strtotime($value);

        $this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date');
    }

    public function testGetDomain()
    {
        $cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com');

        $this->assertEquals('.myfoodomain.com', $cookie->getDomain(), '->getDomain() returns the domain name on which the cookie is valid');
    }

    public function testIsSecure()
    {
        $cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com', true);

        $this->assertTrue($cookie->isSecure(), '->isSecure() returns whether the cookie is transmitted over HTTPS');
    }

    public function testIsHttpOnly()
    {
        $cookie = new Cookie('foo', 'bar', 3600, '/', '.myfoodomain.com', false, true);

        $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns whether the cookie is only transmitted over HTTP');
    }

    public function testCookieIsNotCleared()
    {
        $cookie = new Cookie('foo', 'bar', time()+3600*24);

        $this->assertFalse($cookie->isCleared(), '->isCleared() returns false if the cookie did not expire yet');
    }

    public function testCookieIsCleared()
    {
        $cookie = new Cookie('foo', 'bar', time()-20);

        $this->assertTrue($cookie->isCleared(), '->isCleared() returns true if the cookie has expired');
    }

    public function testToString()
    {
        $cookie = new Cookie('foo', 'bar', strtotime('Fri, 20-May-2011 15:25:52 GMT'), '/', '.myfoodomain.com', true);
        $this->assertEquals('foo=bar; expires=Fri, 20-May-2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly', $cookie->__toString(), '->__toString() returns string representation of the cookie');

        $cookie = new Cookie('foo', null, 1, '/admin/', '.myfoodomain.com');
        $this->assertEquals('foo=deleted; expires='.gmdate("D, d-M-Y H:i:s T", time()-31536001).'; path=/admin/; domain=.myfoodomain.com; httponly', $cookie->__toString(), '->__toString() returns string representation of a cleared cookie if value is NULL');

        $cookie = new Cookie('foo', 'bar', 0, '/', '');
        $this->assertEquals('foo=bar; path=/; httponly', $cookie->__toString());
    }
}
PK<1[�q�H��NHttpFoundation/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\RedirectResponse;

class RedirectResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testGenerateMetaRedirect()
    {
        $response = new RedirectResponse('foo.bar');

        $this->assertEquals(1, preg_match(
            '#<meta http-equiv="refresh" content="\d+;url=foo\.bar" />#',
            preg_replace(array('/\s+/', '/\'/'), array(' ', '"'), $response->getContent())
        ));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRedirectResponseConstructorNullUrl()
    {
        $response = new RedirectResponse(null);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRedirectResponseConstructorWrongStatusCode()
    {
        $response = new RedirectResponse('foo.bar', 404);
    }

    public function testGenerateLocationHeader()
    {
        $response = new RedirectResponse('foo.bar');

        $this->assertTrue($response->headers->has('Location'));
        $this->assertEquals('foo.bar', $response->headers->get('Location'));
    }

    public function testGetTargetUrl()
    {
        $response = new RedirectResponse('foo.bar');

        $this->assertEquals('foo.bar', $response->getTargetUrl());
    }

    public function testSetTargetUrl()
    {
        $response = new RedirectResponse('foo.bar');
        $response->setTargetUrl('baz.beep');

        $this->assertEquals('baz.beep', $response->getTargetUrl());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetTargetUrlNull()
    {
        $response = new RedirectResponse('foo.bar');
        $response->setTargetUrl(null);
    }

    public function testCreate()
    {
        $response = RedirectResponse::create('foo', 301);

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
        $this->assertEquals(301, $response->getStatusCode());
    }
}
PK<1[qr��



VHttpFoundation/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpFoundation\ExpressionRequestMatcher;
use Symfony\Component\HttpFoundation\Request;

class ExpressionRequestMatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     */
    public function testWhenNoExpressionIsSet()
    {
        $expressionRequestMatcher = new ExpressionRequestMatcher();
        $expressionRequestMatcher->matches(new Request());
    }

    /**
     * @dataProvider provideExpressions
     */
    public function testMatchesWhenParentMatchesIsTrue($expression, $expected)
    {
        $request = Request::create('/foo');
        $expressionRequestMatcher = new ExpressionRequestMatcher();

        $expressionRequestMatcher->setExpression(new ExpressionLanguage(), $expression);
        $this->assertSame($expected, $expressionRequestMatcher->matches($request));
    }

    /**
     * @dataProvider provideExpressions
     */
    public function testMatchesWhenParentMatchesIsFalse($expression)
    {
        $request = Request::create('/foo');
        $request->attributes->set('foo', 'foo');
        $expressionRequestMatcher = new ExpressionRequestMatcher();
        $expressionRequestMatcher->matchAttribute('foo', 'bar');

        $expressionRequestMatcher->setExpression(new ExpressionLanguage(), $expression);
        $this->assertFalse($expressionRequestMatcher->matches($request));
    }

    public function provideExpressions()
    {
        return array(
            array('request.getMethod() == method', true),
            array('request.getPathInfo() == path', true),
            array('request.getHost() == host', true),
            array('request.getClientIp() == ip', true),
            array('request.attributes.all() == attributes', true),
            array('request.getMethod() == method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip &&  request.attributes.all() == attributes', true),
            array('request.getMethod() != method', false),
            array('request.getMethod() != method && request.getPathInfo() == path && request.getHost() == host && request.getClientIp() == ip &&  request.attributes.all() == attributes', false),
        );
    }
}
PK<1[_�|���PHttpFoundation/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

class BinaryFileResponseTest extends ResponseTestCase
{
    public function testConstruction()
    {
        $response = new BinaryFileResponse('README.md', 404, array('X-Header' => 'Foo'), true, null, true, true);
        $this->assertEquals(404, $response->getStatusCode());
        $this->assertEquals('Foo', $response->headers->get('X-Header'));
        $this->assertTrue($response->headers->has('ETag'));
        $this->assertTrue($response->headers->has('Last-Modified'));
        $this->assertFalse($response->headers->has('Content-Disposition'));

        $response = BinaryFileResponse::create('README.md', 404, array(), true, ResponseHeaderBag::DISPOSITION_INLINE);
        $this->assertEquals(404, $response->getStatusCode());
        $this->assertFalse($response->headers->has('ETag'));
        $this->assertEquals('inline; filename="README.md"', $response->headers->get('Content-Disposition'));
    }

    /**
     * @expectedException \LogicException
     */
    public function testSetContent()
    {
        $response = new BinaryFileResponse('README.md');
        $response->setContent('foo');
    }

    public function testGetContent()
    {
        $response = new BinaryFileResponse('README.md');
        $this->assertFalse($response->getContent());
    }

    /**
     * @dataProvider provideRanges
     */
    public function testRequests($requestRange, $offset, $length, $responseRange)
    {
        $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif')->setAutoEtag();

        // do a request to get the ETag
        $request = Request::create('/');
        $response->prepare($request);
        $etag = $response->headers->get('ETag');

        // prepare a request for a range of the testing file
        $request = Request::create('/');
        $request->headers->set('If-Range', $etag);
        $request->headers->set('Range', $requestRange);

        $file = fopen(__DIR__.'/File/Fixtures/test.gif', 'r');
        fseek($file, $offset);
        $data = fread($file, $length);
        fclose($file);

        $this->expectOutputString($data);
        $response = clone $response;
        $response->prepare($request);
        $response->sendContent();

        $this->assertEquals(206, $response->getStatusCode());
        $this->assertEquals('binary', $response->headers->get('Content-Transfer-Encoding'));
        $this->assertEquals($responseRange, $response->headers->get('Content-Range'));
    }

    public function provideRanges()
    {
        return array(
            array('bytes=1-4', 1, 4, 'bytes 1-4/35'),
            array('bytes=-5', 30, 5, 'bytes 30-34/35'),
            array('bytes=30-', 30, 5, 'bytes 30-34/35'),
            array('bytes=30-30', 30, 1, 'bytes 30-30/35'),
            array('bytes=30-34', 30, 5, 'bytes 30-34/35'),
        );
    }

    /**
     * @dataProvider provideFullFileRanges
     */
    public function testFullFileRequests($requestRange)
    {
        $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif')->setAutoEtag();

        // prepare a request for a range of the testing file
        $request = Request::create('/');
        $request->headers->set('Range', $requestRange);

        $file = fopen(__DIR__.'/File/Fixtures/test.gif', 'r');
        $data = fread($file, 35);
        fclose($file);

        $this->expectOutputString($data);
        $response = clone $response;
        $response->prepare($request);
        $response->sendContent();

        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals('binary', $response->headers->get('Content-Transfer-Encoding'));
    }

    public function provideFullFileRanges()
    {
        return array(
            array('bytes=0-'),
            array('bytes=0-34'),
            array('bytes=-35'),
            // Syntactical invalid range-request should also return the full resource
            array('bytes=20-10'),
            array('bytes=50-40'),
        );
    }

    /**
     * @dataProvider provideInvalidRanges
     */
    public function testInvalidRequests($requestRange)
    {
        $response = BinaryFileResponse::create(__DIR__.'/File/Fixtures/test.gif')->setAutoEtag();

        // prepare a request for a range of the testing file
        $request = Request::create('/');
        $request->headers->set('Range', $requestRange);

        $response = clone $response;
        $response->prepare($request);
        $response->sendContent();

        $this->assertEquals(416, $response->getStatusCode());
        $this->assertEquals('binary', $response->headers->get('Content-Transfer-Encoding'));
        #$this->assertEquals('', $response->headers->get('Content-Range'));
    }

    public function provideInvalidRanges()
    {
        return array(
            array('bytes=-40'),
            array('bytes=30-40')
        );
    }

    public function testXSendfile()
    {
        $request = Request::create('/');
        $request->headers->set('X-Sendfile-Type', 'X-Sendfile');

        BinaryFileResponse::trustXSendfileTypeHeader();
        $response = BinaryFileResponse::create('README.md');
        $response->prepare($request);

        $this->expectOutputString('');
        $response->sendContent();

        $this->assertContains('README.md', $response->headers->get('X-Sendfile'));
    }

    /**
     * @dataProvider getSampleXAccelMappings
     */
    public function testXAccelMapping($realpath, $mapping, $virtual)
    {
        $request = Request::create('/');
        $request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect');
        $request->headers->set('X-Accel-Mapping', $mapping);

        $file = $this->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
                     ->disableOriginalConstructor()
                     ->getMock();
        $file->expects($this->any())
             ->method('getRealPath')
             ->will($this->returnValue($realpath));
        $file->expects($this->any())
             ->method('isReadable')
             ->will($this->returnValue(true));

        BinaryFileResponse::trustXSendFileTypeHeader();
        $response = new BinaryFileResponse('README.md');
        $reflection = new \ReflectionObject($response);
        $property = $reflection->getProperty('file');
        $property->setAccessible(true);
        $property->setValue($response, $file);

        $response->prepare($request);
        $this->assertEquals($virtual, $response->headers->get('X-Accel-Redirect'));
    }

    public function getSampleXAccelMappings()
    {
        return array(
            array('/var/www/var/www/files/foo.txt', '/files/=/var/www/', '/files/var/www/files/foo.txt'),
            array('/home/foo/bar.txt', '/files/=/var/www/,/baz/=/home/foo/', '/baz/bar.txt'),
        );
    }

    protected function provideResponse()
    {
        return new BinaryFileResponse('README.md');
    }
}
PK<1[��@LLEHttpFoundation/Symfony/Component/HttpFoundation/Tests/FileBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\FileBag;

/**
 * FileBagTest.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class FileBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFileMustBeAnArrayOrUploadedFile()
    {
        new FileBag(array('file' => 'foo'));
    }

    public function testShouldConvertsUploadedFiles()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array('file' => array(
            'name' => basename($tmpFile),
            'type' => 'text/plain',
            'tmp_name' => $tmpFile,
            'error' => 0,
            'size' => 100
        )));

        $this->assertEquals($file, $bag->get('file'));
    }

    public function testShouldSetEmptyUploadedFilesToNull()
    {
        $bag = new FileBag(array('file' => array(
            'name' => '',
            'type' => '',
            'tmp_name' => '',
            'error' => UPLOAD_ERR_NO_FILE,
            'size' => 0
        )));

        $this->assertNull($bag->get('file'));
    }

    public function testShouldConvertUploadedFilesWithPhpBug()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array(
            'child' => array(
                'name' => array(
                    'file' => basename($tmpFile),
                ),
                'type' => array(
                    'file' => 'text/plain',
                ),
                'tmp_name' => array(
                    'file' => $tmpFile,
                ),
                'error' => array(
                    'file' => 0,
                ),
                'size' => array(
                    'file' => 100,
                ),
            )
        ));

        $files = $bag->all();
        $this->assertEquals($file, $files['child']['file']);
    }

    public function testShouldConvertNestedUploadedFilesWithPhpBug()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);

        $bag = new FileBag(array(
            'child' => array(
                'name' => array(
                    'sub' => array('file' => basename($tmpFile))
                ),
                'type' => array(
                    'sub' => array('file' => 'text/plain')
                ),
                'tmp_name' => array(
                    'sub' => array('file' => $tmpFile)
                ),
                'error' => array(
                    'sub' => array('file' => 0)
                ),
                'size' => array(
                    'sub' => array('file' => 100)
                ),
            )
        ));

        $files = $bag->all();
        $this->assertEquals($file, $files['child']['sub']['file']);
    }

    public function testShouldNotConvertNestedUploadedFiles()
    {
        $tmpFile = $this->createTempFile();
        $file = new UploadedFile($tmpFile, basename($tmpFile), 'text/plain', 100, 0);
        $bag = new FileBag(array('image' => array('file' => $file)));

        $files = $bag->all();
        $this->assertEquals($file, $files['image']['file']);
    }

    protected function createTempFile()
    {
        return tempnam(sys_get_temp_dir().'/form_test', 'FormTest');
    }

    protected function setUp()
    {
        mkdir(sys_get_temp_dir().'/form_test', 0777, true);
    }

    protected function tearDown()
    {
        foreach (glob(sys_get_temp_dir().'/form_test/*') as $file) {
            unlink($file);
        }

        rmdir(sys_get_temp_dir().'/form_test');
    }
}
PK<1[�m��..GHttpFoundation/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\HeaderBag;

class HeaderBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::__construct
     */
    public function testConstructor()
    {
        $bag = new HeaderBag(array('foo' => 'bar'));
        $this->assertTrue($bag->has('foo'));
    }

    public function testToStringNull()
    {
        $bag = new HeaderBag();
        $this->assertEquals('', $bag->__toString());
    }

    public function testToStringNotNull()
    {
        $bag = new HeaderBag(array('foo' => 'bar'));
        $this->assertEquals("Foo: bar\r\n", $bag->__toString());
    }

    public function testKeys()
    {
        $bag = new HeaderBag(array('foo' => 'bar'));
        $keys = $bag->keys();
        $this->assertEquals("foo", $keys[0]);
    }

    public function testGetDate()
    {
        $bag = new HeaderBag(array('foo' => 'Tue, 4 Sep 2012 20:00:00 +0200'));
        $headerDate = $bag->getDate('foo');
        $this->assertInstanceOf('DateTime', $headerDate);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testGetDateException()
    {
        $bag = new HeaderBag(array('foo' => 'Tue'));
        $headerDate = $bag->getDate('foo');
    }

    public function testGetCacheControlHeader()
    {
        $bag = new HeaderBag();
        $bag->addCacheControlDirective('public', '#a');
        $this->assertTrue($bag->hasCacheControlDirective('public'));
        $this->assertEquals('#a', $bag->getCacheControlDirective('public'));
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::all
     */
    public function testAll()
    {
        $bag = new HeaderBag(array('foo' => 'bar'));
        $this->assertEquals(array('foo' => array('bar')), $bag->all(), '->all() gets all the input');

        $bag = new HeaderBag(array('FOO' => 'BAR'));
        $this->assertEquals(array('foo' => array('BAR')), $bag->all(), '->all() gets all the input key are lower case');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::replace
     */
    public function testReplace()
    {
        $bag = new HeaderBag(array('foo' => 'bar'));

        $bag->replace(array('NOPE' => 'BAR'));
        $this->assertEquals(array('nope' => array('BAR')), $bag->all(), '->replace() replaces the input with the argument');
        $this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::get
     */
    public function testGet()
    {
        $bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz'));
        $this->assertEquals( 'bar', $bag->get('foo'), '->get return current value');
        $this->assertEquals( 'bar', $bag->get('FoO'), '->get key in case insensitive');
        $this->assertEquals( array('bar'), $bag->get('foo', 'nope', false), '->get return the value as array');

        // defaults
        $this->assertNull($bag->get('none'), '->get unknown values returns null');
        $this->assertEquals( 'default', $bag->get('none', 'default'), '->get unknown values returns default');
        $this->assertEquals( array('default'), $bag->get('none', 'default', false), '->get unknown values returns default as array');

        $bag->set('foo', 'bor', false);
        $this->assertEquals( 'bar', $bag->get('foo'), '->get return first value');
        $this->assertEquals( array('bar', 'bor'), $bag->get('foo', 'nope', false), '->get return all values as array');
    }

    public function testSetAssociativeArray()
    {
        $bag = new HeaderBag();
        $bag->set('foo', array('bad-assoc-index' => 'value'));
        $this->assertSame('value', $bag->get('foo'));
        $this->assertEquals(array('value'), $bag->get('foo', 'nope', false), 'assoc indices of multi-valued headers are ignored');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::contains
     */
    public function testContains()
    {
        $bag = new HeaderBag(array('foo' => 'bar', 'fuzz' => 'bizz'));
        $this->assertTrue(  $bag->contains('foo', 'bar'), '->contains first value');
        $this->assertTrue(  $bag->contains('fuzz', 'bizz'), '->contains second value');
        $this->assertFalse(  $bag->contains('nope', 'nope'), '->contains unknown value');
        $this->assertFalse(  $bag->contains('foo', 'nope'), '->contains unknown value');

        // Multiple values
        $bag->set('foo', 'bor', false);
        $this->assertTrue(  $bag->contains('foo', 'bar'), '->contains first value');
        $this->assertTrue(  $bag->contains('foo', 'bor'), '->contains second value');
        $this->assertFalse(  $bag->contains('foo', 'nope'), '->contains unknown value');
    }

    public function testCacheControlDirectiveAccessors()
    {
        $bag = new HeaderBag();
        $bag->addCacheControlDirective('public');

        $this->assertTrue($bag->hasCacheControlDirective('public'));
        $this->assertTrue($bag->getCacheControlDirective('public'));
        $this->assertEquals('public', $bag->get('cache-control'));

        $bag->addCacheControlDirective('max-age', 10);
        $this->assertTrue($bag->hasCacheControlDirective('max-age'));
        $this->assertEquals(10, $bag->getCacheControlDirective('max-age'));
        $this->assertEquals('max-age=10, public', $bag->get('cache-control'));

        $bag->removeCacheControlDirective('max-age');
        $this->assertFalse($bag->hasCacheControlDirective('max-age'));
    }

    public function testCacheControlDirectiveParsing()
    {
        $bag = new HeaderBag(array('cache-control' => 'public, max-age=10'));
        $this->assertTrue($bag->hasCacheControlDirective('public'));
        $this->assertTrue($bag->getCacheControlDirective('public'));

        $this->assertTrue($bag->hasCacheControlDirective('max-age'));
        $this->assertEquals(10, $bag->getCacheControlDirective('max-age'));

        $bag->addCacheControlDirective('s-maxage', 100);
        $this->assertEquals('max-age=10, public, s-maxage=100', $bag->get('cache-control'));
    }

    public function testCacheControlDirectiveParsingQuotedZero()
    {
        $bag = new HeaderBag(array('cache-control' => 'max-age="0"'));
        $this->assertTrue($bag->hasCacheControlDirective('max-age'));
        $this->assertEquals(0, $bag->getCacheControlDirective('max-age'));
    }

    public function testCacheControlDirectiveOverrideWithReplace()
    {
        $bag = new HeaderBag(array('cache-control' => 'private, max-age=100'));
        $bag->replace(array('cache-control' => 'public, max-age=10'));
        $this->assertTrue($bag->hasCacheControlDirective('public'));
        $this->assertTrue($bag->getCacheControlDirective('public'));

        $this->assertTrue($bag->hasCacheControlDirective('max-age'));
        $this->assertEquals(10, $bag->getCacheControlDirective('max-age'));
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::getIterator
     */
    public function testGetIterator()
    {
        $headers   = array('foo' => 'bar', 'hello' => 'world', 'third' => 'charm');
        $headerBag = new HeaderBag($headers);

        $i = 0;
        foreach ($headerBag as $key => $val) {
            $i++;
            $this->assertEquals(array($headers[$key]), $val);
        }

        $this->assertEquals(count($headers), $i);
    }

    /**
     * @covers Symfony\Component\HttpFoundation\HeaderBag::count
     */
    public function testCount()
    {
        $headers   = array('foo' => 'bar', 'HELLO' => 'WORLD');
        $headerBag = new HeaderBag($headers);

        $this->assertEquals(count($headers), count($headerBag));
    }
}
PK<1[��܏##LHttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/test.gifnu�[���GIF87a�������,D;PK<1[�+�vUHttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/.unknownextensionnu�[���fPK<1[THttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/directory/.emptynu�[���PK<1[��܏##HHttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/testnu�[���GIF87a�������,D;PK<1[~rM;;THttpFoundation/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\File\MimeType;

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\MimeType\FileBinaryMimeTypeGuesser;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException;

class MimeTypeTest extends \PHPUnit_Framework_TestCase
{
    protected $path;

    public function testGuessImageWithoutExtension()
    {
        if (extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test'));
        } else {
            $this->assertNull(MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test'));
        }
    }

    public function testGuessImageWithDirectory()
    {
        $this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');

        MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/directory');
    }

    public function testGuessImageWithFileBinaryMimeTypeGuesser()
    {
        $guesser = MimeTypeGuesser::getInstance();
        $guesser->register(new FileBinaryMimeTypeGuesser());
        if (extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test'));
        } else {
            $this->assertNull(MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test'));
        }
    }

    public function testGuessImageWithKnownExtension()
    {
        if (extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test.gif'));
        } else {
            $this->assertNull(MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/test.gif'));
        }
    }

    public function testGuessFileWithUnknownExtension()
    {
        if (extension_loaded('fileinfo')) {
            $this->assertEquals('application/octet-stream', MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/.unknownextension'));
        } else {
            $this->assertNull(MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/.unknownextension'));
        }
    }

    public function testGuessWithIncorrectPath()
    {
        $this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');
        MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/not_here');
    }

    public function testGuessWithNonReadablePath()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('Can not verify chmod operations on Windows');
        }

        if (in_array(get_current_user(), array('root'))) {
            $this->markTestSkipped('This test will fail if run under superuser');
        }

        $path = __DIR__.'/../Fixtures/to_delete';
        touch($path);
        @chmod($path, 0333);

        if (get_current_user() != 'root' && substr(sprintf('%o', fileperms($path)), -4) == '0333') {
            $this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException');
            MimeTypeGuesser::getInstance()->guess($path);
        } else {
            $this->markTestSkipped('Can not verify chmod operations, change of file permissions failed');
        }
    }

    public static function tearDownAfterClass()
    {
        $path = __DIR__.'/../Fixtures/to_delete';
        if (file_exists($path)) {
            @chmod($path, 0666);
            @unlink($path);
        }
    }
}
PK<1[��##GHttpFoundation/Symfony/Component/HttpFoundation/Tests/File/FileTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\File;

use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;

class FileTest extends \PHPUnit_Framework_TestCase
{
    protected $file;

    public function testGetMimeTypeUsesMimeTypeGuessers()
    {
        $file = new File(__DIR__.'/Fixtures/test.gif');
        $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');

        MimeTypeGuesser::getInstance()->register($guesser);

        $this->assertEquals('image/gif', $file->getMimeType());
    }

    public function testGuessExtensionWithoutGuesser()
    {
        $file = new File(__DIR__.'/Fixtures/directory/.empty');

        $this->assertNull($file->guessExtension());
    }

    public function testGuessExtensionIsBasedOnMimeType()
    {
        $file = new File(__DIR__.'/Fixtures/test');
        $guesser = $this->createMockGuesser($file->getPathname(), 'image/gif');

        MimeTypeGuesser::getInstance()->register($guesser);

        $this->assertEquals('gif', $file->guessExtension());
    }

    public function testConstructWhenFileNotExists()
    {
        $this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');

        new File(__DIR__.'/Fixtures/not_here');
    }

    public function testMove()
    {
        $path = __DIR__.'/Fixtures/test.copy.gif';
        $targetDir = __DIR__.'/Fixtures/directory';
        $targetPath = $targetDir.'/test.copy.gif';
        @unlink($path);
        @unlink($targetPath);
        copy(__DIR__.'/Fixtures/test.gif', $path);

        $file = new File($path);
        $movedFile = $file->move($targetDir);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $movedFile);

        $this->assertTrue(file_exists($targetPath));
        $this->assertFalse(file_exists($path));
        $this->assertEquals(realpath($targetPath), $movedFile->getRealPath());

        @unlink($targetPath);
    }

    public function testMoveWithNewName()
    {
        $path = __DIR__.'/Fixtures/test.copy.gif';
        $targetDir = __DIR__.'/Fixtures/directory';
        $targetPath = $targetDir.'/test.newname.gif';
        @unlink($path);
        @unlink($targetPath);
        copy(__DIR__.'/Fixtures/test.gif', $path);

        $file = new File($path);
        $movedFile = $file->move($targetDir, 'test.newname.gif');

        $this->assertTrue(file_exists($targetPath));
        $this->assertFalse(file_exists($path));
        $this->assertEquals(realpath($targetPath), $movedFile->getRealPath());

        @unlink($targetPath);
    }

    public function getFilenameFixtures()
    {
        return array(
            array('original.gif', 'original.gif'),
            array('..\\..\\original.gif', 'original.gif'),
            array('../../original.gif', 'original.gif'),
            array('файлfile.gif', 'файлfile.gif'),
            array('..\\..\\файлfile.gif', 'файлfile.gif'),
            array('../../файлfile.gif', 'файлfile.gif'),
        );
    }

    /**
     * @dataProvider getFilenameFixtures
     */
    public function testMoveWithNonLatinName($filename, $sanitizedFilename)
    {
        $path = __DIR__.'/Fixtures/'.$sanitizedFilename;
        $targetDir = __DIR__.'/Fixtures/directory/';
        $targetPath = $targetDir.$sanitizedFilename;
        @unlink($path);
        @unlink($targetPath);
        copy(__DIR__.'/Fixtures/test.gif', $path);

        $file = new File($path);
        $movedFile = $file->move($targetDir,$filename);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $movedFile);

        $this->assertTrue(file_exists($targetPath));
        $this->assertFalse(file_exists($path));
        $this->assertEquals(realpath($targetPath), $movedFile->getRealPath());

        @unlink($targetPath);
    }

    public function testMoveToAnUnexistentDirectory()
    {
        $sourcePath = __DIR__.'/Fixtures/test.copy.gif';
        $targetDir = __DIR__.'/Fixtures/directory/sub';
        $targetPath = $targetDir.'/test.copy.gif';
        @unlink($sourcePath);
        @unlink($targetPath);
        @rmdir($targetDir);
        copy(__DIR__.'/Fixtures/test.gif', $sourcePath);

        $file = new File($sourcePath);
        $movedFile = $file->move($targetDir);

        $this->assertFileExists($targetPath);
        $this->assertFileNotExists($sourcePath);
        $this->assertEquals(realpath($targetPath), $movedFile->getRealPath());

        @unlink($sourcePath);
        @unlink($targetPath);
        @rmdir($targetDir);
    }

    public function testGetExtension()
    {
        $file = new File(__DIR__.'/Fixtures/test.gif');
        $this->assertEquals('gif', $file->getExtension());
    }

    protected function createMockGuesser($path, $mimeType)
    {
        $guesser = $this->getMock('Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface');
        $guesser
            ->expects($this->once())
            ->method('guess')
            ->with($this->equalTo($path))
            ->will($this->returnValue($mimeType))
        ;

        return $guesser;
    }
}
PK<1[��t�AAOHttpFoundation/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\File;

use Symfony\Component\HttpFoundation\File\UploadedFile;

class UploadedFileTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!ini_get('file_uploads')) {
            $this->markTestSkipped('file_uploads is disabled in php.ini');
        }
    }

    public function testConstructWhenFileNotExists()
    {
        $this->setExpectedException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException');

        new UploadedFile(
            __DIR__.'/Fixtures/not_here',
            'original.gif',
            null
        );
    }

    public function testFileUploadsWithNoMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null,
            filesize(__DIR__.'/Fixtures/test.gif'),
            UPLOAD_ERR_OK
        );

        $this->assertEquals('application/octet-stream', $file->getClientMimeType());

        if (extension_loaded('fileinfo')) {
            $this->assertEquals('image/gif', $file->getMimeType());
        }
    }

    public function testFileUploadsWithUnknownMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/.unknownextension',
            'original.gif',
            null,
            filesize(__DIR__.'/Fixtures/.unknownextension'),
            UPLOAD_ERR_OK
        );

        $this->assertEquals('application/octet-stream', $file->getClientMimeType());
    }

    public function testGuessClientExtension()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals('gif', $file->guessClientExtension());
    }

    public function testGuessClientExtensionWithIncorrectMimeType()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/jpeg',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals('jpeg', $file->guessClientExtension());
    }

    public function testErrorIsOkByDefault()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals(UPLOAD_ERR_OK, $file->getError());
    }

    public function testGetClientOriginalName()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals('original.gif', $file->getClientOriginalName());
    }

    public function testGetClientOriginalExtension()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals('gif', $file->getClientOriginalExtension());
    }

    /**
     * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileException
     */
    public function testMoveLocalFileIsNotAllowed()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            UPLOAD_ERR_OK
        );

        $movedFile = $file->move(__DIR__.'/Fixtures/directory');
    }

    public function testMoveLocalFileIsAllowedInTestMode()
    {
        $path = __DIR__.'/Fixtures/test.copy.gif';
        $targetDir = __DIR__.'/Fixtures/directory';
        $targetPath = $targetDir.'/test.copy.gif';
        @unlink($path);
        @unlink($targetPath);
        copy(__DIR__.'/Fixtures/test.gif', $path);

        $file = new UploadedFile(
            $path,
            'original.gif',
            'image/gif',
            filesize($path),
            UPLOAD_ERR_OK,
            true
        );

        $movedFile = $file->move(__DIR__.'/Fixtures/directory');

        $this->assertTrue(file_exists($targetPath));
        $this->assertFalse(file_exists($path));
        $this->assertEquals(realpath($targetPath), $movedFile->getRealPath());

        @unlink($targetPath);
    }

    public function testGetClientOriginalNameSanitizeFilename()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            '../../original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals('original.gif', $file->getClientOriginalName());
    }

    public function testGetSize()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            'image/gif',
            filesize(__DIR__.'/Fixtures/test.gif'),
            null
        );

        $this->assertEquals(filesize(__DIR__.'/Fixtures/test.gif'), $file->getSize());

        $file = new UploadedFile(
            __DIR__.'/Fixtures/test',
            'original.gif',
            'image/gif'
        );

        $this->assertEquals(filesize(__DIR__.'/Fixtures/test'), $file->getSize());
    }

    public function testGetExtension()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null
        );

        $this->assertEquals('gif', $file->getExtension());
    }

    public function testIsValid()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null,
            filesize(__DIR__.'/Fixtures/test.gif'),
            UPLOAD_ERR_OK,
            true
        );

        $this->assertTrue($file->isValid());
    }

    /**
     * @dataProvider uploadedFileErrorProvider
     */
    public function testIsInvalidOnUploadError($error)
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null,
            filesize(__DIR__.'/Fixtures/test.gif'),
            $error
        );

        $this->assertFalse($file->isValid());
    }

    public function uploadedFileErrorProvider()
    {
        return array(
            array(UPLOAD_ERR_INI_SIZE),
            array(UPLOAD_ERR_FORM_SIZE),
            array(UPLOAD_ERR_PARTIAL),
            array(UPLOAD_ERR_NO_TMP_DIR),
            array(UPLOAD_ERR_EXTENSION),
        );
    }

    public function testIsInvalidIfNotHttpUpload()
    {
        $file = new UploadedFile(
            __DIR__.'/Fixtures/test.gif',
            'original.gif',
            null,
            filesize(__DIR__.'/Fixtures/test.gif'),
            UPLOAD_ERR_OK
        );

        $this->assertFalse($file->isValid());
    }
}
PK<1[�ʾV�
�
NHttpFoundation/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class StreamedResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $response = new StreamedResponse(function () { echo 'foo'; }, 404, array('Content-Type' => 'text/plain'));

        $this->assertEquals(404, $response->getStatusCode());
        $this->assertEquals('text/plain', $response->headers->get('Content-Type'));
    }

    public function testPrepareWith11Protocol()
    {
        $response = new StreamedResponse(function () { echo 'foo'; });
        $request = Request::create('/');
        $request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');

        $response->prepare($request);

        $this->assertEquals('1.1', $response->getProtocolVersion());
        $this->assertNotEquals('chunked', $response->headers->get('Transfer-Encoding'), 'Apache assumes responses with a Transfer-Encoding header set to chunked to already be encoded.');
        $this->assertEquals('no-cache, private', $response->headers->get('Cache-Control'));
    }

    public function testPrepareWith10Protocol()
    {
        $response = new StreamedResponse(function () { echo 'foo'; });
        $request = Request::create('/');
        $request->server->set('SERVER_PROTOCOL', 'HTTP/1.0');

        $response->prepare($request);

        $this->assertEquals('1.0', $response->getProtocolVersion());
        $this->assertNull($response->headers->get('Transfer-Encoding'));
        $this->assertEquals('no-cache, private', $response->headers->get('Cache-Control'));
    }

    public function testPrepareWithHeadRequest()
    {
        $response = new StreamedResponse(function () { echo 'foo'; });
        $request = Request::create('/', 'HEAD');

        $response->prepare($request);
    }

    public function testSendContent()
    {
        $called = 0;

        $response = new StreamedResponse(function () use (&$called) { ++$called; });

        $response->sendContent();
        $this->assertEquals(1, $called);

        $response->sendContent();
        $this->assertEquals(1, $called);
    }

    /**
     * @expectedException \LogicException
     */
    public function testSendContentWithNonCallable()
    {
        $response = new StreamedResponse(null);
        $response->sendContent();
    }

    /**
     * @expectedException \LogicException
     */
    public function testSetCallbackNonCallable()
    {
        $response = new StreamedResponse(null);
        $response->setCallback(null);
    }

    /**
     * @expectedException \LogicException
     */
    public function testSetContent()
    {
        $response = new StreamedResponse(function () { echo 'foo'; });
        $response->setContent('foo');
    }

    public function testGetContent()
    {
        $response = new StreamedResponse(function () { echo 'foo'; });
        $this->assertFalse($response->getContent());
    }

    public function testCreate()
    {
        $response = StreamedResponse::create(function () {}, 204);

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $response);
        $this->assertEquals(204, $response->getStatusCode());
    }
}
PK<1[M�{��^HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Flash/AutoExpireFlashBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Flash;

use Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag as FlashBag;

/**
 * AutoExpireFlashBagTest
 *
 * @author Drak <drak@zikula.org>
 */
class AutoExpireFlashBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\HttpFoundation\Session\Flash\AutoExpireFlashBag
     */
    private $bag;

    /**
     * @var array
     */
    protected $array = array();

    protected function setUp()
    {
        parent::setUp();
        $this->bag = new FlashBag();
        $this->array = array('new' => array('notice' => array('A previous flash message')));
        $this->bag->initialize($this->array);
    }

    public function tearDown()
    {
        $this->bag = null;
        parent::tearDown();
    }

    public function testInitialize()
    {
        $bag = new FlashBag();
        $array = array('new' => array('notice' => array('A previous flash message')));
        $bag->initialize($array);
        $this->assertEquals(array('A previous flash message'), $bag->peek('notice'));
        $array = array('new' => array(
                'notice' => array('Something else'),
                'error' => array('a'),
            ));
        $bag->initialize($array);
        $this->assertEquals(array('Something else'), $bag->peek('notice'));
        $this->assertEquals(array('a'), $bag->peek('error'));
    }

    public function testGetStorageKey()
    {
        $this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
        $attributeBag = new FlashBag('test');
        $this->assertEquals('test', $attributeBag->getStorageKey());
    }

    public function testGetSetName()
    {
        $this->assertEquals('flashes', $this->bag->getName());
        $this->bag->setName('foo');
        $this->assertEquals('foo', $this->bag->getName());
    }

    public function testPeek()
    {
        $this->assertEquals(array(), $this->bag->peek('non_existing'));
        $this->assertEquals(array('default'), $this->bag->peek('non_existing', array('default')));
        $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
        $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
    }

    public function testSet()
    {
        $this->bag->set('notice', 'Foo');
        $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
    }

    public function testHas()
    {
        $this->assertFalse($this->bag->has('nothing'));
        $this->assertTrue($this->bag->has('notice'));
    }

    public function testKeys()
    {
        $this->assertEquals(array('notice'), $this->bag->keys());
    }

    public function testPeekAll()
    {
        $array = array(
            'new' => array(
                'notice' => 'Foo',
                'error' => 'Bar',
            ),
        );

        $this->bag->initialize($array);
        $this->assertEquals(array(
            'notice' => 'Foo',
            'error' => 'Bar',
            ), $this->bag->peekAll()
        );

        $this->assertEquals(array(
            'notice' => 'Foo',
            'error' => 'Bar',
            ), $this->bag->peekAll()
        );
    }

    public function testGet()
    {
        $this->assertEquals(array(), $this->bag->get('non_existing'));
        $this->assertEquals(array('default'), $this->bag->get('non_existing', array('default')));
        $this->assertEquals(array('A previous flash message'), $this->bag->get('notice'));
        $this->assertEquals(array(), $this->bag->get('notice'));
    }

    public function testSetAll()
    {
        $this->bag->setAll(array('a' => 'first', 'b' => 'second'));
        $this->assertFalse($this->bag->has('a'));
        $this->assertFalse($this->bag->has('b'));
    }

    public function testAll()
    {
        $this->bag->set('notice', 'Foo');
        $this->bag->set('error', 'Bar');
        $this->assertEquals(array(
            'notice' => array('A previous flash message'),
            ), $this->bag->all()
        );

        $this->assertEquals(array(), $this->bag->all());
    }

    public function testClear()
    {
        $this->assertEquals(array('notice' => array('A previous flash message')), $this->bag->clear());
    }
}
PK<1[��ƒ��THttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Flash/FlashBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Flash;

use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;

/**
 * FlashBagTest
 *
 * @author Drak <drak@zikula.org>
 */
class FlashBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\HttpFoundation\SessionFlash\FlashBagInterface
     */
    private $bag;

    /**
     * @var array
     */
    protected $array = array();

    protected function setUp()
    {
        parent::setUp();
        $this->bag = new FlashBag();
        $this->array = array('notice' => array('A previous flash message'));
        $this->bag->initialize($this->array);
    }

    public function tearDown()
    {
        $this->bag = null;
        parent::tearDown();
    }

    public function testInitialize()
    {
        $bag = new FlashBag();
        $bag->initialize($this->array);
        $this->assertEquals($this->array, $bag->peekAll());
        $array = array('should' => array('change'));
        $bag->initialize($array);
        $this->assertEquals($array, $bag->peekAll());
    }

    public function testGetStorageKey()
    {
        $this->assertEquals('_sf2_flashes', $this->bag->getStorageKey());
        $attributeBag = new FlashBag('test');
        $this->assertEquals('test', $attributeBag->getStorageKey());
    }

    public function testGetSetName()
    {
        $this->assertEquals('flashes', $this->bag->getName());
        $this->bag->setName('foo');
        $this->assertEquals('foo', $this->bag->getName());
    }

    public function testPeek()
    {
        $this->assertEquals(array(), $this->bag->peek('non_existing'));
        $this->assertEquals(array('default'), $this->bag->peek('not_existing', array('default')));
        $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
        $this->assertEquals(array('A previous flash message'), $this->bag->peek('notice'));
    }

    public function testGet()
    {
        $this->assertEquals(array(), $this->bag->get('non_existing'));
        $this->assertEquals(array('default'), $this->bag->get('not_existing', array('default')));
        $this->assertEquals(array('A previous flash message'), $this->bag->get('notice'));
        $this->assertEquals(array(), $this->bag->get('notice'));
    }

    public function testAll()
    {
        $this->bag->set('notice', 'Foo');
        $this->bag->set('error', 'Bar');
        $this->assertEquals(array(
            'notice' => array('Foo'),
            'error' => array('Bar')), $this->bag->all()
        );

        $this->assertEquals(array(), $this->bag->all());
    }

    public function testSet()
    {
        $this->bag->set('notice', 'Foo');
        $this->bag->set('notice', 'Bar');
        $this->assertEquals(array('Bar'), $this->bag->peek('notice'));
    }

    public function testHas()
    {
        $this->assertFalse($this->bag->has('nothing'));
        $this->assertTrue($this->bag->has('notice'));
    }

    public function testKeys()
    {
        $this->assertEquals(array('notice'), $this->bag->keys());
    }

    public function testPeekAll()
    {
        $this->bag->set('notice', 'Foo');
        $this->bag->set('error', 'Bar');
        $this->assertEquals(array(
            'notice' => array('Foo'),
            'error' => array('Bar'),
            ), $this->bag->peekAll()
        );
        $this->assertTrue($this->bag->has('notice'));
        $this->assertTrue($this->bag->has('error'));
        $this->assertEquals(array(
            'notice' => array('Foo'),
            'error' => array('Bar'),
            ), $this->bag->peekAll()
        );
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Session\Flash\FlashBag::getIterator
     */
    public function testGetIterator()
    {
        $flashes = array('hello' => 'world', 'beep' => 'boop', 'notice' => 'nope');
        foreach ($flashes as $key => $val) {
            $this->bag->set($key, $val);
        }

        $i = 0;
        foreach ($this->bag as $key => $val) {
            $this->assertEquals(array($flashes[$key]), $val);
            $i++;
        }

        $this->assertEquals(count($flashes), $i);
        $this->assertCount(0, $this->bag->all());
    }
}
PK=1[0�����\HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute;

use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;

/**
 * Tests AttributeBag
 *
 * @author Drak <drak@zikula.org>
 */
class AttributeBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    private $array;

    /**
     * @var AttributeBag
     */
    private $bag;

    protected function setUp()
    {
        $this->array = array(
            'hello' => 'world',
            'always' => 'be happy',
            'user.login' => 'drak',
            'csrf.token' => array(
                'a' => '1234',
                'b' => '4321',
            ),
            'category' => array(
                'fishing' => array(
                    'first' => 'cod',
                    'second' => 'sole')
                ),
        );
        $this->bag = new AttributeBag('_sf2');
        $this->bag->initialize($this->array);
    }

    protected function tearDown()
    {
        $this->bag = null;
        $this->array = array();
    }

    public function testInitialize()
    {
        $bag = new AttributeBag();
        $bag->initialize($this->array);
        $this->assertEquals($this->array, $bag->all());
        $array = array('should' => 'change');
        $bag->initialize($array);
        $this->assertEquals($array, $bag->all());
    }

    public function testGetStorageKey()
    {
        $this->assertEquals('_sf2', $this->bag->getStorageKey());
        $attributeBag = new AttributeBag('test');
        $this->assertEquals('test', $attributeBag->getStorageKey());
    }

    public function testGetSetName()
    {
        $this->assertEquals('attributes', $this->bag->getName());
        $this->bag->setName('foo');
        $this->assertEquals('foo', $this->bag->getName());
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testHas($key, $value, $exists)
    {
        $this->assertEquals($exists, $this->bag->has($key));
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testGet($key, $value, $expected)
    {
        $this->assertEquals($value, $this->bag->get($key));
    }

    public function testGetDefaults()
    {
        $this->assertNull($this->bag->get('user2.login'));
        $this->assertEquals('default', $this->bag->get('user2.login', 'default'));
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testSet($key, $value, $expected)
    {
        $this->bag->set($key, $value);
        $this->assertEquals($value, $this->bag->get($key));
    }

    public function testAll()
    {
        $this->assertEquals($this->array, $this->bag->all());

        $this->bag->set('hello', 'fabien');
        $array = $this->array;
        $array['hello'] = 'fabien';
        $this->assertEquals($array, $this->bag->all());
    }

    public function testReplace()
    {
        $array = array();
        $array['name'] = 'jack';
        $array['foo.bar'] = 'beep';
        $this->bag->replace($array);
        $this->assertEquals($array, $this->bag->all());
        $this->assertNull($this->bag->get('hello'));
        $this->assertNull($this->bag->get('always'));
        $this->assertNull($this->bag->get('user.login'));
    }

    public function testRemove()
    {
        $this->assertEquals('world', $this->bag->get('hello'));
        $this->bag->remove('hello');
        $this->assertNull($this->bag->get('hello'));

        $this->assertEquals('be happy', $this->bag->get('always'));
        $this->bag->remove('always');
        $this->assertNull($this->bag->get('always'));

        $this->assertEquals('drak', $this->bag->get('user.login'));
        $this->bag->remove('user.login');
        $this->assertNull($this->bag->get('user.login'));
    }

    public function testClear()
    {
        $this->bag->clear();
        $this->assertEquals(array(), $this->bag->all());
    }

    public function attributesProvider()
    {
        return array(
            array('hello', 'world', true),
            array('always', 'be happy', true),
            array('user.login', 'drak', true),
            array('csrf.token', array('a' => '1234', 'b' => '4321'), true),
            array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true),
            array('user2.login', null, false),
            array('never', null, false),
            array('bye', null, false),
            array('bye/for/now', null, false),
        );
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::getIterator
     */
    public function testGetIterator()
    {
        $i = 0;
        foreach ($this->bag as $key => $val) {
            $this->assertEquals($this->array[$key], $val);
            $i++;
        }

        $this->assertEquals(count($this->array), $i);
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag::count
     */
    public function testCount()
    {
        $this->assertEquals(count($this->array), count($this->bag));
    }
}
PK=1[)��fHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Attribute/NamespacedAttributeBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Attribute;

use Symfony\Component\HttpFoundation\Session\Attribute\NamespacedAttributeBag;

/**
 * Tests NamespacedAttributeBag
 *
 * @author Drak <drak@zikula.org>
 */
class NamespacedAttributeBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    private $array;

    /**
     * @var NamespacedAttributeBag
     */
    private $bag;

    protected function setUp()
    {
        $this->array = array(
            'hello' => 'world',
            'always' => 'be happy',
            'user.login' => 'drak',
            'csrf.token' => array(
                'a' => '1234',
                'b' => '4321',
            ),
            'category' => array(
                'fishing' => array(
                    'first' => 'cod',
                    'second' => 'sole')
                ),
        );
        $this->bag = new NamespacedAttributeBag('_sf2', '/');
        $this->bag->initialize($this->array);
    }

    protected function tearDown()
    {
        $this->bag = null;
        $this->array = array();
    }

    public function testInitialize()
    {
        $bag = new NamespacedAttributeBag();
        $bag->initialize($this->array);
        $this->assertEquals($this->array, $this->bag->all());
        $array = array('should' => 'not stick');
        $bag->initialize($array);

        // should have remained the same
        $this->assertEquals($this->array, $this->bag->all());
    }

    public function testGetStorageKey()
    {
        $this->assertEquals('_sf2', $this->bag->getStorageKey());
        $attributeBag = new NamespacedAttributeBag('test');
        $this->assertEquals('test', $attributeBag->getStorageKey());
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testHas($key, $value, $exists)
    {
        $this->assertEquals($exists, $this->bag->has($key));
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testGet($key, $value, $expected)
    {
        $this->assertEquals($value, $this->bag->get($key));
    }

    public function testGetDefaults()
    {
        $this->assertNull($this->bag->get('user2.login'));
        $this->assertEquals('default', $this->bag->get('user2.login', 'default'));
    }

    /**
     * @dataProvider attributesProvider
     */
    public function testSet($key, $value, $expected)
    {
        $this->bag->set($key, $value);
        $this->assertEquals($value, $this->bag->get($key));
    }

    public function testAll()
    {
        $this->assertEquals($this->array, $this->bag->all());

        $this->bag->set('hello', 'fabien');
        $array = $this->array;
        $array['hello'] = 'fabien';
        $this->assertEquals($array, $this->bag->all());
    }

    public function testReplace()
    {
        $array = array();
        $array['name'] = 'jack';
        $array['foo.bar'] = 'beep';
        $this->bag->replace($array);
        $this->assertEquals($array, $this->bag->all());
        $this->assertNull($this->bag->get('hello'));
        $this->assertNull($this->bag->get('always'));
        $this->assertNull($this->bag->get('user.login'));
    }

    public function testRemove()
    {
        $this->assertEquals('world', $this->bag->get('hello'));
        $this->bag->remove('hello');
        $this->assertNull($this->bag->get('hello'));

        $this->assertEquals('be happy', $this->bag->get('always'));
        $this->bag->remove('always');
        $this->assertNull($this->bag->get('always'));

        $this->assertEquals('drak', $this->bag->get('user.login'));
        $this->bag->remove('user.login');
        $this->assertNull($this->bag->get('user.login'));
    }

    public function testRemoveExistingNamespacedAttribute()
    {
        $this->assertSame('cod', $this->bag->remove('category/fishing/first'));
    }

    public function testRemoveNonexistingNamespacedAttribute()
    {
        $this->assertNull($this->bag->remove('foo/bar/baz'));
    }

    public function testClear()
    {
        $this->bag->clear();
        $this->assertEquals(array(), $this->bag->all());
    }

    public function attributesProvider()
    {
        return array(
            array('hello', 'world', true),
            array('always', 'be happy', true),
            array('user.login', 'drak', true),
            array('csrf.token', array('a' => '1234', 'b' => '4321'), true),
            array('csrf.token/a', '1234', true),
            array('csrf.token/b', '4321', true),
            array('category', array('fishing' => array('first' => 'cod', 'second' => 'sole')), true),
            array('category/fishing', array('first' => 'cod', 'second' => 'sole'), true),
            array('category/fishing/missing/first', null, false),
            array('category/fishing/first', 'cod', true),
            array('category/fishing/second', 'sole', true),
            array('category/fishing/missing/second', null, false),
            array('user2.login', null, false),
            array('never', null, false),
            array('bye', null, false),
            array('bye/for/now', null, false),
        );
    }
}
PK=1[��ppMHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session;

use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;

/**
 * SessionTest
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Robert Schönthal <seroscho@googlemail.com>
 * @author Drak <drak@zikula.org>
 */
class SessionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface
     */
    protected $storage;

    /**
     * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
     */
    protected $session;

    protected function setUp()
    {
        $this->storage = new MockArraySessionStorage();
        $this->session = new Session($this->storage, new AttributeBag(), new FlashBag());
    }

    protected function tearDown()
    {
        $this->storage = null;
        $this->session = null;
    }

    public function testStart()
    {
        $this->assertEquals('', $this->session->getId());
        $this->assertTrue($this->session->start());
        $this->assertNotEquals('', $this->session->getId());
    }

    public function testIsStarted()
    {
        $this->assertFalse($this->session->isStarted());
        $this->session->start();
        $this->assertTrue($this->session->isStarted());
    }

    public function testSetId()
    {
        $this->assertEquals('', $this->session->getId());
        $this->session->setId('0123456789abcdef');
        $this->session->start();
        $this->assertEquals('0123456789abcdef', $this->session->getId());
    }

    public function testSetName()
    {
        $this->assertEquals('MOCKSESSID', $this->session->getName());
        $this->session->setName('session.test.com');
        $this->session->start();
        $this->assertEquals('session.test.com', $this->session->getName());
    }

    public function testGet()
    {
        // tests defaults
        $this->assertNull($this->session->get('foo'));
        $this->assertEquals(1, $this->session->get('foo', 1));
    }

    /**
     * @dataProvider setProvider
     */
    public function testSet($key, $value)
    {
        $this->session->set($key, $value);
        $this->assertEquals($value, $this->session->get($key));
    }

    /**
     * @dataProvider setProvider
     */
    public function testHas($key, $value)
    {
        $this->session->set($key, $value);
        $this->assertTrue($this->session->has($key));
        $this->assertFalse($this->session->has($key.'non_value'));
    }

    public function testReplace()
    {
        $this->session->replace(array('happiness' => 'be good', 'symfony' => 'awesome'));
        $this->assertEquals(array('happiness' => 'be good', 'symfony' => 'awesome'), $this->session->all());
        $this->session->replace(array());
        $this->assertEquals(array(), $this->session->all());
    }

    /**
     * @dataProvider setProvider
     */
    public function testAll($key, $value, $result)
    {
        $this->session->set($key, $value);
        $this->assertEquals($result, $this->session->all());
    }

    /**
     * @dataProvider setProvider
     */
    public function testClear($key, $value)
    {
        $this->session->set('hi', 'fabien');
        $this->session->set($key, $value);
        $this->session->clear();
        $this->assertEquals(array(), $this->session->all());
    }

    public function setProvider()
    {
        return array(
            array('foo', 'bar', array('foo' => 'bar')),
            array('foo.bar', 'too much beer', array('foo.bar' => 'too much beer')),
            array('great', 'symfony2 is great', array('great' => 'symfony2 is great')),
        );
    }

    /**
     * @dataProvider setProvider
     */
    public function testRemove($key, $value)
    {
        $this->session->set('hi.world', 'have a nice day');
        $this->session->set($key, $value);
        $this->session->remove($key);
        $this->assertEquals(array('hi.world' => 'have a nice day'), $this->session->all());
    }

    public function testInvalidate()
    {
        $this->session->set('invalidate', 123);
        $this->session->invalidate();
        $this->assertEquals(array(), $this->session->all());
    }

    public function testMigrate()
    {
        $this->session->set('migrate', 321);
        $this->session->migrate();
        $this->assertEquals(321, $this->session->get('migrate'));
    }

    public function testMigrateDestroy()
    {
        $this->session->set('migrate', 333);
        $this->session->migrate(true);
        $this->assertEquals(333, $this->session->get('migrate'));
    }

    public function testSave()
    {
        $this->session->start();
        $this->session->save();
    }

    public function testGetId()
    {
        $this->assertEquals('', $this->session->getId());
        $this->session->start();
        $this->assertNotEquals('', $this->session->getId());
    }

    public function testGetFlashBag()
    {
        $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Session\\Flash\\FlashBagInterface', $this->session->getFlashBag());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Session\Session::getIterator
     */
    public function testGetIterator()
    {
        $attributes = array('hello' => 'world', 'symfony2' => 'rocks');
        foreach ($attributes as $key => $val) {
            $this->session->set($key, $val);
        }

        $i = 0;
        foreach ($this->session as $key => $val) {
            $this->assertEquals($attributes[$key], $val);
            $i++;
        }

        $this->assertEquals(count($attributes), $i);
    }

    /**
     * @covers \Symfony\Component\HttpFoundation\Session\Session::count
     */
    public function testGetCount()
    {
        $this->session->set('hello', 'world');
        $this->session->set('symfony2', 'rocks');

        $this->assertCount(2, $this->session);
    }

    public function testGetMeta()
    {
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\MetadataBag', $this->session->getMetadataBag());
    }
}
PK=1[>��*dHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;

use Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;

/**
 * Test class for MockFileSessionStorage.
 *
 * @author Drak <drak@zikula.org>
 */
class MockFileSessionStorageTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string
     */
    private $sessionDir;

    /**
     * @var FileMockSessionStorage
     */
    protected $storage;

    protected function setUp()
    {
        $this->sessionDir = sys_get_temp_dir().'/sf2test';
        $this->storage = $this->getStorage();
    }

    protected function tearDown()
    {
        $this->sessionDir = null;
        $this->storage = null;
        array_map('unlink', glob($this->sessionDir.'/*.session'));
        if (is_dir($this->sessionDir)) {
            rmdir($this->sessionDir);
        }
    }

    public function testStart()
    {
        $this->assertEquals('', $this->storage->getId());
        $this->assertTrue($this->storage->start());
        $id = $this->storage->getId();
        $this->assertNotEquals('', $this->storage->getId());
        $this->assertTrue($this->storage->start());
        $this->assertEquals($id, $this->storage->getId());
    }

    public function testRegenerate()
    {
        $this->storage->start();
        $this->storage->getBag('attributes')->set('regenerate', 1234);
        $this->storage->regenerate();
        $this->assertEquals(1234, $this->storage->getBag('attributes')->get('regenerate'));
        $this->storage->regenerate(true);
        $this->assertEquals(1234, $this->storage->getBag('attributes')->get('regenerate'));
    }

    public function testGetId()
    {
        $this->assertEquals('', $this->storage->getId());
        $this->storage->start();
        $this->assertNotEquals('', $this->storage->getId());
    }

    public function testSave()
    {
        $this->storage->start();
        $id = $this->storage->getId();
        $this->assertNotEquals('108', $this->storage->getBag('attributes')->get('new'));
        $this->assertFalse($this->storage->getBag('flashes')->has('newkey'));
        $this->storage->getBag('attributes')->set('new', '108');
        $this->storage->getBag('flashes')->set('newkey', 'test');
        $this->storage->save();

        $storage = $this->getStorage();
        $storage->setId($id);
        $storage->start();
        $this->assertEquals('108', $storage->getBag('attributes')->get('new'));
        $this->assertTrue($storage->getBag('flashes')->has('newkey'));
        $this->assertEquals(array('test'), $storage->getBag('flashes')->peek('newkey'));
    }

    public function testMultipleInstances()
    {
        $storage1 = $this->getStorage();
        $storage1->start();
        $storage1->getBag('attributes')->set('foo', 'bar');
        $storage1->save();

        $storage2 = $this->getStorage();
        $storage2->setId($storage1->getId());
        $storage2->start();
        $this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances');
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testSaveWithoutStart()
    {
        $storage1 = $this->getStorage();
        $storage1->save();
    }

    private function getStorage()
    {
        $storage = new MockFileSessionStorage($this->sessionDir);
        $storage->registerBag(new FlashBag());
        $storage->registerBag(new AttributeBag());

        return $storage;
    }
}
PK=1[5�h���jHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;

/**
 * Test class for NativeSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 *
 * @runTestsInSeparateProcesses
 */
class NativeSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $handler = new NativeSessionHandler();

        // note for PHPUnit optimisers - the use of assertTrue/False
        // here is deliberate since the tests do not require the classes to exist - drak
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->assertFalse($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        } else {
            $this->assertTrue($handler instanceof \SessionHandler);
            $this->assertTrue($handler instanceof NativeSessionHandler);
        }
    }
}
PK=1[1�Mf
f
lHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;

class MemcacheSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    const PREFIX = 'prefix_';
    const TTL = 1000;
    /**
     * @var MemcacheSessionHandler
     */
    protected $storage;

    protected $memcache;

    protected function setUp()
    {
        if (!class_exists('Memcache')) {
            $this->markTestSkipped('Skipped tests Memcache class is not present');
        }

        $this->memcache = $this->getMock('Memcache');
        $this->storage = new MemcacheSessionHandler(
            $this->memcache,
            array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
        );
    }

    protected function tearDown()
    {
        $this->memcache = null;
        $this->storage = null;
    }

    public function testOpenSession()
    {
        $this->assertTrue($this->storage->open('', ''));
    }

    public function testCloseSession()
    {
        $this->memcache
            ->expects($this->once())
            ->method('close')
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($this->storage->close());
    }

    public function testReadSession()
    {
        $this->memcache
            ->expects($this->once())
            ->method('get')
            ->with(self::PREFIX.'id')
        ;

        $this->assertEquals('', $this->storage->read('id'));
    }

    public function testWriteSession()
    {
        $this->memcache
            ->expects($this->once())
            ->method('set')
            ->with(self::PREFIX.'id', 'data', 0, $this->equalTo(time() + self::TTL, 2))
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($this->storage->write('id', 'data'));
    }

    public function testDestroySession()
    {
        $this->memcache
            ->expects($this->once())
            ->method('delete')
            ->with(self::PREFIX.'id')
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($this->storage->destroy('id'));
    }

    public function testGcSession()
    {
        $this->assertTrue($this->storage->gc(123));
    }

    /**
     * @dataProvider getOptionFixtures
     */
    public function testSupportedOptions($options, $supported)
    {
        try {
            new MemcacheSessionHandler($this->memcache, $options);
            $this->assertTrue($supported);
        } catch (\InvalidArgumentException $e) {
            $this->assertFalse($supported);
        }
    }

    public function getOptionFixtures()
    {
        return array(
            array(array('prefix' => 'session'), true),
            array(array('expiretime' => 100), true),
            array(array('prefix' => 'session', 'expiretime' => 200), true),
            array(array('expiretime' => 100, 'foo' => 'bar'), false),
        );
    }

    public function testGetConnection()
    {
        $method = new \ReflectionMethod($this->storage, 'getMemcache');
        $method->setAccessible(true);

        $this->assertInstanceOf('\Memcache', $method->invoke($this->storage));
    }
}
PK=1[�+?�

nHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;

/**
 * Test class for NativeFileSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 *
 * @runTestsInSeparateProcesses
 */
class NativeFileSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir()));

        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
            $this->assertEquals('files', ini_get('session.save_handler'));
        } else {
            $this->assertEquals('files', $storage->getSaveHandler()->getSaveHandlerName());
            $this->assertEquals('user', ini_get('session.save_handler'));
        }

        $this->assertEquals(sys_get_temp_dir(), ini_get('session.save_path'));
        $this->assertEquals('TESTING', ini_get('session.name'));
    }

    /**
     * @dataProvider savePathDataProvider
     */
    public function testConstructSavePath($savePath, $expectedSavePath, $path)
    {
        $handler = new NativeFileSessionHandler($savePath);
        $this->assertEquals($expectedSavePath, ini_get('session.save_path'));
        $this->assertTrue(is_dir(realpath($path)));

        rmdir($path);
    }

    public function savePathDataProvider()
    {
        $base = sys_get_temp_dir();

        return array(
            array("$base/foo", "$base/foo", "$base/foo"),
            array("5;$base/foo", "5;$base/foo", "$base/foo"),
            array("5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"),
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructException()
    {
        $handler = new NativeFileSessionHandler('something;invalid;with;too-many-args');
    }

    public function testConstructDefault()
    {
        $path = ini_get('session.save_path');
        $storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler());

        $this->assertEquals($path, ini_get('session.save_path'));
    }
}
PK=1[>��$$kHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;

/**
 * @author Markus Bachmann <markus.bachmann@bachi.biz>
 */
class MongoDbSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $mongo;
    private $storage;
    public $options;

    protected function setUp()
    {
        if (!extension_loaded('mongo')) {
            $this->markTestSkipped('MongoDbSessionHandler requires the PHP "mongo" extension.');
        }

        $mongoClass = version_compare(phpversion('mongo'), '1.3.0', '<') ? 'Mongo' : 'MongoClient';

        $this->mongo = $this->getMockBuilder($mongoClass)
            ->disableOriginalConstructor()
            ->getMock();

        $this->options = array(
            'id_field'   => '_id',
            'data_field' => 'data',
            'time_field' => 'time',
            'database' => 'sf2-test',
            'collection' => 'session-test'
        );

        $this->storage = new MongoDbSessionHandler($this->mongo, $this->options);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorShouldThrowExceptionForInvalidMongo()
    {
        new MongoDbSessionHandler(new \stdClass(), $this->options);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorShouldThrowExceptionForMissingOptions()
    {
        new MongoDbSessionHandler($this->mongo, array());
    }

    public function testOpenMethodAlwaysReturnTrue()
    {
        $this->assertTrue($this->storage->open('test', 'test'), 'The "open" method should always return true');
    }

    public function testCloseMethodAlwaysReturnTrue()
    {
        $this->assertTrue($this->storage->close(), 'The "close" method should always return true');
    }

    public function testWrite()
    {
        $collection = $this->getMockBuilder('MongoCollection')
            ->disableOriginalConstructor()
            ->getMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $that = $this;
        $data = array();

        $collection->expects($this->once())
            ->method('update')
            ->will($this->returnCallback(function ($criteria, $updateData, $options) use ($that, &$data) {
                $that->assertEquals(array($that->options['id_field'] => 'foo'), $criteria);
                $that->assertEquals(array('upsert' => true, 'multiple' => false), $options);

                $data = $updateData['$set'];
            }));

        $this->assertTrue($this->storage->write('foo', 'bar'));

        $this->assertEquals('bar', $data[$this->options['data_field']]->bin);
        $that->assertInstanceOf('MongoDate', $data[$this->options['time_field']]);
    }

    public function testReplaceSessionData()
    {
        $collection = $this->getMockBuilder('MongoCollection')
            ->disableOriginalConstructor()
            ->getMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $data = array();

        $collection->expects($this->exactly(2))
            ->method('update')
            ->will($this->returnCallback(function ($criteria, $updateData, $options) use (&$data) {
                $data = $updateData;
            }));

        $this->storage->write('foo', 'bar');
        $this->storage->write('foo', 'foobar');

        $this->assertEquals('foobar', $data['$set'][$this->options['data_field']]->bin);
    }

    public function testDestroy()
    {
        $collection = $this->getMockBuilder('MongoCollection')
            ->disableOriginalConstructor()
            ->getMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $collection->expects($this->once())
            ->method('remove')
            ->with(array($this->options['id_field'] => 'foo'));

        $this->assertTrue($this->storage->destroy('foo'));
    }

    public function testGc()
    {
        $collection = $this->getMockBuilder('MongoCollection')
            ->disableOriginalConstructor()
            ->getMock();

        $this->mongo->expects($this->once())
            ->method('selectCollection')
            ->with($this->options['database'], $this->options['collection'])
            ->will($this->returnValue($collection));

        $that = $this;

        $collection->expects($this->once())
            ->method('remove')
            ->will($this->returnCallback(function ($criteria) use ($that) {
                $that->assertInstanceOf('MongoDate', $criteria[$that->options['time_field']]['$lt']);
                $that->assertGreaterThanOrEqual(time() - -1, $criteria[$that->options['time_field']]['$lt']->sec);
            }));

        $this->assertTrue($this->storage->gc(-1));
    }

    public function testGetConnection()
    {
        $method = new \ReflectionMethod($this->storage, 'getMongo');
        $method->setAccessible(true);

        $mongoClass = (version_compare(phpversion('mongo'), '1.3.0', '<')) ? '\Mongo' : '\MongoClient';

        $this->assertInstanceOf($mongoClass, $method->invoke($this->storage));
    }
}
PK=1[`����mHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcachedSessionHandler;

class MemcachedSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    const PREFIX = 'prefix_';
    const TTL = 1000;

    /**
     * @var MemcachedSessionHandler
     */
    protected $storage;

    protected $memcached;

    protected function setUp()
    {
        if (!class_exists('Memcached')) {
            $this->markTestSkipped('Skipped tests Memcached class is not present');
        }

        $this->memcached = $this->getMock('Memcached');
        $this->storage = new MemcachedSessionHandler(
            $this->memcached,
            array('prefix' => self::PREFIX, 'expiretime' => self::TTL)
        );
    }

    protected function tearDown()
    {
        $this->memcached = null;
        $this->storage = null;
    }

    public function testOpenSession()
    {
        $this->assertTrue($this->storage->open('', ''));
    }

    public function testCloseSession()
    {
        $this->assertTrue($this->storage->close());
    }

    public function testReadSession()
    {
        $this->memcached
            ->expects($this->once())
            ->method('get')
            ->with(self::PREFIX.'id')
        ;

        $this->assertEquals('', $this->storage->read('id'));
    }

    public function testWriteSession()
    {
        $this->memcached
            ->expects($this->once())
            ->method('set')
            ->with(self::PREFIX.'id', 'data', $this->equalTo(time() + self::TTL, 2))
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($this->storage->write('id', 'data'));
    }

    public function testDestroySession()
    {
        $this->memcached
            ->expects($this->once())
            ->method('delete')
            ->with(self::PREFIX.'id')
            ->will($this->returnValue(true))
        ;

        $this->assertTrue($this->storage->destroy('id'));
    }

    public function testGcSession()
    {
        $this->assertTrue($this->storage->gc(123));
    }

    /**
     * @dataProvider getOptionFixtures
     */
    public function testSupportedOptions($options, $supported)
    {
        try {
            new MemcachedSessionHandler($this->memcached, $options);
            $this->assertTrue($supported);
        } catch (\InvalidArgumentException $e) {
            $this->assertFalse($supported);
        }
    }

    public function getOptionFixtures()
    {
        return array(
            array(array('prefix' => 'session'), true),
            array(array('expiretime' => 100), true),
            array(array('prefix' => 'session', 'expiretime' => 200), true),
            array(array('expiretime' => 100, 'foo' => 'bar'), false),
        );
    }

    public function testGetConnection()
    {
        $method = new \ReflectionMethod($this->storage, 'getMemcached');
        $method->setAccessible(true);

        $this->assertInstanceOf('\Memcached', $method->invoke($this->storage));
    }
}
PK=1[�c=��nHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHandler;

/**
 * @author Adrien Brault <adrien.brault@gmail.com>
 */
class WriteCheckSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function test()
    {
        $wrappedSessionHandlerMock = $this->getMock('SessionHandlerInterface');
        $writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);

        $wrappedSessionHandlerMock
            ->expects($this->once())
            ->method('close')
            ->with()
            ->will($this->returnValue(true))
        ;

        $this->assertEquals(true, $writeCheckSessionHandler->close());
    }

    public function testWrite()
    {
        $wrappedSessionHandlerMock = $this->getMock('SessionHandlerInterface');
        $writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);

        $wrappedSessionHandlerMock
            ->expects($this->once())
            ->method('write')
            ->with('foo', 'bar')
            ->will($this->returnValue(true))
        ;

        $this->assertEquals(true, $writeCheckSessionHandler->write('foo', 'bar'));
    }

    public function testSkippedWrite()
    {
        $wrappedSessionHandlerMock = $this->getMock('SessionHandlerInterface');
        $writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);

        $wrappedSessionHandlerMock
            ->expects($this->once())
            ->method('read')
            ->with('foo')
            ->will($this->returnValue('bar'))
        ;

        $wrappedSessionHandlerMock
            ->expects($this->never())
            ->method('write')
        ;

        $this->assertEquals('bar', $writeCheckSessionHandler->read('foo'));
        $this->assertEquals(true, $writeCheckSessionHandler->write('foo', 'bar'));
    }

    public function testNonSkippedWrite()
    {
        $wrappedSessionHandlerMock = $this->getMock('SessionHandlerInterface');
        $writeCheckSessionHandler = new WriteCheckSessionHandler($wrappedSessionHandlerMock);

        $wrappedSessionHandlerMock
            ->expects($this->once())
            ->method('read')
            ->with('foo')
            ->will($this->returnValue('bar'))
        ;

        $wrappedSessionHandlerMock
            ->expects($this->once())
            ->method('write')
            ->with('foo', 'baZZZ')
            ->will($this->returnValue(true))
        ;

        $this->assertEquals('bar', $writeCheckSessionHandler->read('foo'));
        $this->assertEquals(true, $writeCheckSessionHandler->write('foo', 'baZZZ'));
    }
}
PK=1[�QttgHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;

class PdoSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $pdo;

    protected function setUp()
    {
        if (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers())) {
            $this->markTestSkipped('This test requires SQLite support in your environment');
        }

        $this->pdo = new \PDO("sqlite::memory:");
        $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $sql = "CREATE TABLE sessions (sess_id VARCHAR(255) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)";
        $this->pdo->exec($sql);
    }

    public function testIncompleteOptions()
    {
        $this->setExpectedException('InvalidArgumentException');
        $storage = new PdoSessionHandler($this->pdo, array(), array());
    }

    public function testWrongPdoErrMode()
    {
        $pdo = new \PDO("sqlite::memory:");
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
        $pdo->exec("CREATE TABLE sessions (sess_id VARCHAR(255) PRIMARY KEY, sess_data TEXT, sess_time INTEGER)");

        $this->setExpectedException('InvalidArgumentException');
        $storage = new PdoSessionHandler($pdo, array('db_table' => 'sessions'), array());
    }

    public function testWrongTableOptionsWrite()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'bad_name'), array());
        $this->setExpectedException('RuntimeException');
        $storage->write('foo', 'bar');
    }

    public function testWrongTableOptionsRead()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'bad_name'), array());
        $this->setExpectedException('RuntimeException');
        $storage->read('foo', 'bar');
    }

    public function testWriteRead()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());
        $storage->write('foo', 'bar');
        $this->assertEquals('bar', $storage->read('foo'), 'written value can be read back correctly');
    }

    public function testMultipleInstances()
    {
        $storage1 = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());
        $storage1->write('foo', 'bar');

        $storage2 = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());
        $this->assertEquals('bar', $storage2->read('foo'), 'values persist between instances');
    }

    public function testSessionDestroy()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());
        $storage->write('foo', 'bar');
        $this->assertCount(1, $this->pdo->query('SELECT * FROM sessions')->fetchAll());

        $storage->destroy('foo');

        $this->assertCount(0, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
    }

    public function testSessionGC()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());

        $storage->write('foo', 'bar');
        $storage->write('baz', 'bar');

        $this->assertCount(2, $this->pdo->query('SELECT * FROM sessions')->fetchAll());

        $storage->gc(-1);
        $this->assertCount(0, $this->pdo->query('SELECT * FROM sessions')->fetchAll());
    }

    public function testGetConnection()
    {
        $storage = new PdoSessionHandler($this->pdo, array('db_table' => 'sessions'), array());

        $method = new \ReflectionMethod($storage, 'getConnection');
        $method->setAccessible(true);

        $this->assertInstanceOf('\PDO', $method->invoke($storage));
    }
}
PK=1[+�ɠ��hHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NullSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;

/**
 * Test class for NullSessionHandler.
 *
 * @author Drak <drak@zikula.org>
 *
 * @runTestsInSeparateProcesses
 */
class NullSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
    public function testSaveHandlers()
    {
        $storage = $this->getStorage();
        $this->assertEquals('user', ini_get('session.save_handler'));
    }

    public function testSession()
    {
        session_id('nullsessionstorage');
        $storage = $this->getStorage();
        $session = new Session($storage);
        $this->assertNull($session->get('something'));
        $session->set('something', 'unique');
        $this->assertEquals('unique', $session->get('something'));
    }

    public function testNothingIsPersisted()
    {
        session_id('nullsessionstorage');
        $storage = $this->getStorage();
        $session = new Session($storage);
        $session->start();
        $this->assertEquals('nullsessionstorage', $session->getId());
        $this->assertNull($session->get('something'));
    }

    public function getStorage()
    {
        return new NativeSessionStorage(array(), new NullSessionHandler());
    }
}
PK=1[��x�..eHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;

use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;

/**
 * Test class for PhpSessionStorage.
 *
 * @author Drak <drak@zikula.org>
 *
 * These tests require separate processes.
 *
 * @runTestsInSeparateProcesses
 */
class PhpBridgeSessionStorageTest extends \PHPUnit_Framework_TestCase
{
    private $savePath;

    protected function setUp()
    {
        ini_set('session.save_handler', 'files');
        ini_set('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test');
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath);
        }
    }

    protected function tearDown()
    {
        session_write_close();
        array_map('unlink', glob($this->savePath.'/*'));
        if (is_dir($this->savePath)) {
            rmdir($this->savePath);
        }

        $this->savePath = null;
    }

    /**
     * @return PhpBridgeSessionStorage
     */
    protected function getStorage()
    {
        $storage = new PhpBridgeSessionStorage();
        $storage->registerBag(new AttributeBag());

        return $storage;
    }

    public function testPhpSession53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $storage = $this->getStorage();

        $this->assertFalse(isset($_SESSION));
        $this->assertFalse($storage->getSaveHandler()->isActive());

        session_start();
        $this->assertTrue(isset($_SESSION));
        // in PHP 5.3 we cannot reliably tell if a session has started
        $this->assertFalse($storage->getSaveHandler()->isActive());
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
        $this->assertTrue(isset($_SESSION[$key]));
    }

    public function testPhpSession54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        $storage = $this->getStorage();

        $this->assertFalse(isset($_SESSION));
        $this->assertFalse($storage->getSaveHandler()->isActive());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        // in PHP 5.4 we can reliably detect a session started
        $this->assertTrue($storage->getSaveHandler()->isActive());
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
        $this->assertTrue(isset($_SESSION[$key]));
    }

    public function testClear()
    {
        $storage = $this->getStorage();
        session_start();
        $_SESSION['drak'] = 'loves symfony';
        $storage->getBag('attributes')->set('symfony', 'greatness');
        $key = $storage->getBag('attributes')->getStorageKey();
        $this->assertEquals($_SESSION[$key], array('symfony' => 'greatness'));
        $this->assertEquals($_SESSION['drak'], 'loves symfony');
        $storage->clear();
        $this->assertEquals($_SESSION[$key], array());
        $this->assertEquals($_SESSION['drak'], 'loves symfony');
    }
}
PK=1[�����eHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;

use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;

/**
 * Test class for MockArraySessionStorage.
 *
 * @author Drak <drak@zikula.org>
 */
class MockArraySessionStorageTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var MockArraySessionStorage
     */
    private $storage;

    /**
     * @var AttributeBag
     */
    private $attributes;

    /**
     * @var FlashBag
     */
    private $flashes;

    private $data;

    protected function setUp()
    {
        $this->attributes = new AttributeBag();
        $this->flashes = new FlashBag();

        $this->data = array(
            $this->attributes->getStorageKey() => array('foo' => 'bar'),
            $this->flashes->getStorageKey() => array('notice' => 'hello'),
            );

        $this->storage = new MockArraySessionStorage();
        $this->storage->registerBag($this->flashes);
        $this->storage->registerBag($this->attributes);
        $this->storage->setSessionData($this->data);
    }

    protected function tearDown()
    {
        $this->data = null;
        $this->flashes = null;
        $this->attributes = null;
        $this->storage = null;
    }

    public function testStart()
    {
        $this->assertEquals('', $this->storage->getId());
        $this->storage->start();
        $id = $this->storage->getId();
        $this->assertNotEquals('', $id);
        $this->storage->start();
        $this->assertEquals($id, $this->storage->getId());
    }

    public function testRegenerate()
    {
        $this->storage->start();
        $id = $this->storage->getId();
        $this->storage->regenerate();
        $this->assertNotEquals($id, $this->storage->getId());
        $this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all());
        $this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll());

        $id = $this->storage->getId();
        $this->storage->regenerate(true);
        $this->assertNotEquals($id, $this->storage->getId());
        $this->assertEquals(array('foo' => 'bar'), $this->storage->getBag('attributes')->all());
        $this->assertEquals(array('notice' => 'hello'), $this->storage->getBag('flashes')->peekAll());
    }

    public function testGetId()
    {
        $this->assertEquals('', $this->storage->getId());
        $this->storage->start();
        $this->assertNotEquals('', $this->storage->getId());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testUnstartedSave()
    {
        $this->storage->save();
    }
}
PK=1[t䪑�$�$bHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;

use Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeSessionHandler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;
use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;

/**
 * Test class for NativeSessionStorage.
 *
 * @author Drak <drak@zikula.org>
 *
 * These tests require separate processes.
 *
 * @runTestsInSeparateProcesses
 */
class NativeSessionStorageTest extends \PHPUnit_Framework_TestCase
{
    private $savePath;

    protected function setUp()
    {
        ini_set('session.save_handler', 'files');
        ini_set('session.save_path', $this->savePath = sys_get_temp_dir().'/sf2test');
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath);
        }
    }

    protected function tearDown()
    {
        session_write_close();
        array_map('unlink', glob($this->savePath.'/*'));
        if (is_dir($this->savePath)) {
            rmdir($this->savePath);
        }

        $this->savePath = null;
    }

    /**
     * @param array $options
     *
     * @return NativeSessionStorage
     */
    protected function getStorage(array $options = array())
    {
        $storage = new NativeSessionStorage($options);
        $storage->registerBag(new AttributeBag());

        return $storage;
    }

    public function testBag()
    {
        $storage = $this->getStorage();
        $bag = new FlashBag();
        $storage->registerBag($bag);
        $this->assertSame($bag, $storage->getBag($bag->getName()));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRegisterBagException()
    {
        $storage = $this->getStorage();
        $storage->getBag('non_existing');
    }

    public function testGetId()
    {
        $storage = $this->getStorage();
        $this->assertEquals('', $storage->getId());

        $storage->start();
        $this->assertNotEquals('', $storage->getId());

        $storage->save();
        $this->assertNotEquals('', $storage->getId());
    }

    public function testRegenerate()
    {
        $storage = $this->getStorage();
        $storage->start();
        $id = $storage->getId();
        $storage->getBag('attributes')->set('lucky', 7);
        $storage->regenerate();
        $this->assertNotEquals($id, $storage->getId());
        $this->assertEquals(7, $storage->getBag('attributes')->get('lucky'));
    }

    public function testRegenerateDestroy()
    {
        $storage = $this->getStorage();
        $storage->start();
        $id = $storage->getId();
        $storage->getBag('attributes')->set('legs', 11);
        $storage->regenerate(true);
        $this->assertNotEquals($id, $storage->getId());
        $this->assertEquals(11, $storage->getBag('attributes')->get('legs'));
    }

    public function testDefaultSessionCacheLimiter()
    {
        ini_set('session.cache_limiter', 'nocache');

        $storage = new NativeSessionStorage();
        $this->assertEquals('', ini_get('session.cache_limiter'));
    }

    public function testExplicitSessionCacheLimiter()
    {
        ini_set('session.cache_limiter', 'nocache');

        $storage = new NativeSessionStorage(array('cache_limiter' => 'public'));
        $this->assertEquals('public', ini_get('session.cache_limiter'));
    }

    public function testCookieOptions()
    {
        $options = array(
            'cookie_lifetime' => 123456,
            'cookie_path' => '/my/cookie/path',
            'cookie_domain' => 'symfony2.example.com',
            'cookie_secure' => true,
            'cookie_httponly' => false,
        );

        $this->getStorage($options);
        $temp = session_get_cookie_params();
        $gco = array();

        foreach ($temp as $key => $value) {
            $gco['cookie_'.$key] = $value;
        }

        $this->assertEquals($options, $gco);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetSaveHandlerException()
    {
        $storage = $this->getStorage();
        $storage->setSaveHandler(new \stdClass());
    }

    public function testSetSaveHandler53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        ini_set('session.save_handler', 'files');
        $storage = $this->getStorage();
        $storage->setSaveHandler();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(null);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new SessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeProxy());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy', $storage->getSaveHandler());
    }

    public function testSetSaveHandler54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        ini_set('session.save_handler', 'files');
        $storage = $this->getStorage();
        $storage->setSaveHandler();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(null);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new NativeSessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new NativeSessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandlerProxy(new SessionHandler()));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
        $storage->setSaveHandler(new SessionHandler());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testStartedOutside53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $storage = $this->getStorage();

        $this->assertFalse(isset($_SESSION));

        session_start();
        $this->assertTrue(isset($_SESSION));
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testCanStartOutside54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        $storage = $this->getStorage();

        $this->assertFalse(isset($_SESSION));
        $this->assertFalse($storage->getSaveHandler()->isActive());
        $this->assertFalse($storage->isStarted());

        session_start();
        $this->assertTrue(isset($_SESSION));
        $this->assertTrue($storage->getSaveHandler()->isActive());
        // PHP session might have started, but the storage driver has not, so false is correct here
        $this->assertFalse($storage->isStarted());

        $key = $storage->getMetadataBag()->getStorageKey();
        $this->assertFalse(isset($_SESSION[$key]));
        $storage->start();
    }
}

class SessionHandler implements \SessionHandlerInterface
{
    public function open($savePath, $sessionName)
    {
    }

    public function close()
    {
    }

    public function read($id)
    {
    }

    public function write($id, $data)
    {
    }

    public function destroy($id)
    {
    }

    public function gc($maxlifetime)
    {
    }
}
PK=1[�@|B``_HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/NativeProxyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy;

use Symfony\Component\HttpFoundation\Session\Storage\Proxy\NativeProxy;

/**
 * Test class for NativeProxy.
 *
 * @author Drak <drak@zikula.org>
 */
class NativeProxyTest extends \PHPUnit_Framework_TestCase
{
    public function testIsWrapper()
    {
        $proxy = new NativeProxy();
        $this->assertFalse($proxy->isWrapper());
    }

    public function testGetSaveHandlerName()
    {
        $name = ini_get('session.save_handler');
        $proxy = new NativeProxy();
        $this->assertEquals($name, $proxy->getSaveHandlerName());
    }
}
PK=1[F�++aHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy;

use Symfony\Component\HttpFoundation\Session\Storage\Proxy\AbstractProxy;

// Note until PHPUnit_Mock_Objects 1.2 is released you cannot mock abstracts due to
// https://github.com/sebastianbergmann/phpunit-mock-objects/issues/73
class ConcreteProxy extends AbstractProxy
{

}

class ConcreteSessionHandlerInterfaceProxy extends AbstractProxy implements \SessionHandlerInterface
{
    public function open($savePath, $sessionName)
    {
    }

    public function close()
    {
    }

    public function read($id)
    {
    }

    public function write($id, $data)
    {
    }

    public function destroy($id)
    {
    }

    public function gc($maxlifetime)
    {
    }
}

/**
 * Test class for AbstractProxy.
 *
 * @author Drak <drak@zikula.org>
 */
class AbstractProxyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var AbstractProxy
     */
    protected $proxy;

    protected function setUp()
    {
        $this->proxy = new ConcreteProxy();
    }

    protected function tearDown()
    {
        $this->proxy = null;
    }

    public function testGetSaveHandlerName()
    {
        $this->assertNull($this->proxy->getSaveHandlerName());
    }

    public function testIsSessionHandlerInterface()
    {
        $this->assertFalse($this->proxy->isSessionHandlerInterface());
        $sh = new ConcreteSessionHandlerInterfaceProxy();
        $this->assertTrue($sh->isSessionHandlerInterface());
    }

    public function testIsWrapper()
    {
        $this->assertFalse($this->proxy->isWrapper());
    }

    public function testIsActivePhp53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->assertFalse($this->proxy->isActive());
    }

    /**
     * @runInSeparateProcess
     */
    public function testIsActivePhp54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        $this->assertFalse($this->proxy->isActive());
        session_start();
        $this->assertTrue($this->proxy->isActive());
    }

    public function testSetActivePhp53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->proxy->setActive(true);
        $this->assertTrue($this->proxy->isActive());
        $this->proxy->setActive(false);
        $this->assertFalse($this->proxy->isActive());
    }

    /**
     * @runInSeparateProcess
     * @expectedException \LogicException
     */
    public function testSetActivePhp54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        $this->proxy->setActive(true);
    }

    /**
     * @runInSeparateProcess
     */
    public function testName()
    {
        $this->assertEquals(session_name(), $this->proxy->getName());
        $this->proxy->setName('foo');
        $this->assertEquals('foo', $this->proxy->getName());
        $this->assertEquals(session_name(), $this->proxy->getName());
    }

    /**
     * @expectedException \LogicException
     */
    public function testNameExceptionPhp53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->proxy->setActive(true);
        $this->proxy->setName('foo');
    }

    /**
     * @runInSeparateProcess
     * @expectedException \LogicException
     */
    public function testNameExceptionPhp54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        session_start();
        $this->proxy->setName('foo');
    }

    /**
     * @runInSeparateProcess
     */
    public function testId()
    {
        $this->assertEquals(session_id(), $this->proxy->getId());
        $this->proxy->setId('foo');
        $this->assertEquals('foo', $this->proxy->getId());
        $this->assertEquals(session_id(), $this->proxy->getId());
    }

    /**
     * @expectedException \LogicException
     */
    public function testIdExceptionPhp53()
    {
        if (version_compare(phpversion(), '5.4.0', '>=')) {
            $this->markTestSkipped('Test skipped, for PHP 5.3 only.');
        }

        $this->proxy->setActive(true);
        $this->proxy->setId('foo');
    }

    /**
     * @runInSeparateProcess
     * @expectedException \LogicException
     */
    public function testIdExceptionPhp54()
    {
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->markTestSkipped('Test skipped, for PHP 5.4 only.');
        }

        session_start();
        $this->proxy->setId('foo');
    }
}
PK=1[Č#��gHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Proxy;

use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy;

/**
 * Tests for SessionHandlerProxy class.
 *
 * @author Drak <drak@zikula.org>
 *
 * @runTestsInSeparateProcesses
 */
class SessionHandlerProxyTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_Matcher
     */
    private $mock;

    /**
     * @var SessionHandlerProxy
     */
    private $proxy;

    protected function setUp()
    {
        $this->mock = $this->getMock('SessionHandlerInterface');
        $this->proxy = new SessionHandlerProxy($this->mock);
    }

    protected function tearDown()
    {
        $this->mock = null;
        $this->proxy = null;
    }

    public function testOpen()
    {
        $this->mock->expects($this->once())
            ->method('open')
            ->will($this->returnValue(true));

        $this->assertFalse($this->proxy->isActive());
        $this->proxy->open('name', 'id');
        if (version_compare(phpversion(), '5.4.0', '<')) {
            $this->assertTrue($this->proxy->isActive());
        } else {
            $this->assertFalse($this->proxy->isActive());
        }
    }

    public function testOpenFalse()
    {
        $this->mock->expects($this->once())
            ->method('open')
            ->will($this->returnValue(false));

        $this->assertFalse($this->proxy->isActive());
        $this->proxy->open('name', 'id');
        $this->assertFalse($this->proxy->isActive());
    }

    public function testClose()
    {
        $this->mock->expects($this->once())
            ->method('close')
            ->will($this->returnValue(true));

        $this->assertFalse($this->proxy->isActive());
        $this->proxy->close();
        $this->assertFalse($this->proxy->isActive());
    }

    public function testCloseFalse()
    {
        $this->mock->expects($this->once())
            ->method('close')
            ->will($this->returnValue(false));

        $this->assertFalse($this->proxy->isActive());
        $this->proxy->close();
        $this->assertFalse($this->proxy->isActive());
    }

    public function testRead()
    {
        $this->mock->expects($this->once())
            ->method('read');

        $this->proxy->read('id');
    }

    public function testWrite()
    {
        $this->mock->expects($this->once())
            ->method('write');

        $this->proxy->write('id', 'data');
    }

    public function testDestroy()
    {
        $this->mock->expects($this->once())
            ->method('destroy');

        $this->proxy->destroy('id');
    }

    public function testGc()
    {
        $this->mock->expects($this->once())
            ->method('gc');

        $this->proxy->gc(86400);
    }
}
PK=1[T �S��YHttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MetadataBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage;

use Symfony\Component\HttpFoundation\Session\Storage\MetadataBag;

/**
 * Test class for MetadataBag.
 */
class MetadataBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var MetadataBag
     */
    protected $bag;

    /**
     * @var array
     */
    protected $array = array();

    protected function setUp()
    {
        $this->bag = new MetadataBag();
        $this->array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 0);
        $this->bag->initialize($this->array);
    }

    protected function tearDown()
    {
        $this->array = array();
        $this->bag = null;
    }

    public function testInitialize()
    {
        $sessionMetadata = array();

        $bag1 = new MetadataBag();
        $bag1->initialize($sessionMetadata);
        $this->assertGreaterThanOrEqual(time(), $bag1->getCreated());
        $this->assertEquals($bag1->getCreated(), $bag1->getLastUsed());

        sleep(1);
        $bag2 = new MetadataBag();
        $bag2->initialize($sessionMetadata);
        $this->assertEquals($bag1->getCreated(), $bag2->getCreated());
        $this->assertEquals($bag1->getLastUsed(), $bag2->getLastUsed());
        $this->assertEquals($bag2->getCreated(), $bag2->getLastUsed());

        sleep(1);
        $bag3 = new MetadataBag();
        $bag3->initialize($sessionMetadata);
        $this->assertEquals($bag1->getCreated(), $bag3->getCreated());
        $this->assertGreaterThan($bag2->getLastUsed(), $bag3->getLastUsed());
        $this->assertNotEquals($bag3->getCreated(), $bag3->getLastUsed());
    }

    public function testGetSetName()
    {
        $this->assertEquals('__metadata', $this->bag->getName());
        $this->bag->setName('foo');
        $this->assertEquals('foo', $this->bag->getName());

    }

    public function testGetStorageKey()
    {
        $this->assertEquals('_sf2_meta', $this->bag->getStorageKey());
    }

    public function testGetLifetime()
    {
        $bag = new MetadataBag();
        $array = array(MetadataBag::CREATED => 1234567, MetadataBag::UPDATED => 12345678, MetadataBag::LIFETIME => 1000);
        $bag->initialize($array);
        $this->assertEquals(1000, $bag->getLifetime());
    }

    public function testGetCreated()
    {
        $this->assertEquals(1234567, $this->bag->getCreated());
    }

    public function testGetLastUsed()
    {
        $this->assertLessThanOrEqual(time(), $this->bag->getLastUsed());
    }

    public function testClear()
    {
        $this->bag->clear();
    }

    public function testSkipLastUsedUpdate()
    {
        $bag = new MetadataBag('', 30);
        $timeStamp = time();

        $created = $timeStamp - 15;
        $sessionMetadata = array(
            MetadataBag::CREATED => $created,
            MetadataBag::UPDATED => $created,
            MetadataBag::LIFETIME => 1000
        );
        $bag->initialize($sessionMetadata);

        $this->assertEquals($created, $sessionMetadata[MetadataBag::UPDATED]);
    }

    public function testDoesNotSkipLastUsedUpdate()
    {
        $bag = new MetadataBag('', 30);
        $timeStamp = time();

        $created = $timeStamp - 45;
        $sessionMetadata = array(
            MetadataBag::CREATED => $created,
            MetadataBag::UPDATED => $created,
            MetadataBag::LIFETIME => 1000
        );
        $bag->initialize($sessionMetadata);

        $this->assertEquals($timeStamp, $sessionMetadata[MetadataBag::UPDATED]);
    }
}
PK=1[��7�
�
NHttpFoundation/Symfony/Component/HttpFoundation/Tests/AcceptHeaderItemTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\AcceptHeaderItem;

class AcceptHeaderItemTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideFromStringData
     */
    public function testFromString($string, $value, array $attributes)
    {
        $item = AcceptHeaderItem::fromString($string);
        $this->assertEquals($value, $item->getValue());
        $this->assertEquals($attributes, $item->getAttributes());
    }

    public function provideFromStringData()
    {
        return array(
            array(
                'text/html',
                'text/html', array()
            ),
            array(
                '"this;should,not=matter"',
                'this;should,not=matter', array()
            ),
            array(
                "text/plain; charset=utf-8;param=\"this;should,not=matter\";\tfootnotes=true",
                'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true')
            ),
            array(
                '"this;should,not=matter";charset=utf-8',
                'this;should,not=matter', array('charset' => 'utf-8')
            ),
        );
    }

    /**
     * @dataProvider provideToStringData
     */
    public function testToString($value, array $attributes, $string)
    {
        $item = new AcceptHeaderItem($value, $attributes);
        $this->assertEquals($string, (string) $item);
    }

    public function provideToStringData()
    {
        return array(
            array(
                'text/html', array(),
                'text/html'
            ),
            array(
                'text/plain', array('charset' => 'utf-8', 'param' => 'this;should,not=matter', 'footnotes' => 'true'),
                'text/plain;charset=utf-8;param="this;should,not=matter";footnotes=true'
            ),
        );
    }

    public function testValue()
    {
        $item = new AcceptHeaderItem('value', array());
        $this->assertEquals('value', $item->getValue());

        $item->setValue('new value');
        $this->assertEquals('new value', $item->getValue());

        $item->setValue(1);
        $this->assertEquals('1', $item->getValue());
    }

    public function testQuality()
    {
        $item = new AcceptHeaderItem('value', array());
        $this->assertEquals(1.0, $item->getQuality());

        $item->setQuality(0.5);
        $this->assertEquals(0.5, $item->getQuality());

        $item->setAttribute('q', 0.75);
        $this->assertEquals(0.75, $item->getQuality());
        $this->assertFalse($item->hasAttribute('q'));
    }

    public function testAttribute()
    {
        $item = new AcceptHeaderItem('value', array());
        $this->assertEquals(array(), $item->getAttributes());
        $this->assertFalse($item->hasAttribute('test'));
        $this->assertNull($item->getAttribute('test'));
        $this->assertEquals('default', $item->getAttribute('test', 'default'));

        $item->setAttribute('test', 'value');
        $this->assertEquals(array('test' => 'value'), $item->getAttributes());
        $this->assertTrue($item->hasAttribute('test'));
        $this->assertEquals('value', $item->getAttribute('test'));
        $this->assertEquals('value', $item->getAttribute('test', 'default'));
    }
}
PK=1[�`k JHttpFoundation/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\JsonResponse;

class JsonResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructorEmptyCreatesJsonObject()
    {
        $response = new JsonResponse();
        $this->assertSame('{}', $response->getContent());
    }

    public function testConstructorWithArrayCreatesJsonArray()
    {
        $response = new JsonResponse(array(0, 1, 2, 3));
        $this->assertSame('[0,1,2,3]', $response->getContent());
    }

    public function testConstructorWithAssocArrayCreatesJsonObject()
    {
        $response = new JsonResponse(array('foo' => 'bar'));
        $this->assertSame('{"foo":"bar"}', $response->getContent());
    }

    public function testConstructorWithSimpleTypes()
    {
        $response = new JsonResponse('foo');
        $this->assertSame('"foo"', $response->getContent());

        $response = new JsonResponse(0);
        $this->assertSame('0', $response->getContent());

        $response = new JsonResponse(0.1);
        $this->assertSame('0.1', $response->getContent());

        $response = new JsonResponse(true);
        $this->assertSame('true', $response->getContent());
    }

    public function testConstructorWithCustomStatus()
    {
        $response = new JsonResponse(array(), 202);
        $this->assertSame(202, $response->getStatusCode());
    }

    public function testConstructorAddsContentTypeHeader()
    {
        $response = new JsonResponse();
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
    }

    public function testConstructorWithCustomHeaders()
    {
        $response = new JsonResponse(array(), 200, array('ETag' => 'foo'));
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
        $this->assertSame('foo', $response->headers->get('ETag'));
    }

    public function testConstructorWithCustomContentType()
    {
        $headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json');

        $response = new JsonResponse(array(), 200, $headers);
        $this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type'));
    }

    public function testCreate()
    {
        $response = JsonResponse::create(array('foo' => 'bar'), 204);

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertEquals('{"foo":"bar"}', $response->getContent());
        $this->assertEquals(204, $response->getStatusCode());
    }

    public function testStaticCreateEmptyJsonObject()
    {
        $response = JsonResponse::create();
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('{}', $response->getContent());
    }

    public function testStaticCreateJsonArray()
    {
        $response = JsonResponse::create(array(0, 1, 2, 3));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('[0,1,2,3]', $response->getContent());
    }

    public function testStaticCreateJsonObject()
    {
        $response = JsonResponse::create(array('foo' => 'bar'));
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('{"foo":"bar"}', $response->getContent());
    }

    public function testStaticCreateWithSimpleTypes()
    {
        $response = JsonResponse::create('foo');
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('"foo"', $response->getContent());

        $response = JsonResponse::create(0);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('0', $response->getContent());

        $response = JsonResponse::create(0.1);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('0.1', $response->getContent());

        $response = JsonResponse::create(true);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response);
        $this->assertSame('true', $response->getContent());
    }

    public function testStaticCreateWithCustomStatus()
    {
        $response = JsonResponse::create(array(), 202);
        $this->assertSame(202, $response->getStatusCode());
    }

    public function testStaticCreateAddsContentTypeHeader()
    {
        $response = JsonResponse::create();
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
    }

    public function testStaticCreateWithCustomHeaders()
    {
        $response = JsonResponse::create(array(), 200, array('ETag' => 'foo'));
        $this->assertSame('application/json', $response->headers->get('Content-Type'));
        $this->assertSame('foo', $response->headers->get('ETag'));
    }

    public function testStaticCreateWithCustomContentType()
    {
        $headers = array('Content-Type' => 'application/vnd.acme.blog-v1+json');

        $response = JsonResponse::create(array(), 200, $headers);
        $this->assertSame('application/vnd.acme.blog-v1+json', $response->headers->get('Content-Type'));
    }

    public function testSetCallback()
    {
        $response = JsonResponse::create(array('foo' => 'bar'))->setCallback('callback');

        $this->assertEquals('callback({"foo":"bar"});', $response->getContent());
        $this->assertEquals('text/javascript', $response->headers->get('Content-Type'));
    }

    public function testJsonEncodeFlags()
    {
        $response = new JsonResponse('<>\'&"');

        $this->assertEquals('"\u003C\u003E\u0027\u0026\u0022"', $response->getContent());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetCallbackInvalidIdentifier()
    {
        $response = new JsonResponse('foo');
        $response->setCallback('+invalid');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetContent()
    {
        JsonResponse::create("\xB1\x31");
    }
}
PK=1[�E����LHttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\RequestMatcher;
use Symfony\Component\HttpFoundation\Request;

class RequestMatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider testMethodFixtures
     */
    public function testMethod($requestMethod, $matcherMethod, $isMatch)
    {
        $matcher = new RequestMatcher();
        $matcher->matchMethod($matcherMethod);
        $request = Request::create('', $requestMethod);
        $this->assertSame($isMatch, $matcher->matches($request));

        $matcher = new RequestMatcher(null, null, $matcherMethod);
        $request = Request::create('', $requestMethod);
        $this->assertSame($isMatch, $matcher->matches($request));
    }

    public function testMethodFixtures()
    {
        return array(
            array('get', 'get', true),
            array('get', array('get', 'post'), true),
            array('get', 'post', false),
            array('get', 'GET', true),
            array('get', array('GET', 'POST'), true),
            array('get', 'POST', false),
        );
    }

    /**
     * @dataProvider testHostFixture
     */
    public function testHost($pattern, $isMatch)
    {
        $matcher = new RequestMatcher();
        $request = Request::create('', 'get', array(), array(), array(), array('HTTP_HOST' => 'foo.example.com'));

        $matcher->matchHost($pattern);
        $this->assertSame($isMatch, $matcher->matches($request));

        $matcher= new RequestMatcher(null, $pattern);
        $this->assertSame($isMatch, $matcher->matches($request));
    }

    public function testHostFixture()
    {
        return array(
            array('.*\.example\.com', true),
            array('\.example\.com$', true),
            array('^.*\.example\.com$', true),
            array('.*\.sensio\.com', false),
            array('.*\.example\.COM', true),
            array('\.example\.COM$', true),
            array('^.*\.example\.COM$', true),
            array('.*\.sensio\.COM', false),        );
    }

    public function testPath()
    {
        $matcher = new RequestMatcher();

        $request = Request::create('/admin/foo');

        $matcher->matchPath('/admin/.*');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchPath('/admin');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchPath('^/admin/.*$');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchMethod('/blog/.*');
        $this->assertFalse($matcher->matches($request));
    }

    public function testPathWithLocaleIsNotSupported()
    {
        $matcher = new RequestMatcher();
        $request = Request::create('/en/login');
        $request->setLocale('en');

        $matcher->matchPath('^/{_locale}/login$');
        $this->assertFalse($matcher->matches($request));
    }

    public function testPathWithEncodedCharacters()
    {
        $matcher = new RequestMatcher();
        $request = Request::create('/admin/fo%20o');
        $matcher->matchPath('^/admin/fo o*$');
        $this->assertTrue($matcher->matches($request));
    }

    public function testAttributes()
    {
        $matcher = new RequestMatcher();

        $request = Request::create('/admin/foo');
        $request->attributes->set('foo', 'foo_bar');

        $matcher->matchAttribute('foo', 'foo_.*');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchAttribute('foo', 'foo');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchAttribute('foo', '^foo_bar$');
        $this->assertTrue($matcher->matches($request));

        $matcher->matchAttribute('foo', 'babar');
        $this->assertFalse($matcher->matches($request));
    }
}
PK=1[����,�,OHttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Cookie;

class ResponseHeaderBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\HttpFoundation\ResponseHeaderBag::allPreserveCase
     * @dataProvider provideAllPreserveCase
     */
    public function testAllPreserveCase($headers, $expected)
    {
        $bag = new ResponseHeaderBag($headers);

        $this->assertEquals($expected, $bag->allPreserveCase(), '->allPreserveCase() gets all input keys in original case');
    }

    public function provideAllPreserveCase()
    {
        return array(
            array(
                array('fOo' => 'BAR'),
                array('fOo' => array('BAR'), 'Cache-Control' => array('no-cache'))
            ),
            array(
                array('ETag' => 'xyzzy'),
                array('ETag' => array('xyzzy'), 'Cache-Control' => array('private, must-revalidate'))
            ),
            array(
                array('Content-MD5' => 'Q2hlY2sgSW50ZWdyaXR5IQ=='),
                array('Content-MD5' => array('Q2hlY2sgSW50ZWdyaXR5IQ=='), 'Cache-Control' => array('no-cache'))
            ),
            array(
                array('P3P' => 'CP="CAO PSA OUR"'),
                array('P3P' => array('CP="CAO PSA OUR"'), 'Cache-Control' => array('no-cache'))
            ),
            array(
                array('WWW-Authenticate' => 'Basic realm="WallyWorld"'),
                array('WWW-Authenticate' => array('Basic realm="WallyWorld"'), 'Cache-Control' => array('no-cache'))
            ),
            array(
                array('X-UA-Compatible' => 'IE=edge,chrome=1'),
                array('X-UA-Compatible' => array('IE=edge,chrome=1'), 'Cache-Control' => array('no-cache'))
            ),
            array(
                array('X-XSS-Protection' => '1; mode=block'),
                array('X-XSS-Protection' => array('1; mode=block'), 'Cache-Control' => array('no-cache'))
            ),
        );
    }

    public function testCacheControlHeader()
    {
        $bag = new ResponseHeaderBag(array());
        $this->assertEquals('no-cache', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));

        $bag = new ResponseHeaderBag(array('Cache-Control' => 'public'));
        $this->assertEquals('public', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('public'));

        $bag = new ResponseHeaderBag(array('ETag' => 'abcde'));
        $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('private'));
        $this->assertTrue($bag->hasCacheControlDirective('must-revalidate'));
        $this->assertFalse($bag->hasCacheControlDirective('max-age'));

        $bag = new ResponseHeaderBag(array('Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT'));
        $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array(
            'Expires' => 'Wed, 16 Feb 2011 14:17:43 GMT',
            'Cache-Control' => 'max-age=3600'
        ));
        $this->assertEquals('max-age=3600, private', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('Last-Modified' => 'abcde'));
        $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('Etag' => 'abcde', 'Last-Modified' => 'abcde'));
        $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('cache-control' => 'max-age=100'));
        $this->assertEquals('max-age=100, private', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('cache-control' => 's-maxage=100'));
        $this->assertEquals('s-maxage=100', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('cache-control' => 'private, max-age=100'));
        $this->assertEquals('max-age=100, private', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag(array('cache-control' => 'public, max-age=100'));
        $this->assertEquals('max-age=100, public', $bag->get('Cache-Control'));

        $bag = new ResponseHeaderBag();
        $bag->set('Last-Modified', 'abcde');
        $this->assertEquals('private, must-revalidate', $bag->get('Cache-Control'));
    }

    public function testToStringIncludesCookieHeaders()
    {
        $bag = new ResponseHeaderBag(array());
        $bag->setCookie(new Cookie('foo', 'bar'));

        $this->assertContains("Set-Cookie: foo=bar; path=/; httponly", explode("\r\n", $bag->__toString()));

        $bag->clearCookie('foo');

        $this->assertContains("Set-Cookie: foo=deleted; expires=".gmdate("D, d-M-Y H:i:s T", time() - 31536001)."; path=/; httponly", explode("\r\n", $bag->__toString()));
    }

    public function testReplace()
    {
        $bag = new ResponseHeaderBag(array());
        $this->assertEquals('no-cache', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));

        $bag->replace(array('Cache-Control' => 'public'));
        $this->assertEquals('public', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('public'));
    }

    public function testReplaceWithRemove()
    {
        $bag = new ResponseHeaderBag(array());
        $this->assertEquals('no-cache', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));

        $bag->remove('Cache-Control');
        $bag->replace(array());
        $this->assertEquals('no-cache', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));
    }

    public function testCookiesWithSameNames()
    {
        $bag = new ResponseHeaderBag();
        $bag->setCookie(new Cookie('foo', 'bar', 0, '/path/foo', 'foo.bar'));
        $bag->setCookie(new Cookie('foo', 'bar', 0, '/path/bar', 'foo.bar'));
        $bag->setCookie(new Cookie('foo', 'bar', 0, '/path/bar', 'bar.foo'));
        $bag->setCookie(new Cookie('foo', 'bar'));

        $this->assertCount(4, $bag->getCookies());

        $headers = explode("\r\n", $bag->__toString());
        $this->assertContains("Set-Cookie: foo=bar; path=/path/foo; domain=foo.bar; httponly", $headers);
        $this->assertContains("Set-Cookie: foo=bar; path=/path/foo; domain=foo.bar; httponly", $headers);
        $this->assertContains("Set-Cookie: foo=bar; path=/path/bar; domain=bar.foo; httponly", $headers);
        $this->assertContains("Set-Cookie: foo=bar; path=/; httponly", $headers);

        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertTrue(isset($cookies['foo.bar']['/path/foo']['foo']));
        $this->assertTrue(isset($cookies['foo.bar']['/path/bar']['foo']));
        $this->assertTrue(isset($cookies['bar.foo']['/path/bar']['foo']));
        $this->assertTrue(isset($cookies['']['/']['foo']));
    }

    public function testRemoveCookie()
    {
        $bag = new ResponseHeaderBag();
        $bag->setCookie(new Cookie('foo', 'bar', 0, '/path/foo', 'foo.bar'));
        $bag->setCookie(new Cookie('bar', 'foo', 0, '/path/bar', 'foo.bar'));

        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertTrue(isset($cookies['foo.bar']['/path/foo']));

        $bag->removeCookie('foo', '/path/foo', 'foo.bar');

        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertFalse(isset($cookies['foo.bar']['/path/foo']));

        $bag->removeCookie('bar', '/path/bar', 'foo.bar');

        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertFalse(isset($cookies['foo.bar']));
    }

    public function testRemoveCookieWithNullRemove()
    {
        $bag = new ResponseHeaderBag();
        $bag->setCookie(new Cookie('foo', 'bar', 0));
        $bag->setCookie(new Cookie('bar', 'foo', 0));

        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertTrue(isset($cookies['']['/']));

        $bag->removeCookie('foo', null);
        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertFalse(isset($cookies['']['/']['foo']));

        $bag->removeCookie('bar', null);
        $cookies = $bag->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
        $this->assertFalse(isset($cookies['']['/']['bar']));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetCookiesWithInvalidArgument()
    {
        $bag = new ResponseHeaderBag();

        $cookies = $bag->getCookies('invalid_argument');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testMakeDispositionInvalidDisposition()
    {
        $headers = new ResponseHeaderBag();

        $headers->makeDisposition('invalid', 'foo.html');
    }

    /**
     * @dataProvider provideMakeDisposition
     */
    public function testMakeDisposition($disposition, $filename, $filenameFallback, $expected)
    {
        $headers = new ResponseHeaderBag();

        $this->assertEquals($expected, $headers->makeDisposition($disposition, $filename, $filenameFallback));
    }

    public function testToStringDoesntMessUpHeaders()
    {
        $headers = new ResponseHeaderBag();

        $headers->set('Location', 'http://www.symfony.com');
        $headers->set('Content-type', 'text/html');

        (string) $headers;

        $allHeaders = $headers->allPreserveCase();
        $this->assertEquals(array('http://www.symfony.com'), $allHeaders['Location']);
        $this->assertEquals(array('text/html'), $allHeaders['Content-type']);
    }

    public function provideMakeDisposition()
    {
        return array(
            array('attachment', 'foo.html', 'foo.html', 'attachment; filename="foo.html"'),
            array('attachment', 'foo.html', '', 'attachment; filename="foo.html"'),
            array('attachment', 'foo bar.html', '', 'attachment; filename="foo bar.html"'),
            array('attachment', 'foo "bar".html', '', 'attachment; filename="foo \\"bar\\".html"'),
            array('attachment', 'foo%20bar.html', 'foo bar.html', 'attachment; filename="foo bar.html"; filename*=utf-8\'\'foo%2520bar.html'),
            array('attachment', 'föö.html', 'foo.html', 'attachment; filename="foo.html"; filename*=utf-8\'\'f%C3%B6%C3%B6.html'),
        );
    }

    /**
     * @dataProvider provideMakeDispositionFail
     * @expectedException \InvalidArgumentException
     */
    public function testMakeDispositionFail($disposition, $filename)
    {
        $headers = new ResponseHeaderBag();

        $headers->makeDisposition($disposition, $filename);
    }

    public function provideMakeDispositionFail()
    {
        return array(
            array('attachment', 'foo%20bar.html'),
            array('attachment', 'foo/bar.html'),
            array('attachment', '/foo.html'),
            array('attachment', 'foo\bar.html'),
            array('attachment', '\foo.html'),
            array('attachment', 'föö.html'),
        );
    }
}
PK=1[k\B��r�rFHttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ResponseTest extends ResponseTestCase
{
    public function testCreate()
    {
        $response = Response::create('foo', 301, array('Foo' => 'bar'));

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
        $this->assertEquals(301, $response->getStatusCode());
        $this->assertEquals('bar', $response->headers->get('foo'));
    }

    public function testToString()
    {
        $response = new Response();
        $response = explode("\r\n", $response);
        $this->assertEquals("HTTP/1.0 200 OK", $response[0]);
        $this->assertEquals("Cache-Control: no-cache", $response[1]);
    }

    public function testClone()
    {
        $response = new Response();
        $responseClone = clone $response;
        $this->assertEquals($response, $responseClone);
    }

    public function testSendHeaders()
    {
        $response = new Response();
        $headers = $response->sendHeaders();
        $this->assertObjectHasAttribute('headers', $headers);
        $this->assertObjectHasAttribute('content', $headers);
        $this->assertObjectHasAttribute('version', $headers);
        $this->assertObjectHasAttribute('statusCode', $headers);
        $this->assertObjectHasAttribute('statusText', $headers);
        $this->assertObjectHasAttribute('charset', $headers);
    }

    public function testSend()
    {
        $response = new Response();
        $responseSend = $response->send();
        $this->assertObjectHasAttribute('headers', $responseSend);
        $this->assertObjectHasAttribute('content', $responseSend);
        $this->assertObjectHasAttribute('version', $responseSend);
        $this->assertObjectHasAttribute('statusCode', $responseSend);
        $this->assertObjectHasAttribute('statusText', $responseSend);
        $this->assertObjectHasAttribute('charset', $responseSend);
    }

    public function testGetCharset()
    {
        $response = new Response();
        $charsetOrigin = 'UTF-8';
        $response->setCharset($charsetOrigin);
        $charset = $response->getCharset();
        $this->assertEquals($charsetOrigin, $charset);
    }

    public function testIsCacheable()
    {
        $response = new Response();
        $this->assertFalse($response->isCacheable());
    }

    public function testIsCacheableWithErrorCode()
    {
        $response = new Response('', 500);
        $this->assertFalse($response->isCacheable());
    }

    public function testIsCacheableWithNoStoreDirective()
    {
        $response = new Response();
        $response->headers->set('cache-control', 'private');
        $this->assertFalse($response->isCacheable());
    }

    public function testIsCacheableWithSetTtl()
    {
        $response = new Response();
        $response->setTtl(10);
        $this->assertTrue($response->isCacheable());
    }

    public function testMustRevalidate()
    {
        $response = new Response();
        $this->assertFalse($response->mustRevalidate());
    }

    public function testSetNotModified()
    {
        $response = new Response();
        $modified = $response->setNotModified();
        $this->assertObjectHasAttribute('headers', $modified);
        $this->assertObjectHasAttribute('content', $modified);
        $this->assertObjectHasAttribute('version', $modified);
        $this->assertObjectHasAttribute('statusCode', $modified);
        $this->assertObjectHasAttribute('statusText', $modified);
        $this->assertObjectHasAttribute('charset', $modified);
        $this->assertEquals(304, $modified->getStatusCode());
    }

    public function testIsSuccessful()
    {
        $response = new Response();
        $this->assertTrue($response->isSuccessful());
    }

    public function testIsNotModified()
    {
        $response = new Response();
        $modified = $response->isNotModified(new Request());
        $this->assertFalse($modified);
    }

    public function testIsNotModifiedNotSafe()
    {
        $request = Request::create('/homepage', 'POST');

        $response = new Response();
        $this->assertFalse($response->isNotModified($request));
    }

    public function testIsNotModifiedLastModified()
    {
        $modified = 'Sun, 25 Aug 2013 18:33:31 GMT';

        $request = new Request();
        $request->headers->set('If-Modified-Since', $modified);

        $response = new Response();
        $response->headers->set('Last-Modified', $modified);

        $this->assertTrue($response->isNotModified($request));

        $response->headers->set('Last-Modified', '');
        $this->assertFalse($response->isNotModified($request));
    }

    public function testIsNotModifiedEtag()
    {
        $etagOne = 'randomly_generated_etag';
        $etagTwo = 'randomly_generated_etag_2';

        $request = new Request();
        $request->headers->set('if_none_match', sprintf('%s, %s, %s', $etagOne, $etagTwo, 'etagThree'));

        $response = new Response();

        $response->headers->set('ETag', $etagOne);
        $this->assertTrue($response->isNotModified($request));

        $response->headers->set('ETag', $etagTwo);
        $this->assertTrue($response->isNotModified($request));

        $response->headers->set('ETag', '');
        $this->assertFalse($response->isNotModified($request));
    }

    public function testIsValidateable()
    {
        $response = new Response('', 200, array('Last-Modified' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
        $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if Last-Modified is present');

        $response = new Response('', 200, array('ETag' => '"12345"'));
        $this->assertTrue($response->isValidateable(), '->isValidateable() returns true if ETag is present');

        $response = new Response();
        $this->assertFalse($response->isValidateable(), '->isValidateable() returns false when no validator is present');
    }

    public function testGetDate()
    {
        $response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
        $this->assertEquals(0, $this->createDateTimeOneHourAgo()->diff($response->getDate())->format('%s'), '->getDate() returns the Date header if present');

        $response = new Response();
        $date = $response->getDate();
        $this->assertLessThan(1, $date->diff(new \DateTime(), true)->format('%s'), '->getDate() returns the current Date if no Date header present');

        $response = new Response('', 200, array('Date' => $this->createDateTimeOneHourAgo()->format(DATE_RFC2822)));
        $now = $this->createDateTimeNow();
        $response->headers->set('Date', $now->format(DATE_RFC2822));
        $this->assertEquals(0, $now->diff($response->getDate())->format('%s'), '->getDate() returns the date when the header has been modified');

        $response = new Response('', 200);
        $response->headers->remove('Date');
        $this->assertInstanceOf('\DateTime', $response->getDate());
    }

    public function testGetMaxAge()
    {
        $response = new Response();
        $response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
        $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=600');
        $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'must-revalidate');
        $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
        $this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'must-revalidate');
        $response->headers->set('Expires', -1);
        $this->assertEquals('Sat, 01 Jan 00 00:00:00 +0000', $response->getExpires()->format(DATE_RFC822));

        $response = new Response();
        $this->assertNull($response->getMaxAge(), '->getMaxAge() returns null if no freshness information available');
    }

    public function testSetSharedMaxAge()
    {
        $response = new Response();
        $response->setSharedMaxAge(20);

        $cacheControl = $response->headers->get('Cache-Control');
        $this->assertEquals('public, s-maxage=20', $cacheControl);
    }

    public function testIsPrivate()
    {
        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=100');
        $response->setPrivate();
        $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
        $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');

        $response = new Response();
        $response->headers->set('Cache-Control', 'public, max-age=100');
        $response->setPrivate();
        $this->assertEquals(100, $response->headers->getCacheControlDirective('max-age'), '->isPrivate() adds the private Cache-Control directive when set to true');
        $this->assertTrue($response->headers->getCacheControlDirective('private'), '->isPrivate() adds the private Cache-Control directive when set to true');
        $this->assertFalse($response->headers->hasCacheControlDirective('public'), '->isPrivate() removes the public Cache-Control directive');
    }

    public function testExpire()
    {
        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=100');
        $response->expire();
        $this->assertEquals(100, $response->headers->get('Age'), '->expire() sets the Age to max-age when present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=100, s-maxage=500');
        $response->expire();
        $this->assertEquals(500, $response->headers->get('Age'), '->expire() sets the Age to s-maxage when both max-age and s-maxage are present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=5, s-maxage=500');
        $response->headers->set('Age', '1000');
        $response->expire();
        $this->assertEquals(1000, $response->headers->get('Age'), '->expire() does nothing when the response is already stale/expired');

        $response = new Response();
        $response->expire();
        $this->assertFalse($response->headers->has('Age'), '->expire() does nothing when the response does not include freshness information');

        $response = new Response();
        $response->headers->set('Expires', -1);
        $response->expire();
        $this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');
    }

    public function testGetTtl()
    {
        $response = new Response();
        $this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');

        $response = new Response();
        $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(DATE_RFC2822));
        $this->assertLessThan(1, 3600 - $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');

        $response = new Response();
        $response->headers->set('Expires', $this->createDateTimeOneHourAgo()->format(DATE_RFC2822));
        $this->assertLessThan(0, $response->getTtl(), '->getTtl() returns negative values when Expires is in past');

        $response = new Response();
        $response->headers->set('Expires', $response->getDate()->format(DATE_RFC2822));
        $response->headers->set('Age', 0);
        $this->assertSame(0, $response->getTtl(), '->getTtl() correctly handles zero');

        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=60');
        $this->assertLessThan(1, 60 - $response->getTtl(), '->getTtl() uses Cache-Control max-age when present');
    }

    public function testSetClientTtl()
    {
        $response = new Response();
        $response->setClientTtl(10);

        $this->assertEquals($response->getMaxAge(), $response->getAge() + 10);
    }

    public function testGetSetProtocolVersion()
    {
        $response = new Response();

        $this->assertEquals('1.0', $response->getProtocolVersion());

        $response->setProtocolVersion('1.1');

        $this->assertEquals('1.1', $response->getProtocolVersion());
    }

    public function testGetVary()
    {
        $response = new Response();
        $this->assertEquals(array(), $response->getVary(), '->getVary() returns an empty array if no Vary header is present');

        $response = new Response();
        $response->headers->set('Vary', 'Accept-Language');
        $this->assertEquals(array('Accept-Language'), $response->getVary(), '->getVary() parses a single header name value');

        $response = new Response();
        $response->headers->set('Vary', 'Accept-Language User-Agent    X-Foo');
        $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by spaces');

        $response = new Response();
        $response->headers->set('Vary', 'Accept-Language,User-Agent,    X-Foo');
        $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->getVary() parses multiple header name values separated by commas');

        $vary = array('Accept-Language', 'User-Agent', 'X-foo');

        $response = new Response();
        $response->headers->set('Vary', $vary);
        $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');

        $response = new Response();
        $response->headers->set('Vary', 'Accept-Language, User-Agent, X-foo');
        $this->assertEquals($vary, $response->getVary(), '->getVary() parses multiple header name values in arrays');
    }

    public function testSetVary()
    {
        $response = new Response();
        $response->setVary('Accept-Language');
        $this->assertEquals(array('Accept-Language'), $response->getVary());

        $response->setVary('Accept-Language, User-Agent');
        $this->assertEquals(array('Accept-Language', 'User-Agent'), $response->getVary(), '->setVary() replace the vary header by default');

        $response->setVary('X-Foo', false);
        $this->assertEquals(array('Accept-Language', 'User-Agent', 'X-Foo'), $response->getVary(), '->setVary() doesn\'t wipe out earlier Vary headers if replace is set to false');
    }

    public function testDefaultContentType()
    {
        $headerMock = $this->getMock('Symfony\Component\HttpFoundation\ResponseHeaderBag', array('set'));
        $headerMock->expects($this->at(0))
            ->method('set')
            ->with('Content-Type', 'text/html');
        $headerMock->expects($this->at(1))
            ->method('set')
            ->with('Content-Type', 'text/html; charset=UTF-8');

        $response = new Response('foo');
        $response->headers = $headerMock;

        $response->prepare(new Request());
    }

    public function testContentTypeCharset()
    {
        $response = new Response();
        $response->headers->set('Content-Type', 'text/css');

        // force fixContentType() to be called
        $response->prepare(new Request());

        $this->assertEquals('text/css; charset=UTF-8', $response->headers->get('Content-Type'));
    }

    public function testPrepareDoesNothingIfContentTypeIsSet()
    {
        $response = new Response('foo');
        $response->headers->set('Content-Type', 'text/plain');

        $response->prepare(new Request());

        $this->assertEquals('text/plain; charset=UTF-8', $response->headers->get('content-type'));
    }

    public function testPrepareDoesNothingIfRequestFormatIsNotDefined()
    {
        $response = new Response('foo');

        $response->prepare(new Request());

        $this->assertEquals('text/html; charset=UTF-8', $response->headers->get('content-type'));
    }

    public function testPrepareSetContentType()
    {
        $response = new Response('foo');
        $request = Request::create('/');
        $request->setRequestFormat('json');

        $response->prepare($request);

        $this->assertEquals('application/json', $response->headers->get('content-type'));
    }

    public function testPrepareRemovesContentForHeadRequests()
    {
        $response = new Response('foo');
        $request = Request::create('/', 'HEAD');

        $length = 12345;
        $response->headers->set('Content-Length', $length);
        $response->prepare($request);

        $this->assertEquals('', $response->getContent());
        $this->assertEquals($length, $response->headers->get('Content-Length'), 'Content-Length should be as if it was GET; see RFC2616 14.13');
    }

    public function testPrepareRemovesContentForInformationalResponse()
    {
        $response = new Response('foo');
        $request = Request::create('/');

        $response->setContent('content');
        $response->setStatusCode(101);
        $response->prepare($request);
        $this->assertEquals('', $response->getContent());

        $response->setContent('content');
        $response->setStatusCode(304);
        $response->prepare($request);
        $this->assertEquals('', $response->getContent());
    }

    public function testPrepareRemovesContentLength()
    {
        $response = new Response('foo');
        $request = Request::create('/');

        $response->headers->set('Content-Length', 12345);
        $response->prepare($request);
        $this->assertEquals(12345, $response->headers->get('Content-Length'));

        $response->headers->set('Transfer-Encoding', 'chunked');
        $response->prepare($request);
        $this->assertFalse($response->headers->has('Content-Length'));
    }

    public function testPrepareSetsPragmaOnHttp10Only()
    {
        $request = Request::create('/', 'GET');
        $request->server->set('SERVER_PROTOCOL', 'HTTP/1.0');

        $response = new Response('foo');
        $response->prepare($request);
        $this->assertEquals('no-cache', $response->headers->get('pragma'));
        $this->assertEquals('-1', $response->headers->get('expires'));

        $request->server->set('SERVER_PROTOCOL', 'HTTP/1.1');
        $response = new Response('foo');
        $response->prepare($request);
        $this->assertFalse($response->headers->has('pragma'));
        $this->assertFalse($response->headers->has('expires'));
    }

    public function testSetCache()
    {
        $response = new Response();
        //array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public')
        try {
            $response->setCache(array("wrong option" => "value"));
            $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported');
            $this->assertContains('"wrong option"', $e->getMessage());
        }

        $options = array('etag' => '"whatever"');
        $response->setCache($options);
        $this->assertEquals($response->getEtag(), '"whatever"');

        $now = new \DateTime();
        $options = array('last_modified' => $now);
        $response->setCache($options);
        $this->assertEquals($response->getLastModified()->getTimestamp(), $now->getTimestamp());

        $options = array('max_age' => 100);
        $response->setCache($options);
        $this->assertEquals($response->getMaxAge(), 100);

        $options = array('s_maxage' => 200);
        $response->setCache($options);
        $this->assertEquals($response->getMaxAge(), 200);

        $this->assertTrue($response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($response->headers->hasCacheControlDirective('private'));

        $response->setCache(array('public' => true));
        $this->assertTrue($response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($response->headers->hasCacheControlDirective('private'));

        $response->setCache(array('public' => false));
        $this->assertFalse($response->headers->hasCacheControlDirective('public'));
        $this->assertTrue($response->headers->hasCacheControlDirective('private'));

        $response->setCache(array('private' => true));
        $this->assertFalse($response->headers->hasCacheControlDirective('public'));
        $this->assertTrue($response->headers->hasCacheControlDirective('private'));

        $response->setCache(array('private' => false));
        $this->assertTrue($response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($response->headers->hasCacheControlDirective('private'));
    }

    public function testSendContent()
    {
        $response = new Response('test response rendering', 200);

        ob_start();
        $response->sendContent();
        $string = ob_get_clean();
        $this->assertContains('test response rendering', $string);
    }

    public function testSetPublic()
    {
        $response = new Response();
        $response->setPublic();

        $this->assertTrue($response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($response->headers->hasCacheControlDirective('private'));
    }

    public function testSetExpires()
    {
        $response = new Response();
        $response->setExpires(null);

        $this->assertNull($response->getExpires(), '->setExpires() remove the header when passed null');

        $now = new \DateTime();
        $response->setExpires($now);

        $this->assertEquals($response->getExpires()->getTimestamp(), $now->getTimestamp());
    }

    public function testSetLastModified()
    {
        $response = new Response();
        $response->setLastModified(new \DateTime());
        $this->assertNotNull($response->getLastModified());

        $response->setLastModified(null);
        $this->assertNull($response->getLastModified());
    }

    public function testIsInvalid()
    {
        $response = new Response();

        try {
            $response->setStatusCode(99);
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue($response->isInvalid());
        }

        try {
            $response->setStatusCode(650);
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue($response->isInvalid());
        }

        $response = new Response('', 200);
        $this->assertFalse($response->isInvalid());
    }

    /**
     * @dataProvider getStatusCodeFixtures
     */
    public function testSetStatusCode($code, $text, $expectedText)
    {
        $response = new Response();

        $response->setStatusCode($code, $text);

        $statusText = new \ReflectionProperty($response, 'statusText');
        $statusText->setAccessible(true);

        $this->assertEquals($expectedText, $statusText->getValue($response));
    }

    public function getStatusCodeFixtures()
    {
        return array(
            array('200', null, 'OK'),
            array('200', false, ''),
            array('200', 'foo', 'foo'),
            array('199', null, ''),
            array('199', false, ''),
            array('199', 'foo', 'foo')
        );
    }

    public function testIsInformational()
    {
        $response = new Response('', 100);
        $this->assertTrue($response->isInformational());

        $response = new Response('', 200);
        $this->assertFalse($response->isInformational());
    }

    public function testIsRedirectRedirection()
    {
        foreach (array(301, 302, 303, 307) as $code) {
            $response = new Response('', $code);
            $this->assertTrue($response->isRedirection());
            $this->assertTrue($response->isRedirect());
        }

        $response = new Response('', 304);
        $this->assertTrue($response->isRedirection());
        $this->assertFalse($response->isRedirect());

        $response = new Response('', 200);
        $this->assertFalse($response->isRedirection());
        $this->assertFalse($response->isRedirect());

        $response = new Response('', 404);
        $this->assertFalse($response->isRedirection());
        $this->assertFalse($response->isRedirect());

        $response = new Response('', 301, array('Location' => '/good-uri'));
        $this->assertFalse($response->isRedirect('/bad-uri'));
        $this->assertTrue($response->isRedirect('/good-uri'));
    }

    public function testIsNotFound()
    {
        $response = new Response('', 404);
        $this->assertTrue($response->isNotFound());

        $response = new Response('', 200);
        $this->assertFalse($response->isNotFound());
    }

    public function testIsEmpty()
    {
        foreach (array(201, 204, 304) as $code) {
            $response = new Response('', $code);
            $this->assertTrue($response->isEmpty());
        }

        $response = new Response('', 200);
        $this->assertFalse($response->isEmpty());
    }

    public function testIsForbidden()
    {
        $response = new Response('', 403);
        $this->assertTrue($response->isForbidden());

        $response = new Response('', 200);
        $this->assertFalse($response->isForbidden());
    }

    public function testIsOk()
    {
        $response = new Response('', 200);
        $this->assertTrue($response->isOk());

        $response = new Response('', 404);
        $this->assertFalse($response->isOk());
    }

    public function testIsServerOrClientError()
    {
        $response = new Response('', 404);
        $this->assertTrue($response->isClientError());
        $this->assertFalse($response->isServerError());

        $response = new Response('', 500);
        $this->assertFalse($response->isClientError());
        $this->assertTrue($response->isServerError());
    }

    public function testHasVary()
    {
        $response = new Response();
        $this->assertFalse($response->hasVary());

        $response->setVary('User-Agent');
        $this->assertTrue($response->hasVary());
    }

    public function testSetEtag()
    {
        $response = new Response('', 200, array('ETag' => '"12345"'));
        $response->setEtag();

        $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
    }

    /**
     * @dataProvider validContentProvider
     */
    public function testSetContent($content)
    {
        $response = new Response();
        $response->setContent($content);
        $this->assertEquals((string) $content, $response->getContent());
    }

    /**
     * @expectedException \UnexpectedValueException
     * @dataProvider invalidContentProvider
     */
    public function testSetContentInvalid($content)
    {
        $response = new Response();
        $response->setContent($content);
    }

    public function testSettersAreChainable()
    {
        $response = new Response();

        $setters = array(
            'setProtocolVersion' => '1.0',
            'setCharset' => 'UTF-8',
            'setPublic' => null,
            'setPrivate' => null,
            'setDate' => new \DateTime(),
            'expire' => null,
            'setMaxAge' => 1,
            'setSharedMaxAge' => 1,
            'setTtl' => 1,
            'setClientTtl' => 1,
        );

        foreach ($setters as $setter => $arg) {
            $this->assertEquals($response, $response->{$setter}($arg));
        }
    }

    public function validContentProvider()
    {
        return array(
            'obj'    => array(new StringableObject()),
            'string' => array('Foo'),
            'int'    => array(2),
        );
    }

    public function invalidContentProvider()
    {
        return array(
            'obj'   => array(new \stdClass),
            'array' => array(array()),
            'bool'   => array(true, '1'),
        );
    }

    protected function createDateTimeOneHourAgo()
    {
        $date = new \DateTime();

        return $date->sub(new \DateInterval('PT1H'));
    }

    protected function createDateTimeOneHourLater()
    {
        $date = new \DateTime();

        return $date->add(new \DateInterval('PT1H'));
    }

    protected function createDateTimeNow()
    {
        return new \DateTime();
    }

    protected function provideResponse()
    {
        return new Response();
    }
}

class StringableObject
{
    public function __toString()
    {
        return 'Foo';
    }
}
PK=1[Ak�B#B#JHttpFoundation/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\ParameterBag;

class ParameterBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::__construct
     */
    public function testConstructor()
    {
        $this->testAll();
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::all
     */
    public function testAll()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $bag->all(), '->all() gets all the input');
    }

    public function testKeys()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertEquals(array('foo'), $bag->keys());
    }

    public function testAdd()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $bag->add(array('bar' => 'bas'));
        $this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all());
    }

    public function testRemove()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $bag->add(array('bar' => 'bas'));
        $this->assertEquals(array('foo' => 'bar', 'bar' => 'bas'), $bag->all());
        $bag->remove('bar');
        $this->assertEquals(array('foo' => 'bar'), $bag->all());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::replace
     */
    public function testReplace()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));

        $bag->replace(array('FOO' => 'BAR'));
        $this->assertEquals(array('FOO' => 'BAR'), $bag->all(), '->replace() replaces the input with the argument');
        $this->assertFalse($bag->has('foo'), '->replace() overrides previously set the input');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::get
     */
    public function testGet()
    {
        $bag = new ParameterBag(array('foo' => 'bar', 'null' => null));

        $this->assertEquals('bar', $bag->get('foo'), '->get() gets the value of a parameter');
        $this->assertEquals('default', $bag->get('unknown', 'default'), '->get() returns second argument as default if a parameter is not defined');
        $this->assertNull($bag->get('null', 'default'), '->get() returns null if null is set');
    }

    public function testGetDoesNotUseDeepByDefault()
    {
        $bag = new ParameterBag(array('foo' => array('bar' => 'moo')));

        $this->assertNull($bag->get('foo[bar]'));
    }

    /**
     * @dataProvider getInvalidPaths
     * @expectedException \InvalidArgumentException
     */
    public function testGetDeepWithInvalidPaths($path)
    {
        $bag = new ParameterBag(array('foo' => array('bar' => 'moo')));

        $bag->get($path, null, true);
    }

    public function getInvalidPaths()
    {
        return array(
            array('foo[['),
            array('foo[d'),
            array('foo[bar]]'),
            array('foo[bar]d'),
        );
    }

    public function testGetDeep()
    {
        $bag = new ParameterBag(array('foo' => array('bar' => array('moo' => 'boo'))));

        $this->assertEquals(array('moo' => 'boo'), $bag->get('foo[bar]', null, true));
        $this->assertEquals('boo', $bag->get('foo[bar][moo]', null, true));
        $this->assertEquals('default', $bag->get('foo[bar][foo]', 'default', true));
        $this->assertEquals('default', $bag->get('bar[moo][foo]', 'default', true));
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::set
     */
    public function testSet()
    {
        $bag = new ParameterBag(array());

        $bag->set('foo', 'bar');
        $this->assertEquals('bar', $bag->get('foo'), '->set() sets the value of parameter');

        $bag->set('foo', 'baz');
        $this->assertEquals('baz', $bag->get('foo'), '->set() overrides previously set parameter');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::has
     */
    public function testHas()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));

        $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined');
        $this->assertFalse($bag->has('unknown'), '->has() return false if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::getAlpha
     */
    public function testGetAlpha()
    {
        $bag = new ParameterBag(array('word' => 'foo_BAR_012'));

        $this->assertEquals('fooBAR', $bag->getAlpha('word'), '->getAlpha() gets only alphabetic characters');
        $this->assertEquals('', $bag->getAlpha('unknown'), '->getAlpha() returns empty string if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::getAlnum
     */
    public function testGetAlnum()
    {
        $bag = new ParameterBag(array('word' => 'foo_BAR_012'));

        $this->assertEquals('fooBAR012', $bag->getAlnum('word'), '->getAlnum() gets only alphanumeric characters');
        $this->assertEquals('', $bag->getAlnum('unknown'), '->getAlnum() returns empty string if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::getDigits
     */
    public function testGetDigits()
    {
        $bag = new ParameterBag(array('word' => 'foo_BAR_012'));

        $this->assertEquals('012', $bag->getDigits('word'), '->getDigits() gets only digits as string');
        $this->assertEquals('', $bag->getDigits('unknown'), '->getDigits() returns empty string if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::getInt
     */
    public function testGetInt()
    {
        $bag = new ParameterBag(array('digits' => '0123'));

        $this->assertEquals(123, $bag->getInt('digits'), '->getInt() gets a value of parameter as integer');
        $this->assertEquals(0, $bag->getInt('unknown'), '->getInt() returns zero if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::filter
     */
    public function testFilter()
    {
        $bag = new ParameterBag(array(
            'digits' => '0123ab',
            'email' => 'example@example.com',
            'url' => 'http://example.com/foo',
            'dec' => '256',
            'hex' => '0x100',
            'array' => array('bang'),
            ));

        $this->assertEmpty($bag->filter('nokey'), '->filter() should return empty by default if no key is found');

        $this->assertEquals('0123', $bag->filter('digits', '', false, FILTER_SANITIZE_NUMBER_INT), '->filter() gets a value of parameter as integer filtering out invalid characters');

        $this->assertEquals('example@example.com', $bag->filter('email', '', false, FILTER_VALIDATE_EMAIL), '->filter() gets a value of parameter as email');

        $this->assertEquals('http://example.com/foo', $bag->filter('url', '', false, FILTER_VALIDATE_URL, array('flags' => FILTER_FLAG_PATH_REQUIRED)), '->filter() gets a value of parameter as URL with a path');

        // This test is repeated for code-coverage
        $this->assertEquals('http://example.com/foo', $bag->filter('url', '', false, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED), '->filter() gets a value of parameter as URL with a path');

        $this->assertFalse($bag->filter('dec', '', false, FILTER_VALIDATE_INT, array(
            'flags'   => FILTER_FLAG_ALLOW_HEX,
            'options' => array('min_range' => 1, 'max_range' => 0xff))
                ), '->filter() gets a value of parameter as integer between boundaries');

        $this->assertFalse($bag->filter('hex', '', false, FILTER_VALIDATE_INT, array(
            'flags'   => FILTER_FLAG_ALLOW_HEX,
            'options' => array('min_range' => 1, 'max_range' => 0xff))
                ), '->filter() gets a value of parameter as integer between boundaries');

        $this->assertEquals(array('bang'), $bag->filter('array', '', false), '->filter() gets a value of parameter as an array');

    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::getIterator
     */
    public function testGetIterator()
    {
        $parameters = array('foo' => 'bar', 'hello' => 'world');
        $bag = new ParameterBag($parameters);

        $i = 0;
        foreach ($bag as $key => $val) {
            $i++;
            $this->assertEquals($parameters[$key], $val);
        }

        $this->assertEquals(count($parameters), $i);
    }

    /**
     * @covers Symfony\Component\HttpFoundation\ParameterBag::count
     */
    public function testCount()
    {
        $parameters = array('foo' => 'bar', 'hello' => 'world');
        $bag = new ParameterBag($parameters);

        $this->assertEquals(count($parameters), count($bag));
    }
}
PK=1[��q��EHttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;

class RequestTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\HttpFoundation\Request::__construct
     */
    public function testConstructor()
    {
        $this->testInitialize();
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::initialize
     */
    public function testInitialize()
    {
        $request = new Request();

        $request->initialize(array('foo' => 'bar'));
        $this->assertEquals('bar', $request->query->get('foo'), '->initialize() takes an array of query parameters as its first argument');

        $request->initialize(array(), array('foo' => 'bar'));
        $this->assertEquals('bar', $request->request->get('foo'), '->initialize() takes an array of request parameters as its second argument');

        $request->initialize(array(), array(), array('foo' => 'bar'));
        $this->assertEquals('bar', $request->attributes->get('foo'), '->initialize() takes an array of attributes as its third argument');

        $request->initialize(array(), array(), array(), array(), array(), array('HTTP_FOO' => 'bar'));
        $this->assertEquals('bar', $request->headers->get('FOO'), '->initialize() takes an array of HTTP headers as its fourth argument');
    }

    public function testGetLocale()
    {
        $request = new Request();
        $request->setLocale('pl');
        $locale = $request->getLocale();
        $this->assertEquals('pl', $locale);
    }

    public function testGetUser()
    {
        $request = Request::create('http://user_test:password_test@test.com/');
        $user = $request->getUser();

        $this->assertEquals('user_test', $user);
    }

    public function testGetPassword()
    {
        $request = Request::create('http://user_test:password_test@test.com/');
        $password = $request->getPassword();

        $this->assertEquals('password_test', $password);
    }

    public function testIsNoCache()
    {
        $request = new Request();
        $isNoCache = $request->isNoCache();

        $this->assertFalse($isNoCache);
    }

    public function testGetContentType()
    {
        $request = new Request();
        $contentType = $request->getContentType();

        $this->assertNull($contentType);
    }

    public function testSetDefaultLocale()
    {
        $request = new Request();
        $request->setDefaultLocale('pl');
        $locale = $request->getLocale();

        $this->assertEquals('pl', $locale);
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::create
     */
    public function testCreate()
    {
        $request = Request::create('http://test.com/foo?bar=baz');
        $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('bar=baz', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com/foo', 'GET', array('bar' => 'baz'));
        $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('bar=baz', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com/foo?bar=foo', 'GET', array('bar' => 'baz'));
        $this->assertEquals('http://test.com/foo?bar=baz', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('bar=baz', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('https://test.com/foo?bar=baz');
        $this->assertEquals('https://test.com/foo?bar=baz', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('bar=baz', $request->getQueryString());
        $this->assertEquals(443, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertTrue($request->isSecure());

        $request = Request::create('test.com:90/foo');
        $this->assertEquals('http://test.com:90/foo', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('test.com', $request->getHost());
        $this->assertEquals('test.com:90', $request->getHttpHost());
        $this->assertEquals(90, $request->getPort());
        $this->assertFalse($request->isSecure());

        $request = Request::create('https://test.com:90/foo');
        $this->assertEquals('https://test.com:90/foo', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('test.com', $request->getHost());
        $this->assertEquals('test.com:90', $request->getHttpHost());
        $this->assertEquals(90, $request->getPort());
        $this->assertTrue($request->isSecure());

        $request = Request::create('https://127.0.0.1:90/foo');
        $this->assertEquals('https://127.0.0.1:90/foo', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('127.0.0.1', $request->getHost());
        $this->assertEquals('127.0.0.1:90', $request->getHttpHost());
        $this->assertEquals(90, $request->getPort());
        $this->assertTrue($request->isSecure());

        $request = Request::create('https://[::1]:90/foo');
        $this->assertEquals('https://[::1]:90/foo', $request->getUri());
        $this->assertEquals('/foo', $request->getPathInfo());
        $this->assertEquals('[::1]', $request->getHost());
        $this->assertEquals('[::1]:90', $request->getHttpHost());
        $this->assertEquals(90, $request->getPort());
        $this->assertTrue($request->isSecure());

        $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}';
        $request = Request::create('http://example.com/jsonrpc', 'POST', array(), array(), array(), array(), $json);
        $this->assertEquals($json, $request->getContent());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com');
        $this->assertEquals('http://test.com/', $request->getUri());
        $this->assertEquals('/', $request->getPathInfo());
        $this->assertEquals('', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com?test=1');
        $this->assertEquals('http://test.com/?test=1', $request->getUri());
        $this->assertEquals('/', $request->getPathInfo());
        $this->assertEquals('test=1', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com:90/?test=1');
        $this->assertEquals('http://test.com:90/?test=1', $request->getUri());
        $this->assertEquals('/', $request->getPathInfo());
        $this->assertEquals('test=1', $request->getQueryString());
        $this->assertEquals(90, $request->getPort());
        $this->assertEquals('test.com:90', $request->getHttpHost());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test:test@test.com');
        $this->assertEquals('http://test.com/', $request->getUri());
        $this->assertEquals('/', $request->getPathInfo());
        $this->assertEquals('', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertEquals('test', $request->getUser());
        $this->assertEquals('test', $request->getPassword());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://testnopass@test.com');
        $this->assertEquals('http://test.com/', $request->getUri());
        $this->assertEquals('/', $request->getPathInfo());
        $this->assertEquals('', $request->getQueryString());
        $this->assertEquals(80, $request->getPort());
        $this->assertEquals('test.com', $request->getHttpHost());
        $this->assertEquals('testnopass', $request->getUser());
        $this->assertNull($request->getPassword());
        $this->assertFalse($request->isSecure());

        $request = Request::create('http://test.com/?foo');
        $this->assertEquals('/?foo', $request->getRequestUri());
        $this->assertEquals(array('foo' => ''), $request->query->all());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::create
     */
    public function testCreateCheckPrecedence()
    {
        // server is used by default
        $request = Request::create('/', 'DELETE', array(), array(), array(), array(
            'HTTP_HOST'     => 'example.com',
            'HTTPS'         => 'on',
            'SERVER_PORT'   => 443,
            'PHP_AUTH_USER' => 'fabien',
            'PHP_AUTH_PW'   => 'pa$$',
            'QUERY_STRING'  => 'foo=bar',
            'CONTENT_TYPE'  => 'application/json',
        ));
        $this->assertEquals('example.com', $request->getHost());
        $this->assertEquals(443, $request->getPort());
        $this->assertTrue($request->isSecure());
        $this->assertEquals('fabien', $request->getUser());
        $this->assertEquals('pa$$', $request->getPassword());
        $this->assertEquals('', $request->getQueryString());
        $this->assertEquals('application/json', $request->headers->get('CONTENT_TYPE'));

        // URI has precedence over server
        $request = Request::create('http://thomas:pokemon@example.net:8080/?foo=bar', 'GET', array(), array(), array(), array(
            'HTTP_HOST'   => 'example.com',
            'HTTPS'       => 'on',
            'SERVER_PORT' => 443,
        ));
        $this->assertEquals('example.net', $request->getHost());
        $this->assertEquals(8080, $request->getPort());
        $this->assertFalse($request->isSecure());
        $this->assertEquals('thomas', $request->getUser());
        $this->assertEquals('pokemon', $request->getPassword());
        $this->assertEquals('foo=bar', $request->getQueryString());
    }

    public function testDuplicate()
    {
        $request = new Request(array('foo' => 'bar'), array('foo' => 'bar'), array('foo' => 'bar'), array(), array(), array('HTTP_FOO' => 'bar'));
        $dup = $request->duplicate();

        $this->assertEquals($request->query->all(), $dup->query->all(), '->duplicate() duplicates a request an copy the current query parameters');
        $this->assertEquals($request->request->all(), $dup->request->all(), '->duplicate() duplicates a request an copy the current request parameters');
        $this->assertEquals($request->attributes->all(), $dup->attributes->all(), '->duplicate() duplicates a request an copy the current attributes');
        $this->assertEquals($request->headers->all(), $dup->headers->all(), '->duplicate() duplicates a request an copy the current HTTP headers');

        $dup = $request->duplicate(array('foo' => 'foobar'), array('foo' => 'foobar'), array('foo' => 'foobar'), array(), array(), array('HTTP_FOO' => 'foobar'));

        $this->assertEquals(array('foo' => 'foobar'), $dup->query->all(), '->duplicate() overrides the query parameters if provided');
        $this->assertEquals(array('foo' => 'foobar'), $dup->request->all(), '->duplicate() overrides the request parameters if provided');
        $this->assertEquals(array('foo' => 'foobar'), $dup->attributes->all(), '->duplicate() overrides the attributes if provided');
        $this->assertEquals(array('foo' => array('foobar')), $dup->headers->all(), '->duplicate() overrides the HTTP header if provided');
    }

    public function testDuplicateWithFormat()
    {
        $request = new Request(array(), array(), array('_format' => 'json'));
        $dup = $request->duplicate();

        $this->assertEquals('json', $dup->getRequestFormat());
        $this->assertEquals('json', $dup->attributes->get('_format'));

        $request = new Request();
        $request->setRequestFormat('xml');
        $dup = $request->duplicate();

        $this->assertEquals('xml', $dup->getRequestFormat());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getFormat
     * @covers Symfony\Component\HttpFoundation\Request::setFormat
     * @dataProvider getFormatToMimeTypeMapProvider
     */
    public function testGetFormatFromMimeType($format, $mimeTypes)
    {
        $request = new Request();
        foreach ($mimeTypes as $mime) {
            $this->assertEquals($format, $request->getFormat($mime));
        }
        $request->setFormat($format, $mimeTypes);
        foreach ($mimeTypes as $mime) {
            $this->assertEquals($format, $request->getFormat($mime));
        }
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getFormat
     */
    public function testGetFormatFromMimeTypeWithParameters()
    {
        $request = new Request();
        $this->assertEquals('json', $request->getFormat('application/json; charset=utf-8'));
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getMimeType
     * @dataProvider getFormatToMimeTypeMapProvider
     */
    public function testGetMimeTypeFromFormat($format, $mimeTypes)
    {
        if (null !== $format) {
            $request = new Request();
            $this->assertEquals($mimeTypes[0], $request->getMimeType($format));
        }
    }

    public function getFormatToMimeTypeMapProvider()
    {
        return array(
            array(null, array(null, 'unexistent-mime-type')),
            array('txt', array('text/plain')),
            array('js', array('application/javascript', 'application/x-javascript', 'text/javascript')),
            array('css', array('text/css')),
            array('json', array('application/json', 'application/x-json')),
            array('xml', array('text/xml', 'application/xml', 'application/x-xml')),
            array('rdf', array('application/rdf+xml')),
            array('atom',array('application/atom+xml')),
        );
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getUri
     */
    public function testGetUri()
    {
        $server = array();

        // Standard Request on non default PORT
        // http://host:8080/index.php/path/info?query=string

        $server['HTTP_HOST'] = 'host:8080';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '8080';

        $server['QUERY_STRING'] = 'query=string';
        $server['REQUEST_URI'] = '/index.php/path/info?query=string';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['PATH_INFO'] = '/path/info';
        $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info';
        $server['PHP_SELF'] = '/index_dev.php/path/info';
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';

        $request = new Request();

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://host:8080/index.php/path/info?query=string', $request->getUri(), '->getUri() with non default port');

        // Use std port number
        $server['HTTP_HOST'] = 'host';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://host/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port');

        // Without HOST HEADER
        unset($server['HTTP_HOST']);
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://servername/index.php/path/info?query=string', $request->getUri(), '->getUri() with default port without HOST_HEADER');

        // Request with URL REWRITING (hide index.php)
        //   RewriteCond %{REQUEST_FILENAME} !-f
        //   RewriteRule ^(.*)$ index.php [QSA,L]
        // http://host:8080/path/info?query=string
        $server = array();
        $server['HTTP_HOST'] = 'host:8080';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '8080';

        $server['REDIRECT_QUERY_STRING'] = 'query=string';
        $server['REDIRECT_URL'] = '/path/info';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['QUERY_STRING'] = 'query=string';
        $server['REQUEST_URI'] = '/path/info?toto=test&1=1';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['PHP_SELF'] = '/index.php';
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';

        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://host:8080/path/info?query=string', $request->getUri(), '->getUri() with rewrite');

        // Use std port number
        //  http://host/path/info?query=string
        $server['HTTP_HOST'] = 'host';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://host/path/info?query=string', $request->getUri(), '->getUri() with rewrite and default port');

        // Without HOST HEADER
        unset($server['HTTP_HOST']);
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://servername/path/info?query=string', $request->getUri(), '->getUri() with rewrite, default port without HOST_HEADER');

        // With encoded characters

        $server = array(
            'HTTP_HOST'       => 'host:8080',
            'SERVER_NAME'     => 'servername',
            'SERVER_PORT'     => '8080',
            'QUERY_STRING'    => 'query=string',
            'REQUEST_URI'     => '/ba%20se/index_dev.php/foo%20bar/in+fo?query=string',
            'SCRIPT_NAME'     => '/ba se/index_dev.php',
            'PATH_TRANSLATED' => 'redirect:/index.php/foo bar/in+fo',
            'PHP_SELF'        => '/ba se/index_dev.php/path/info',
            'SCRIPT_FILENAME' => '/some/where/ba se/index_dev.php',
        );

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals(
            'http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string',
            $request->getUri()
        );

        // with user info

        $server['PHP_AUTH_USER'] = 'fabien';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri());

        $server['PHP_AUTH_PW'] = 'symfony';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://host:8080/ba%20se/index_dev.php/foo%20bar/in+fo?query=string', $request->getUri());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getUriForPath
     */
    public function testGetUriForPath()
    {
        $request = Request::create('http://test.com/foo?bar=baz');
        $this->assertEquals('http://test.com/some/path', $request->getUriForPath('/some/path'));

        $request = Request::create('http://test.com:90/foo?bar=baz');
        $this->assertEquals('http://test.com:90/some/path', $request->getUriForPath('/some/path'));

        $request = Request::create('https://test.com/foo?bar=baz');
        $this->assertEquals('https://test.com/some/path', $request->getUriForPath('/some/path'));

        $request = Request::create('https://test.com:90/foo?bar=baz');
        $this->assertEquals('https://test.com:90/some/path', $request->getUriForPath('/some/path'));

        $server = array();

        // Standard Request on non default PORT
        // http://host:8080/index.php/path/info?query=string

        $server['HTTP_HOST'] = 'host:8080';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '8080';

        $server['QUERY_STRING'] = 'query=string';
        $server['REQUEST_URI'] = '/index.php/path/info?query=string';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['PATH_INFO'] = '/path/info';
        $server['PATH_TRANSLATED'] = 'redirect:/index.php/path/info';
        $server['PHP_SELF'] = '/index_dev.php/path/info';
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';

        $request = new Request();

        $request->initialize(array(), array(), array(), array(), array(),$server);

        $this->assertEquals('http://host:8080/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with non default port');

        // Use std port number
        $server['HTTP_HOST'] = 'host';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://host/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port');

        // Without HOST HEADER
        unset($server['HTTP_HOST']);
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://servername/index.php/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with default port without HOST_HEADER');

        // Request with URL REWRITING (hide index.php)
        //   RewriteCond %{REQUEST_FILENAME} !-f
        //   RewriteRule ^(.*)$ index.php [QSA,L]
        // http://host:8080/path/info?query=string
        $server = array();
        $server['HTTP_HOST'] = 'host:8080';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '8080';

        $server['REDIRECT_QUERY_STRING'] = 'query=string';
        $server['REDIRECT_URL'] = '/path/info';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['QUERY_STRING'] = 'query=string';
        $server['REQUEST_URI'] = '/path/info?toto=test&1=1';
        $server['SCRIPT_NAME'] = '/index.php';
        $server['PHP_SELF'] = '/index.php';
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';

        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://host:8080/some/path', $request->getUriForPath('/some/path'), '->getUri() with rewrite');

        // Use std port number
        //  http://host/path/info?query=string
        $server['HTTP_HOST'] = 'host';
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://host/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite and default port');

        // Without HOST HEADER
        unset($server['HTTP_HOST']);
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '80';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'), '->getUriForPath() with rewrite, default port without HOST_HEADER');
        $this->assertEquals('servername', $request->getHttpHost());

        // with user info

        $server['PHP_AUTH_USER'] = 'fabien';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));

        $server['PHP_AUTH_PW'] = 'symfony';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername/some/path', $request->getUriForPath('/some/path'));
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getUserInfo
     */
    public function testGetUserInfo()
    {
        $request = new Request();

        $server['PHP_AUTH_USER'] = 'fabien';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('fabien', $request->getUserInfo());

        $server['PHP_AUTH_USER'] = '0';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('0', $request->getUserInfo());

        $server['PHP_AUTH_PW'] = '0';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('0:0', $request->getUserInfo());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getSchemeAndHttpHost
     */
    public function testGetSchemeAndHttpHost()
    {
        $request = new Request();

        $server = array();
        $server['SERVER_NAME'] = 'servername';
        $server['SERVER_PORT'] = '90';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());

        $server['PHP_AUTH_USER'] = 'fabien';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());

        $server['PHP_AUTH_USER'] = '0';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());

        $server['PHP_AUTH_PW'] = '0';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('http://servername:90', $request->getSchemeAndHttpHost());
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::getQueryString
     * @covers Symfony\Component\HttpFoundation\Request::normalizeQueryString
     * @dataProvider getQueryStringNormalizationData
     */
    public function testGetQueryString($query, $expectedQuery, $msg)
    {
        $request = new Request();

        $request->server->set('QUERY_STRING', $query);
        $this->assertSame($expectedQuery, $request->getQueryString(), $msg);
    }

    public function getQueryStringNormalizationData()
    {
        return array(
            array('foo', 'foo', 'works with valueless parameters'),
            array('foo=', 'foo=', 'includes a dangling equal sign'),
            array('bar=&foo=bar', 'bar=&foo=bar', '->works with empty parameters'),
            array('foo=bar&bar=', 'bar=&foo=bar', 'sorts keys alphabetically'),

            // GET parameters, that are submitted from a HTML form, encode spaces as "+" by default (as defined in enctype application/x-www-form-urlencoded).
            // PHP also converts "+" to spaces when filling the global _GET or when using the function parse_str.
            array('him=John%20Doe&her=Jane+Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes spaces in both encodings "%20" and "+"'),

            array('foo[]=1&foo[]=2', 'foo%5B%5D=1&foo%5B%5D=2', 'allows array notation'),
            array('foo=1&foo=2', 'foo=1&foo=2', 'allows repeated parameters'),
            array('pa%3Dram=foo%26bar%3Dbaz&test=test', 'pa%3Dram=foo%26bar%3Dbaz&test=test', 'works with encoded delimiters'),
            array('0', '0', 'allows "0"'),
            array('Jane Doe&John%20Doe', 'Jane%20Doe&John%20Doe', 'normalizes encoding in keys'),
            array('her=Jane Doe&him=John%20Doe', 'her=Jane%20Doe&him=John%20Doe', 'normalizes encoding in values'),
            array('foo=bar&&&test&&', 'foo=bar&test', 'removes unneeded delimiters'),
            array('formula=e=m*c^2', 'formula=e%3Dm%2Ac%5E2', 'correctly treats only the first "=" as delimiter and the next as value'),

            // Ignore pairs with empty key, even if there was a value, e.g. "=value", as such nameless values cannot be retrieved anyway.
            // PHP also does not include them when building _GET.
            array('foo=bar&=a=b&=x=y', 'foo=bar', 'removes params with empty key'),
        );
    }

    public function testGetQueryStringReturnsNull()
    {
        $request = new Request();

        $this->assertNull($request->getQueryString(), '->getQueryString() returns null for non-existent query string');

        $request->server->set('QUERY_STRING', '');
        $this->assertNull($request->getQueryString(), '->getQueryString() returns null for empty query string');
    }

    public function testGetHost()
    {
        $request = new Request();

        $request->initialize(array('foo' => 'bar'));
        $this->assertEquals('', $request->getHost(), '->getHost() return empty string if not initialized');

        $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com'));
        $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header');

        // Host header with port number
        $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.example.com:8080'));
        $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from Host Header with port number');

        // Server values
        $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com'));
        $this->assertEquals('www.example.com', $request->getHost(), '->getHost() from server name');

        $request->initialize(array(), array(), array(), array(), array(), array('SERVER_NAME' => 'www.example.com', 'HTTP_HOST' => 'www.host.com'));
        $this->assertEquals('www.host.com', $request->getHost(), '->getHost() value from Host header has priority over SERVER_NAME ');
    }

    public function testGetPort()
    {
        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'https',
            'HTTP_X_FORWARDED_PORT' => '443'
        ));
        $port = $request->getPort();

        $this->assertEquals(80, $port, 'Without trusted proxies FORWARDED_PROTO and FORWARDED_PORT are ignored.');

        Request::setTrustedProxies(array('1.1.1.1'));
        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'https',
            'HTTP_X_FORWARDED_PORT'  => '8443'
        ));
        $port = $request->getPort();

        $this->assertEquals(8443, $port, 'With PROTO and PORT set PORT takes precedence.');

        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'https'
        ));
        $port = $request->getPort();

        $this->assertEquals(443, $port, 'With only PROTO set getPort() defaults to 443.');

        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'http'
        ));
        $port = $request->getPort();

        $this->assertEquals(80, $port, 'If X_FORWARDED_PROTO is set to HTTP return 80.');

        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'On'
        ));
        $port = $request->getPort();
        $this->assertEquals(443, $port, 'With only PROTO set and value is On, getPort() defaults to 443.');

        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => '1'
        ));
        $port = $request->getPort();
        $this->assertEquals(443, $port, 'With only PROTO set and value is 1, getPort() defaults to 443.');

        $request = Request::create('http://example.com', 'GET', array(), array(), array(), array(
            'HTTP_X_FORWARDED_PROTO' => 'something-else'
        ));
        $port = $request->getPort();
        $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.');

        Request::setTrustedProxies(array());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testGetHostWithFakeHttpHostValue()
    {
        $request = new Request();
        $request->initialize(array(), array(), array(), array(), array(), array('HTTP_HOST' => 'www.host.com?query=string'));
        $request->getHost();
    }

    /**
     * @covers Symfony\Component\HttpFoundation\Request::setMethod
     * @covers Symfony\Component\HttpFoundation\Request::getMethod
     */
    public function testGetSetMethod()
    {
        $request = new Request();

        $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns GET if no method is defined');

        $request->setMethod('get');
        $this->assertEquals('GET', $request->getMethod(), '->getMethod() returns an uppercased string');

        $request->setMethod('PURGE');
        $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method even if it is not a standard one');

        $request->setMethod('POST');
        $this->assertEquals('POST', $request->getMethod(), '->getMethod() returns the method POST if no _method is defined');

        $request->setMethod('POST');
        $request->request->set('_method', 'purge');
        $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');

        $request = new Request();
        $request->setMethod('POST');
        $request->request->set('_method', 'purge');

        $this->assertFalse(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be disabled by default');

        Request::enableHttpMethodParameterOverride();

        $this->assertTrue(Request::getHttpMethodParameterOverride(), 'httpMethodParameterOverride should be enabled now but it is not');

        $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
        $this->disableHttpMethodParameterOverride();

        $request = new Request();
        $request->setMethod('POST');
        $request->query->set('_method', 'purge');
        $this->assertEquals('POST', $request->getMethod(), '->getMethod() does not return the method from _method if defined and POST but support not enabled');

        $request = new Request();
        $request->setMethod('POST');
        $request->query->set('_method', 'purge');
        Request::enableHttpMethodParameterOverride();
        $this->assertEquals('PURGE', $request->getMethod(), '->getMethod() returns the method from _method if defined and POST');
        $this->disableHttpMethodParameterOverride();

        $request = new Request();
        $request->setMethod('POST');
        $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
        $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override even though _method is set if defined and POST');

        $request = new Request();
        $request->setMethod('POST');
        $request->headers->set('X-HTTP-METHOD-OVERRIDE', 'delete');
        $this->assertEquals('DELETE', $request->getMethod(), '->getMethod() returns the method from X-HTTP-Method-Override if defined and POST');
    }

    /**
     * @dataProvider testGetClientIpsProvider
     */
    public function testGetClientIp($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
    {
        $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);

        $this->assertEquals($expected[0], $request->getClientIp());

        Request::setTrustedProxies(array());
    }

    /**
     * @dataProvider testGetClientIpsProvider
     */
    public function testGetClientIps($expected, $remoteAddr, $httpForwardedFor, $trustedProxies)
    {
        $request = $this->getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies);

        $this->assertEquals($expected, $request->getClientIps());

        Request::setTrustedProxies(array());
    }

    public function testGetClientIpsProvider()
    {
        //        $expected                   $remoteAddr                $httpForwardedFor            $trustedProxies
        return array(
            // simple IPv4
            array(array('88.88.88.88'),              '88.88.88.88',              null,                        null),
            // trust the IPv4 remote addr
            array(array('88.88.88.88'),              '88.88.88.88',              null,                        array('88.88.88.88')),

            // simple IPv6
            array(array('::1'),                      '::1',                      null,                        null),
            // trust the IPv6 remote addr
            array(array('::1'),                      '::1',                      null,                        array('::1')),

            // forwarded for with remote IPv4 addr not trusted
            array(array('127.0.0.1'),                '127.0.0.1',                '88.88.88.88',               null),
            // forwarded for with remote IPv4 addr trusted
            array(array('88.88.88.88'),              '127.0.0.1',                '88.88.88.88',               array('127.0.0.1')),
            // forwarded for with remote IPv4 and all FF addrs trusted
            array(array('88.88.88.88'),              '127.0.0.1',                '88.88.88.88',               array('127.0.0.1', '88.88.88.88')),
            // forwarded for with remote IPv4 range trusted
            array(array('88.88.88.88'),              '123.45.67.89',             '88.88.88.88',               array('123.45.67.0/24')),

            // forwarded for with remote IPv6 addr not trusted
            array(array('1620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3',  null),
            // forwarded for with remote IPv6 addr trusted
            array(array('2620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3',  array('1620:0:1cfe:face:b00c::3')),
            // forwarded for with remote IPv6 range trusted
            array(array('88.88.88.88'),              '2a01:198:603:0:396e:4789:8e99:890f', '88.88.88.88',     array('2a01:198:603:0::/65')),

            // multiple forwarded for with remote IPv4 addr trusted
            array(array('88.88.88.88', '87.65.43.21', '127.0.0.1'), '123.45.67.89', '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89')),
            // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted
            array(array('87.65.43.21', '127.0.0.1'), '123.45.67.89',             '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '88.88.88.88')),
            // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
            array(array('88.88.88.88', '127.0.0.1'), '123.45.67.89',             '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21')),
            // multiple forwarded for with remote IPv4 addr and all reverse proxies trusted
            array(array('127.0.0.1'),                '123.45.67.89',             '127.0.0.1, 87.65.43.21, 88.88.88.88', array('123.45.67.89', '87.65.43.21', '88.88.88.88', '127.0.0.1')),

            // multiple forwarded for with remote IPv6 addr trusted
            array(array('2620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3')),
            // multiple forwarded for with remote IPv6 addr and some reverse proxies trusted
            array(array('3620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '2620:0:1cfe:face:b00c::3')),
            // multiple forwarded for with remote IPv4 addr and some reverse proxies trusted but in the middle
            array(array('2620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3'), '1620:0:1cfe:face:b00c::3', '4620:0:1cfe:face:b00c::3,3620:0:1cfe:face:b00c::3,2620:0:1cfe:face:b00c::3', array('1620:0:1cfe:face:b00c::3', '3620:0:1cfe:face:b00c::3')),
        );
    }

    public function testGetContentWorksTwiceInDefaultMode()
    {
        $req = new Request();
        $this->assertEquals('', $req->getContent());
        $this->assertEquals('', $req->getContent());
    }

    public function testGetContentReturnsResource()
    {
        $req = new Request();
        $retval = $req->getContent(true);
        $this->assertInternalType('resource', $retval);
        $this->assertEquals("", fread($retval, 1));
        $this->assertTrue(feof($retval));
    }

    /**
     * @expectedException \LogicException
     * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider
     */
    public function testGetContentCantBeCalledTwiceWithResources($first, $second)
    {
        $req = new Request();
        $req->getContent($first);
        $req->getContent($second);
    }

    public function getContentCantBeCalledTwiceWithResourcesProvider()
    {
        return array(
            'Resource then fetch' => array(true, false),
            'Resource then resource' => array(true, true),
            'Fetch then resource' => array(false, true),
        );
    }

    public function provideOverloadedMethods()
    {
        return array(
            array('PUT'),
            array('DELETE'),
            array('PATCH'),
            array('put'),
            array('delete'),
            array('patch'),

        );
    }

    /**
     * @dataProvider provideOverloadedMethods
     */
    public function testCreateFromGlobals($method)
    {
        $normalizedMethod = strtoupper($method);

        $_GET['foo1']    = 'bar1';
        $_POST['foo2']   = 'bar2';
        $_COOKIE['foo3'] = 'bar3';
        $_FILES['foo4']  = array('bar4');
        $_SERVER['foo5'] = 'bar5';

        $request = Request::createFromGlobals();
        $this->assertEquals('bar1', $request->query->get('foo1'), '::fromGlobals() uses values from $_GET');
        $this->assertEquals('bar2', $request->request->get('foo2'), '::fromGlobals() uses values from $_POST');
        $this->assertEquals('bar3', $request->cookies->get('foo3'), '::fromGlobals() uses values from $_COOKIE');
        $this->assertEquals(array('bar4'), $request->files->get('foo4'), '::fromGlobals() uses values from $_FILES');
        $this->assertEquals('bar5', $request->server->get('foo5'), '::fromGlobals() uses values from $_SERVER');

        unset($_GET['foo1'], $_POST['foo2'], $_COOKIE['foo3'], $_FILES['foo4'], $_SERVER['foo5']);

        $_SERVER['REQUEST_METHOD'] = $method;
        $_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
        $request = RequestContentProxy::createFromGlobals();
        $this->assertEquals($normalizedMethod, $request->getMethod());
        $this->assertEquals('mycontent', $request->request->get('content'));

        unset($_SERVER['REQUEST_METHOD'], $_SERVER['CONTENT_TYPE']);

        Request::createFromGlobals();
        Request::enableHttpMethodParameterOverride();
        $_POST['_method']   = $method;
        $_POST['foo6']      = 'bar6';
        $_SERVER['REQUEST_METHOD'] = 'PoSt';
        $request = Request::createFromGlobals();
        $this->assertEquals($normalizedMethod, $request->getMethod());
        $this->assertEquals('POST', $request->getRealMethod());
        $this->assertEquals('bar6', $request->request->get('foo6'));

        unset($_POST['_method'], $_POST['foo6'], $_SERVER['REQUEST_METHOD']);
        $this->disableHttpMethodParameterOverride();
    }

    public function testOverrideGlobals()
    {
        $request = new Request();
        $request->initialize(array('foo' => 'bar'));

        // as the Request::overrideGlobals really work, it erase $_SERVER, so we must backup it
        $server = $_SERVER;

        $request->overrideGlobals();

        $this->assertEquals(array('foo' => 'bar'), $_GET);

        $request->initialize(array(), array('foo' => 'bar'));
        $request->overrideGlobals();

        $this->assertEquals(array('foo' => 'bar'), $_POST);

        $this->assertArrayNotHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);

        $request->headers->set('X_FORWARDED_PROTO', 'https');

        Request::setTrustedProxies(array('1.1.1.1'));
        $this->assertTrue($request->isSecure());
        Request::setTrustedProxies(array());

        $request->overrideGlobals();

        $this->assertArrayHasKey('HTTP_X_FORWARDED_PROTO', $_SERVER);

        $request->headers->set('CONTENT_TYPE', 'multipart/form-data');
        $request->headers->set('CONTENT_LENGTH', 12345);
        $request->overrideGlobals();
        $this->assertArrayHasKey('CONTENT_TYPE', $_SERVER);
        $this->assertArrayHasKey('CONTENT_LENGTH', $_SERVER);

        // restore initial $_SERVER array
        $_SERVER = $server;
    }

    public function testGetScriptName()
    {
        $request = new Request();
        $this->assertEquals('', $request->getScriptName());

        $server = array();
        $server['SCRIPT_NAME'] = '/index.php';

        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('/index.php', $request->getScriptName());

        $server = array();
        $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('/frontend.php', $request->getScriptName());

        $server = array();
        $server['SCRIPT_NAME'] = '/index.php';
        $server['ORIG_SCRIPT_NAME'] = '/frontend.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('/index.php', $request->getScriptName());
    }

    public function testGetBasePath()
    {
        $request = new Request();
        $this->assertEquals('', $request->getBasePath());

        $server = array();
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);
        $this->assertEquals('', $request->getBasePath());

        $server = array();
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';
        $server['SCRIPT_NAME'] = '/index.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('', $request->getBasePath());

        $server = array();
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';
        $server['PHP_SELF'] = '/index.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('', $request->getBasePath());

        $server = array();
        $server['SCRIPT_FILENAME'] = '/some/where/index.php';
        $server['ORIG_SCRIPT_NAME'] = '/index.php';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('', $request->getBasePath());
    }

    public function testGetPathInfo()
    {
        $request = new Request();
        $this->assertEquals('/', $request->getPathInfo());

        $server = array();
        $server['REQUEST_URI'] = '/path/info';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('/path/info', $request->getPathInfo());

        $server = array();
        $server['REQUEST_URI'] = '/path%20test/info';
        $request->initialize(array(), array(), array(), array(), array(), $server);

        $this->assertEquals('/path%20test/info', $request->getPathInfo());
    }

    public function testGetPreferredLanguage()
    {
        $request = new Request();
        $this->assertNull($request->getPreferredLanguage());
        $this->assertNull($request->getPreferredLanguage(array()));
        $this->assertEquals('fr', $request->getPreferredLanguage(array('fr')));
        $this->assertEquals('fr', $request->getPreferredLanguage(array('fr', 'en')));
        $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'fr')));
        $this->assertEquals('fr-ch', $request->getPreferredLanguage(array('fr-ch', 'fr-fr')));

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
        $this->assertEquals('en', $request->getPreferredLanguage(array('en', 'en-us')));

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
        $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8');
        $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5');
        $this->assertEquals('en', $request->getPreferredLanguage(array('fr', 'en')));
    }

    public function testIsXmlHttpRequest()
    {
        $request = new Request();
        $this->assertFalse($request->isXmlHttpRequest());

        $request->headers->set('X-Requested-With', 'XMLHttpRequest');
        $this->assertTrue($request->isXmlHttpRequest());

        $request->headers->remove('X-Requested-With');
        $this->assertFalse($request->isXmlHttpRequest());
    }

    public function testIntlLocale()
    {
        if (!extension_loaded('intl')) {
            $this->markTestSkipped('The intl extension is needed to run this test.');
        }

        $request = new Request();

        $request->setDefaultLocale('fr');
        $this->assertEquals('fr', $request->getLocale());
        $this->assertEquals('fr', \Locale::getDefault());

        $request->setLocale('en');
        $this->assertEquals('en', $request->getLocale());
        $this->assertEquals('en', \Locale::getDefault());

        $request->setDefaultLocale('de');
        $this->assertEquals('en', $request->getLocale());
        $this->assertEquals('en', \Locale::getDefault());
    }

    public function testGetCharsets()
    {
        $request = new Request();
        $this->assertEquals(array(), $request->getCharsets());
        $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
        $this->assertEquals(array(), $request->getCharsets()); // testing caching

        $request = new Request();
        $request->headers->set('Accept-Charset', 'ISO-8859-1, US-ASCII, UTF-8; q=0.8, ISO-10646-UCS-2; q=0.6');
        $this->assertEquals(array('ISO-8859-1', 'US-ASCII', 'UTF-8', 'ISO-10646-UCS-2'), $request->getCharsets());

        $request = new Request();
        $request->headers->set('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7');
        $this->assertEquals(array('ISO-8859-1', 'utf-8', '*'), $request->getCharsets());
    }

    public function testGetEncodings()
    {
        $request = new Request();
        $this->assertEquals(array(), $request->getEncodings());
        $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
        $this->assertEquals(array(), $request->getEncodings()); // testing caching

        $request = new Request();
        $request->headers->set('Accept-Encoding', 'gzip,deflate,sdch');
        $this->assertEquals(array('gzip', 'deflate', 'sdch'), $request->getEncodings());

        $request = new Request();
        $request->headers->set('Accept-Encoding', 'gzip;q=0.4,deflate;q=0.9,compress;q=0.7');
        $this->assertEquals(array('deflate', 'compress', 'gzip'), $request->getEncodings());
    }

    public function testGetAcceptableContentTypes()
    {
        $request = new Request();
        $this->assertEquals(array(), $request->getAcceptableContentTypes());
        $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
        $this->assertEquals(array(), $request->getAcceptableContentTypes()); // testing caching

        $request = new Request();
        $request->headers->set('Accept', 'application/vnd.wap.wmlscriptc, text/vnd.wap.wml, application/vnd.wap.xhtml+xml, application/xhtml+xml, text/html, multipart/mixed, */*');
        $this->assertEquals(array('application/vnd.wap.wmlscriptc', 'text/vnd.wap.wml', 'application/vnd.wap.xhtml+xml', 'application/xhtml+xml', 'text/html', 'multipart/mixed', '*/*'), $request->getAcceptableContentTypes());
    }

    public function testGetLanguages()
    {
        $request = new Request();
        $this->assertEquals(array(), $request->getLanguages());

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');
        $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());
        $this->assertEquals(array('zh', 'en_US', 'en'), $request->getLanguages());

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8');
        $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test out of order qvalues

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en, en-us');
        $this->assertEquals(array('zh', 'en', 'en_US'), $request->getLanguages()); // Test equal weighting without qvalues

        $request = new Request();
        $request->headers->set('Accept-language', 'zh; q=0.6, en, en-us; q=0.6');
        $this->assertEquals(array('en', 'zh', 'en_US'), $request->getLanguages()); // Test equal weighting with qvalues

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, i-cherokee; q=0.6');
        $this->assertEquals(array('zh', 'cherokee'), $request->getLanguages());
    }

    public function testGetRequestFormat()
    {
        $request = new Request();
        $this->assertEquals('html', $request->getRequestFormat());

        $request = new Request();
        $this->assertNull($request->getRequestFormat(null));

        $request = new Request();
        $this->assertNull($request->setRequestFormat('foo'));
        $this->assertEquals('foo', $request->getRequestFormat(null));
    }

    public function testHasSession()
    {
        $request = new Request();

        $this->assertFalse($request->hasSession());
        $request->setSession(new Session(new MockArraySessionStorage()));
        $this->assertTrue($request->hasSession());
    }

    public function testGetSession()
    {
        $request = new Request();

        $request->setSession(new Session(new MockArraySessionStorage()));
        $this->assertTrue($request->hasSession());

        $session = $request->getSession();
        $this->assertObjectHasAttribute('storage', $session);
        $this->assertObjectHasAttribute('flashName', $session);
        $this->assertObjectHasAttribute('attributeName', $session);
    }

    public function testHasPreviousSession()
    {
        $request = new Request();

        $this->assertFalse($request->hasPreviousSession());
        $request->cookies->set('MOCKSESSID', 'foo');
        $this->assertFalse($request->hasPreviousSession());
        $request->setSession(new Session(new MockArraySessionStorage()));
        $this->assertTrue($request->hasPreviousSession());
    }

    public function testToString()
    {
        $request = new Request();

        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6');

        $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $request->__toString());
    }

    public function testIsMethod()
    {
        $request = new Request();
        $request->setMethod('POST');
        $this->assertTrue($request->isMethod('POST'));
        $this->assertTrue($request->isMethod('post'));
        $this->assertFalse($request->isMethod('GET'));
        $this->assertFalse($request->isMethod('get'));

        $request->setMethod('GET');
        $this->assertTrue($request->isMethod('GET'));
        $this->assertTrue($request->isMethod('get'));
        $this->assertFalse($request->isMethod('POST'));
        $this->assertFalse($request->isMethod('post'));
    }

    /**
     * @dataProvider getBaseUrlData
     */
    public function testGetBaseUrl($uri, $server, $expectedBaseUrl, $expectedPathInfo)
    {
        $request = Request::create($uri, 'GET', array(), array(), array(), $server);

        $this->assertSame($expectedBaseUrl, $request->getBaseUrl(), 'baseUrl');
        $this->assertSame($expectedPathInfo, $request->getPathInfo(), 'pathInfo');
    }

    public function getBaseUrlData()
    {
        return array(
            array(
                '/foo%20bar',
                array(
                    'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
                    'SCRIPT_NAME'     => '/foo bar/app.php',
                    'PHP_SELF'        => '/foo bar/app.php',
                ),
                '/foo%20bar',
                '/',
            ),
            array(
                '/foo%20bar/home',
                array(
                    'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
                    'SCRIPT_NAME'     => '/foo bar/app.php',
                    'PHP_SELF'        => '/foo bar/app.php',
                ),
                '/foo%20bar',
                '/home',
            ),
            array(
                '/foo%20bar/app.php/home',
                array(
                    'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
                    'SCRIPT_NAME'     => '/foo bar/app.php',
                    'PHP_SELF'        => '/foo bar/app.php',
                ),
                '/foo%20bar/app.php',
                '/home',
            ),
            array(
                '/foo%20bar/app.php/home%3Dbaz',
                array(
                    'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo bar/app.php',
                    'SCRIPT_NAME'     => '/foo bar/app.php',
                    'PHP_SELF'        => '/foo bar/app.php',
                ),
                '/foo%20bar/app.php',
                '/home%3Dbaz',
            ),
            array(
                '/foo/bar+baz',
                array(
                    'SCRIPT_FILENAME' => '/home/John Doe/public_html/foo/app.php',
                    'SCRIPT_NAME'     => '/foo/app.php',
                    'PHP_SELF'        => '/foo/app.php',
                ),
                '/foo',
                '/bar+baz',
            ),
        );
    }

    /**
     * @dataProvider urlencodedStringPrefixData
     */
    public function testUrlencodedStringPrefix($string, $prefix, $expect)
    {
        $request = new Request();

        $me = new \ReflectionMethod($request, 'getUrlencodedPrefix');
        $me->setAccessible(true);

        $this->assertSame($expect, $me->invoke($request, $string, $prefix));
    }

    public function urlencodedStringPrefixData()
    {
        return array(
            array('foo', 'foo', 'foo'),
            array('fo%6f', 'foo', 'fo%6f'),
            array('foo/bar', 'foo', 'foo'),
            array('fo%6f/bar', 'foo', 'fo%6f'),
            array('f%6f%6f/bar', 'foo', 'f%6f%6f'),
            array('%66%6F%6F/bar', 'foo', '%66%6F%6F'),
            array('fo+o/bar', 'fo+o', 'fo+o'),
            array('fo%2Bo/bar', 'fo+o', 'fo%2Bo'),
        );
    }

    private function disableHttpMethodParameterOverride()
    {
        $class = new \ReflectionClass('Symfony\\Component\\HttpFoundation\\Request');
        $property = $class->getProperty('httpMethodParameterOverride');
        $property->setAccessible(true);
        $property->setValue(false);
    }

    private function getRequestInstanceForClientIpTests($remoteAddr, $httpForwardedFor, $trustedProxies)
    {
        $request = new Request();

        $server = array('REMOTE_ADDR' => $remoteAddr);
        if (null !== $httpForwardedFor) {
            $server['HTTP_X_FORWARDED_FOR'] = $httpForwardedFor;
        }

        if ($trustedProxies) {
            Request::setTrustedProxies($trustedProxies);
        }

        $request->initialize(array(), array(), array(), array(), array(), $server);

        return $request;
    }

    public function testTrustedProxies()
    {
        $request = Request::create('http://example.com/');
        $request->server->set('REMOTE_ADDR', '3.3.3.3');
        $request->headers->set('X_FORWARDED_FOR', '1.1.1.1, 2.2.2.2');
        $request->headers->set('X_FORWARDED_HOST', 'foo.example.com, real.example.com:8080');
        $request->headers->set('X_FORWARDED_PROTO', 'https');
        $request->headers->set('X_FORWARDED_PORT', 443);
        $request->headers->set('X_MY_FOR', '3.3.3.3, 4.4.4.4');
        $request->headers->set('X_MY_HOST', 'my.example.com');
        $request->headers->set('X_MY_PROTO', 'http');
        $request->headers->set('X_MY_PORT', 81);

        // no trusted proxies
        $this->assertEquals('3.3.3.3', $request->getClientIp());
        $this->assertEquals('example.com', $request->getHost());
        $this->assertEquals(80, $request->getPort());
        $this->assertFalse($request->isSecure());

        // disabling proxy trusting
        Request::setTrustedProxies(array());
        $this->assertEquals('3.3.3.3', $request->getClientIp());
        $this->assertEquals('example.com', $request->getHost());
        $this->assertEquals(80, $request->getPort());
        $this->assertFalse($request->isSecure());

        // trusted proxy via setTrustedProxies()
        Request::setTrustedProxies(array('3.3.3.3', '2.2.2.2'));
        $this->assertEquals('1.1.1.1', $request->getClientIp());
        $this->assertEquals('real.example.com', $request->getHost());
        $this->assertEquals(443, $request->getPort());
        $this->assertTrue($request->isSecure());

        // check various X_FORWARDED_PROTO header values
        $request->headers->set('X_FORWARDED_PROTO', 'ssl');
        $this->assertTrue($request->isSecure());

        $request->headers->set('X_FORWARDED_PROTO', 'https, http');
        $this->assertTrue($request->isSecure());

        // custom header names
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_MY_FOR');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_MY_HOST');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_MY_PORT');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_MY_PROTO');
        $this->assertEquals('4.4.4.4', $request->getClientIp());
        $this->assertEquals('my.example.com', $request->getHost());
        $this->assertEquals(81, $request->getPort());
        $this->assertFalse($request->isSecure());

        // disabling via empty header names
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, null);
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, null);
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, null);
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, null);
        $this->assertEquals('3.3.3.3', $request->getClientIp());
        $this->assertEquals('example.com', $request->getHost());
        $this->assertEquals(80, $request->getPort());
        $this->assertFalse($request->isSecure());

        // reset
        Request::setTrustedProxies(array());
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, 'X_FORWARDED_FOR');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_HOST, 'X_FORWARDED_HOST');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PORT, 'X_FORWARDED_PORT');
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_PROTO, 'X_FORWARDED_PROTO');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetTrustedProxiesInvalidHeaderName()
    {
        Request::create('http://example.com/');
        Request::setTrustedHeaderName('bogus name', 'X_MY_FOR');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetTrustedProxiesInvalidHeaderName()
    {
        Request::create('http://example.com/');
        Request::getTrustedHeaderName('bogus name');
    }

    /**
     * @dataProvider iisRequestUriProvider
     */
    public function testIISRequestUri($headers, $server, $expectedRequestUri)
    {
        $request = new Request();
        $request->headers->replace($headers);
        $request->server->replace($server);

        $this->assertEquals($expectedRequestUri, $request->getRequestUri(), '->getRequestUri() is correct');

        $subRequestUri = '/bar/foo';
        $subRequest = Request::create($subRequestUri, 'get', array(), array(), array(), $request->server->all());
        $this->assertEquals($subRequestUri, $subRequest->getRequestUri(), '->getRequestUri() is correct in sub request');
    }

    public function iisRequestUriProvider()
    {
        return array(
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(),
                '/foo/bar'
            ),
            array(
                array(
                    'X_REWRITE_URL' => '/foo/bar',
                ),
                array(),
                '/foo/bar'
            ),
            array(
                array(),
                array(
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar'
                ),
                '/foo/bar'
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'HTTP_X_ORIGINAL_URL' => '/foo/bar'
                ),
                '/foo/bar'
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar'
                ),
                '/foo/bar'
            ),
            array(
                array(
                    'X_ORIGINAL_URL' => '/foo/bar',
                ),
                array(
                    'HTTP_X_ORIGINAL_URL' => '/foo/bar',
                    'IIS_WasUrlRewritten' => '1',
                    'UNENCODED_URL' => '/foo/bar'
                ),
                '/foo/bar'
            ),
            array(
                array(),
                array(
                    'ORIG_PATH_INFO' => '/foo/bar',
                ),
                '/foo/bar'
            ),
            array(
                array(),
                array(
                    'ORIG_PATH_INFO' => '/foo/bar',
                    'QUERY_STRING' => 'foo=bar',
                ),
                '/foo/bar?foo=bar'
            )
        );
    }

    public function testTrustedHosts()
    {
        // create a request
        $request = Request::create('/');

        // no trusted host set -> no host check
        $request->headers->set('host', 'evil.com');
        $this->assertEquals('evil.com', $request->getHost());

        // add a trusted domain and all its subdomains
        Request::setTrustedHosts(array('.*\.?trusted.com$'));

        // untrusted host
        $request->headers->set('host', 'evil.com');
        try {
            $request->getHost();
            $this->fail('Request::getHost() should throw an exception when host is not trusted.');
        } catch (\UnexpectedValueException $e) {
            $this->assertEquals('Untrusted Host "evil.com"', $e->getMessage());
        }

        // trusted hosts
        $request->headers->set('host', 'trusted.com');
        $this->assertEquals('trusted.com', $request->getHost());
        $this->assertEquals(80, $request->getPort());

        $request->server->set('HTTPS', true);
        $request->headers->set('host', 'trusted.com');
        $this->assertEquals('trusted.com', $request->getHost());
        $this->assertEquals(443, $request->getPort());
        $request->server->set('HTTPS', false);

        $request->headers->set('host', 'trusted.com:8000');
        $this->assertEquals('trusted.com', $request->getHost());
        $this->assertEquals(8000, $request->getPort());

        $request->headers->set('host', 'subdomain.trusted.com');
        $this->assertEquals('subdomain.trusted.com', $request->getHost());

        // reset request for following tests
        Request::setTrustedHosts(array());
    }

    public function testFactory()
    {
        Request::setFactory(function (array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null) {
            return new NewRequest();
        });

        $this->assertEquals('foo', Request::create('/')->getFoo());

        Request::setFactory(null);
    }
}

class RequestContentProxy extends Request
{
    public function getContent($asResource = false)
    {
        return http_build_query(array('_method' => 'PUT', 'content' => 'mycontent'));
    }
}

class NewRequest extends Request
{
    public function getFoo()
    {
        return 'foo';
    }
}
PK=1[%�bD�
�
KHttpFoundation/Symfony/Component/HttpFoundation/Tests/ApacheRequestTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\ApacheRequest;

class ApacheRequestTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provideServerVars
     */
    public function testUriMethods($server, $expectedRequestUri, $expectedBaseUrl, $expectedPathInfo)
    {
        $request = new ApacheRequest();
        $request->server->replace($server);

        $this->assertEquals($expectedRequestUri, $request->getRequestUri(), '->getRequestUri() is correct');
        $this->assertEquals($expectedBaseUrl, $request->getBaseUrl(), '->getBaseUrl() is correct');
        $this->assertEquals($expectedPathInfo, $request->getPathInfo(), '->getPathInfo() is correct');
    }

    public function provideServerVars()
    {
        return array(
            array(
                array(
                    'REQUEST_URI' => '/foo/app_dev.php/bar',
                    'SCRIPT_NAME' => '/foo/app_dev.php',
                    'PATH_INFO'   => '/bar',
                ),
                '/foo/app_dev.php/bar',
                '/foo/app_dev.php',
                '/bar'
            ),
            array(
                array(
                    'REQUEST_URI' => '/foo/bar',
                    'SCRIPT_NAME' => '/foo/app_dev.php',
                ),
                '/foo/bar',
                '/foo',
                '/bar',
            ),
            array(
                array(
                    'REQUEST_URI' => '/app_dev.php/foo/bar',
                    'SCRIPT_NAME' => '/app_dev.php',
                    'PATH_INFO'   => '/foo/bar',
                ),
                '/app_dev.php/foo/bar',
                '/app_dev.php',
                '/foo/bar',
            ),
            array(
                array(
                    'REQUEST_URI' => '/foo/bar',
                    'SCRIPT_NAME' => '/app_dev.php',
                ),
                '/foo/bar',
                '',
                '/foo/bar',
            ),
            array(
                array(
                    'REQUEST_URI' => '/app_dev.php',
                    'SCRIPT_NAME' => '/app_dev.php',
                ),
                '/app_dev.php',
                '/app_dev.php',
                '/',
            ),
            array(
                array(
                    'REQUEST_URI' => '/',
                    'SCRIPT_NAME' => '/app_dev.php',
                ),
                '/',
                '',
                '/',
            ),
        );
    }
}
PK=1[�1r�
�
JHttpFoundation/Symfony/Component/HttpFoundation/Tests/AcceptHeaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\AcceptHeader;
use Symfony\Component\HttpFoundation\AcceptHeaderItem;

class AcceptHeaderTest extends \PHPUnit_Framework_TestCase
{
    public function testFirst()
    {
        $header = AcceptHeader::fromString('text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c');
        $this->assertSame('text/html', $header->first()->getValue());
    }

    /**
     * @dataProvider provideFromStringData
     */
    public function testFromString($string, array $items)
    {
        $header = AcceptHeader::fromString($string);
        $parsed = array_values($header->all());
        // reset index since the fixtures don't have them set
        foreach ($parsed as $item) {
            $item->setIndex(0);
        }
        $this->assertEquals($items, $parsed);
    }

    public function provideFromStringData()
    {
        return array(
            array('', array()),
            array('gzip', array(new AcceptHeaderItem('gzip'))),
            array('gzip,deflate,sdch', array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))),
            array("gzip, deflate\t,sdch", array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch'))),
            array('"this;should,not=matter"', array(new AcceptHeaderItem('this;should,not=matter'))),
        );
    }

    /**
     * @dataProvider provideToStringData
     */
    public function testToString(array $items, $string)
    {
        $header = new AcceptHeader($items);
        $this->assertEquals($string, (string) $header);
    }

    public function provideToStringData()
    {
        return array(
            array(array(), ''),
            array(array(new AcceptHeaderItem('gzip')), 'gzip'),
            array(array(new AcceptHeaderItem('gzip'), new AcceptHeaderItem('deflate'), new AcceptHeaderItem('sdch')), 'gzip,deflate,sdch'),
            array(array(new AcceptHeaderItem('this;should,not=matter')), 'this;should,not=matter'),
        );
    }

    /**
     * @dataProvider provideFilterData
     */
    public function testFilter($string, $filter, array $values)
    {
        $header = AcceptHeader::fromString($string)->filter($filter);
        $this->assertEquals($values, array_keys($header->all()));
    }

    public function provideFilterData()
    {
        return array(
            array('fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4', '/fr.*/', array('fr-FR', 'fr')),
        );
    }

    /**
     * @dataProvider provideSortingData
     */
    public function testSorting($string, array $values)
    {
        $header = AcceptHeader::fromString($string);
        $this->assertEquals($values, array_keys($header->all()));
    }

    public function provideSortingData()
    {
        return array(
            'quality has priority' => array('*;q=0.3,ISO-8859-1,utf-8;q=0.7',  array('ISO-8859-1', 'utf-8', '*')),
            'order matters when q is equal' => array('*;q=0.3,ISO-8859-1;q=0.7,utf-8;q=0.7',  array('ISO-8859-1', 'utf-8', '*')),
            'order matters when q is equal2' => array('*;q=0.3,utf-8;q=0.7,ISO-8859-1;q=0.7',  array('utf-8', 'ISO-8859-1', '*')),
        );
    }
}
PK=1[��?�GHttpFoundation/Symfony/Component/HttpFoundation/Tests/ServerBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpFoundation\Tests;

use Symfony\Component\HttpFoundation\ServerBag;

/**
 * ServerBagTest
 *
 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class ServerBagTest extends \PHPUnit_Framework_TestCase
{
    public function testShouldExtractHeadersFromServerArray()
    {
        $server = array(
            'SOME_SERVER_VARIABLE' => 'value',
            'SOME_SERVER_VARIABLE2' => 'value',
            'ROOT' => 'value',
            'HTTP_CONTENT_TYPE' => 'text/html',
            'HTTP_CONTENT_LENGTH' => '0',
            'HTTP_ETAG' => 'asdf',
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => 'bar',
        );

        $bag = new ServerBag($server);

        $this->assertEquals(array(
            'CONTENT_TYPE' => 'text/html',
            'CONTENT_LENGTH' => '0',
            'ETAG' => 'asdf',
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => 'bar',
        ), $bag->getHeaders());
    }

    public function testHttpPasswordIsOptional()
    {
        $bag = new ServerBag(array('PHP_AUTH_USER' => 'foo'));

        $this->assertEquals(array(
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => ''
        ), $bag->getHeaders());
    }

    public function testHttpBasicAuthWithPhpCgi()
    {
        $bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar')));

        $this->assertEquals(array(
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => 'bar'
        ), $bag->getHeaders());
    }

    public function testHttpBasicAuthWithPhpCgiRedirect()
    {
        $bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:bar')));

        $this->assertEquals(array(
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:bar'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => 'bar'
        ), $bag->getHeaders());
    }

    public function testHttpBasicAuthWithPhpCgiEmptyPassword()
    {
        $bag = new ServerBag(array('HTTP_AUTHORIZATION' => 'Basic '.base64_encode('foo:')));

        $this->assertEquals(array(
            'AUTHORIZATION' => 'Basic '.base64_encode('foo:'),
            'PHP_AUTH_USER' => 'foo',
            'PHP_AUTH_PW' => ''
        ), $bag->getHeaders());
    }

    public function testHttpDigestAuthWithPhpCgi()
    {
        $digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"';
        $bag = new ServerBag(array('HTTP_AUTHORIZATION' => $digest));

        $this->assertEquals(array(
            'AUTHORIZATION' => $digest,
            'PHP_AUTH_DIGEST' => $digest,
        ), $bag->getHeaders());
    }

    public function testHttpDigestAuthWithPhpCgiRedirect()
    {
        $digest = 'Digest username="foo", realm="acme", nonce="'.md5('secret').'", uri="/protected, qop="auth"';
        $bag = new ServerBag(array('REDIRECT_HTTP_AUTHORIZATION' => $digest));

        $this->assertEquals(array(
            'AUTHORIZATION' => $digest,
            'PHP_AUTH_DIGEST' => $digest,
        ), $bag->getHeaders());
    }

    public function testOAuthBearerAuth()
    {
        $headerContent = 'Bearer L-yLEOr9zhmUYRkzN1jwwxwQ-PBNiKDc8dgfB4hTfvo';
        $bag = new ServerBag(array('HTTP_AUTHORIZATION' => $headerContent));

        $this->assertEquals(array(
            'AUTHORIZATION' => $headerContent,
        ), $bag->getHeaders());
    }
}
PK=1[���bpp@HttpFoundation/Symfony/Component/HttpFoundation/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony HttpFoundation Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK=1[��J=�'�'?BrowserKit/Symfony/Component/BrowserKit/Tests/CookieJarTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\Response;

class CookieJarTest extends \PHPUnit_Framework_TestCase
{
    public function testSetGet()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie = new Cookie('foo', 'bar'));

        $this->assertEquals($cookie, $cookieJar->get('foo'), '->set() sets a cookie');

        $this->assertNull($cookieJar->get('foobar'), '->get() returns null if the cookie does not exist');

        $cookieJar->set($cookie = new Cookie('foo', 'bar', time() - 86400));
        $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired');
    }

    public function testExpire()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie = new Cookie('foo', 'bar'));
        $cookieJar->expire('foo');
        $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired');
    }

    public function testAll()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar'));
        $cookieJar->set($cookie2 = new Cookie('bar', 'foo'));

        $this->assertEquals(array($cookie1, $cookie2), $cookieJar->all(), '->all() returns all cookies in the jar');
    }

    public function testClear()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar'));
        $cookieJar->set($cookie2 = new Cookie('bar', 'foo'));

        $cookieJar->clear();

        $this->assertEquals(array(), $cookieJar->all(), '->clear() expires all cookies');
    }

    public function testUpdateFromResponse()
    {
        $response = new Response('', 200, array('Set-Cookie' => 'foo=foo'));

        $cookieJar = new CookieJar();
        $cookieJar->updateFromResponse($response);

        $this->assertEquals('foo', $cookieJar->get('foo')->getValue(), '->updateFromResponse() updates cookies from a Response objects');
    }

    public function testUpdateFromSetCookie()
    {
        $setCookies = array('foo=foo');

        $cookieJar = new CookieJar();
        $cookieJar->set(new Cookie('bar', 'bar'));
        $cookieJar->updateFromSetCookie($setCookies);

        $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $cookieJar->get('foo'));
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $cookieJar->get('bar'));
        $this->assertEquals('foo', $cookieJar->get('foo')->getValue(), '->updateFromSetCookie() updates cookies from a Set-Cookie header');
        $this->assertEquals('bar', $cookieJar->get('bar')->getValue(), '->updateFromSetCookie() keeps existing cookies');
    }

    public function testUpdateFromEmptySetCookie()
    {
        $cookieJar = new CookieJar();
        $cookieJar->updateFromSetCookie(array(''));
        $this->assertEquals(array(), $cookieJar->all());
    }

    public function testUpdateFromSetCookieWithMultipleCookies()
    {
        $timestamp = time() + 3600;
        $date = gmdate('D, d M Y H:i:s \G\M\T', $timestamp);
        $setCookies = array(sprintf('foo=foo; expires=%s; domain=.symfony.com; path=/, bar=bar; domain=.blog.symfony.com, PHPSESSID=id; expires=%s', $date, $date));

        $cookieJar = new CookieJar();
        $cookieJar->updateFromSetCookie($setCookies);

        $fooCookie = $cookieJar->get('foo', '/', '.symfony.com');
        $barCookie = $cookieJar->get('bar', '/', '.blog.symfony.com');
        $phpCookie = $cookieJar->get('PHPSESSID');

        $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $fooCookie);
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $barCookie);
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Cookie', $phpCookie);
        $this->assertEquals('foo', $fooCookie->getValue());
        $this->assertEquals('bar', $barCookie->getValue());
        $this->assertEquals('id', $phpCookie->getValue());
        $this->assertEquals($timestamp, $fooCookie->getExpiresTime());
        $this->assertNull($barCookie->getExpiresTime());
        $this->assertEquals($timestamp, $phpCookie->getExpiresTime());
    }

    /**
     * @dataProvider provideAllValuesValues
     */
    public function testAllValues($uri, $values)
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo_nothing', 'foo'));
        $cookieJar->set($cookie2 = new Cookie('foo_expired', 'foo', time() - 86400));
        $cookieJar->set($cookie3 = new Cookie('foo_path', 'foo', null, '/foo'));
        $cookieJar->set($cookie4 = new Cookie('foo_domain', 'foo', null, '/', '.example.com'));
        $cookieJar->set($cookie4 = new Cookie('foo_strict_domain', 'foo', null, '/', '.www4.example.com'));
        $cookieJar->set($cookie5 = new Cookie('foo_secure', 'foo', null, '/', '', true));

        $this->assertEquals($values, array_keys($cookieJar->allValues($uri)), '->allValues() returns the cookie for a given URI');
    }

    public function provideAllValuesValues()
    {
        return array(
            array('http://www.example.com', array('foo_nothing', 'foo_domain')),
            array('http://www.example.com/', array('foo_nothing', 'foo_domain')),
            array('http://foo.example.com/', array('foo_nothing', 'foo_domain')),
            array('http://foo.example1.com/', array('foo_nothing')),
            array('https://foo.example.com/', array('foo_nothing', 'foo_secure', 'foo_domain')),
            array('http://www.example.com/foo/bar', array('foo_nothing', 'foo_path', 'foo_domain')),
            array('http://www4.example.com/', array('foo_nothing', 'foo_domain', 'foo_strict_domain')),
        );
    }

    public function testEncodedValues()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true));

        $this->assertEquals(array('foo' => 'bar=baz'), $cookieJar->allValues('/'));
        $this->assertEquals(array('foo' => 'bar%3Dbaz'), $cookieJar->allRawValues('/'));
    }

    public function testCookieExpireWithSameNameButDifferentPaths()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/foo'));
        $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/bar'));
        $cookieJar->expire('foo', '/foo');

        $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired');
        $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/')));
        $this->assertEquals(array(), $cookieJar->allValues('http://example.com/foo'));
        $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://example.com/bar'));
    }

    public function testCookieExpireWithNullPaths()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/'));
        $cookieJar->expire('foo', null);

        $this->assertNull($cookieJar->get('foo'), '->get() returns null if the cookie is expired');
        $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/')));
    }

    public function testCookieWithSameNameButDifferentPaths()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/foo'));
        $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/bar'));

        $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/')));
        $this->assertEquals(array('foo' => 'bar1'), $cookieJar->allValues('http://example.com/foo'));
        $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://example.com/bar'));
    }

    public function testCookieWithSameNameButDifferentDomains()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar1', null, '/', 'foo.example.com'));
        $cookieJar->set($cookie2 = new Cookie('foo', 'bar2', null, '/', 'bar.example.com'));

        $this->assertEquals(array(), array_keys($cookieJar->allValues('http://example.com/')));
        $this->assertEquals(array('foo' => 'bar1'), $cookieJar->allValues('http://foo.example.com/'));
        $this->assertEquals(array('foo' => 'bar2'), $cookieJar->allValues('http://bar.example.com/'));
    }

    public function testCookieGetWithSubdomain()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar', null, '/', '.example.com'));
        $cookieJar->set($cookie2 = new Cookie('foo1', 'bar', null, '/', 'test.example.com'));

        $this->assertEquals($cookie1, $cookieJar->get('foo','/','foo.example.com'));
        $this->assertEquals($cookie1, $cookieJar->get('foo','/','example.com'));
        $this->assertEquals($cookie2, $cookieJar->get('foo1','/','test.example.com'));
    }

    public function testCookieGetWithSubdirectory()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set($cookie1 = new Cookie('foo', 'bar', null, '/test', '.example.com'));
        $cookieJar->set($cookie2 = new Cookie('foo1', 'bar1', null, '/', '.example.com'));

        $this->assertNull($cookieJar->get('foo','/','.example.com'));
        $this->assertNull($cookieJar->get('foo','/bar','.example.com'));
        $this->assertEquals($cookie1, $cookieJar->get('foo','/test','example.com'));
        $this->assertEquals($cookie2, $cookieJar->get('foo1','/','example.com'));
        $this->assertEquals($cookie2, $cookieJar->get('foo1','/bar','example.com'));
    }

    public function testCookieWithWildcardDomain()
    {
        $cookieJar = new CookieJar();
        $cookieJar->set(new Cookie('foo', 'bar', null, '/', '.example.com'));

        $this->assertEquals(array('foo' => 'bar'), $cookieJar->allValues('http://www.example.com'));
        $this->assertEmpty($cookieJar->allValues('http://wwwexample.com'));
    }
}
PK=1[N�4Z�c�c<BrowserKit/Symfony/Component/BrowserKit/Tests/ClientTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\Client;
use Symfony\Component\BrowserKit\History;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\Request;
use Symfony\Component\BrowserKit\Response;

class SpecialResponse extends Response
{
}

class TestClient extends Client
{
    protected $nextResponse = null;
    protected $nextScript = null;

    public function setNextResponse(Response $response)
    {
        $this->nextResponse = $response;
    }

    public function setNextScript($script)
    {
        $this->nextScript = $script;
    }

    protected function doRequest($request)
    {
        if (null === $this->nextResponse) {
            return new Response();
        }

        $response = $this->nextResponse;
        $this->nextResponse = null;

        return $response;
    }

    protected function filterResponse($response)
    {
        if ($response instanceof SpecialResponse) {
            return new Response($response->getContent(), $response->getStatus(), $response->getHeaders());
        }

        return $response;
    }

    protected function getScript($request)
    {
        $r = new \ReflectionClass('Symfony\Component\BrowserKit\Response');
        $path = $r->getFileName();

        return <<<EOF
<?php

require_once('$path');

echo serialize($this->nextScript);
EOF;
    }
}

class ClientTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\BrowserKit\Client::getHistory
     */
    public function testGetHistory()
    {
        $client = new TestClient(array(), $history = new History());
        $this->assertSame($history, $client->getHistory(), '->getHistory() returns the History');
    }

    /**
     * @covers Symfony\Component\BrowserKit\Client::getCookieJar
     */
    public function testGetCookieJar()
    {
        $client = new TestClient(array(), null, $cookieJar = new CookieJar());
        $this->assertSame($cookieJar, $client->getCookieJar(), '->getCookieJar() returns the CookieJar');
    }

    /**
     * @covers Symfony\Component\BrowserKit\Client::getRequest
     */
    public function testGetRequest()
    {
        $client = new TestClient();
        $client->request('GET', 'http://example.com/');

        $this->assertEquals('http://example.com/', $client->getRequest()->getUri(), '->getCrawler() returns the Request of the last request');
    }

    public function testGetResponse()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('foo'));
        $client->request('GET', 'http://example.com/');

        $this->assertEquals('foo', $client->getResponse()->getContent(), '->getCrawler() returns the Response of the last request');
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getResponse(), '->getCrawler() returns the Response of the last request');
    }

    public function testGetInternalResponse()
    {
        $client = new TestClient();
        $client->setNextResponse(new SpecialResponse('foo'));
        $client->request('GET', 'http://example.com/');

        $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse());
        $this->assertNotInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getInternalResponse());
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Tests\SpecialResponse', $client->getResponse());
    }

    public function testGetContent()
    {
        $json = '{"jsonrpc":"2.0","method":"echo","id":7,"params":["Hello World"]}';

        $client = new TestClient();
        $client->request('POST', 'http://example.com/jsonrpc', array(), array(), array(), $json);
        $this->assertEquals($json, $client->getRequest()->getContent());
    }

    /**
     * @covers Symfony\Component\BrowserKit\Client::getCrawler
     */
    public function testGetCrawler()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('foo'));
        $crawler = $client->request('GET', 'http://example.com/');

        $this->assertSame($crawler, $client->getCrawler(), '->getCrawler() returns the Crawler of the last request');
    }

    public function testRequestHttpHeaders()
    {
        $client = new TestClient();
        $client->request('GET', '/');
        $headers = $client->getRequest()->getServer();
        $this->assertEquals('localhost', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com');
        $headers = $client->getRequest()->getServer();
        $this->assertEquals('www.example.com', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header');

        $client->request('GET', 'https://www.example.com');
        $headers = $client->getRequest()->getServer();
        $this->assertTrue($headers['HTTPS'], '->request() sets the HTTPS header');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com:8080');
        $headers = $client->getRequest()->getServer();
        $this->assertEquals('www.example.com:8080', $headers['HTTP_HOST'], '->request() sets the HTTP_HOST header with port');
    }

    public function testRequestURIConversion()
    {
        $client = new TestClient();
        $client->request('GET', '/foo');
        $this->assertEquals('http://localhost/foo', $client->getRequest()->getUri(), '->request() converts the URI to an absolute one');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com');
        $this->assertEquals('http://www.example.com', $client->getRequest()->getUri(), '->request() does not change absolute URIs');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/');
        $client->request('GET', '/foo');
        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo');
        $client->request('GET', '#');
        $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #');
        $client->request('GET', '#');
        $this->assertEquals('http://www.example.com/foo#', $client->getRequest()->getUri(), '->request() uses the previous request for #');
        $client->request('GET', '#foo');
        $this->assertEquals('http://www.example.com/foo#foo', $client->getRequest()->getUri(), '->request() uses the previous request for #');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo/');
        $client->request('GET', 'bar');
        $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs');

        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->request('GET', 'bar');
        $this->assertEquals('http://www.example.com/foo/bar', $client->getRequest()->getUri(), '->request() uses the previous request for relative URLs');
    }

    public function testRequestReferer()
    {
        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->request('GET', 'bar');
        $server = $client->getRequest()->getServer();
        $this->assertEquals('http://www.example.com/foo/foobar', $server['HTTP_REFERER'], '->request() sets the referer');
    }

    public function testRequestHistory()
    {
        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->request('GET', 'bar');

        $this->assertEquals('http://www.example.com/foo/bar', $client->getHistory()->current()->getUri(), '->request() updates the History');
        $this->assertEquals('http://www.example.com/foo/foobar', $client->getHistory()->back()->getUri(), '->request() updates the History');
    }

    public function testRequestCookies()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>', 200, array('Set-Cookie' => 'foo=bar')));
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar');

        $client->request('GET', 'bar');
        $this->assertEquals(array('foo' => 'bar'), $client->getCookieJar()->allValues('http://www.example.com/foo/foobar'), '->request() updates the CookieJar');
    }

    public function testRequestSecureCookies()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>', 200, array('Set-Cookie' => 'foo=bar; path=/; secure')));
        $client->request('GET', 'https://www.example.com/foo/foobar');

        $this->assertTrue($client->getCookieJar()->get('foo', '/', 'www.example.com')->isSecure());
    }

    public function testClick()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('<html><a href="/foo">foo</a></html>'));
        $crawler = $client->request('GET', 'http://www.example.com/foo/foobar');

        $client->click($crawler->filter('a')->link());

        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() clicks on links');
    }

    public function testClickForm()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>'));
        $crawler = $client->request('GET', 'http://www.example.com/foo/foobar');

        $client->click($crawler->filter('input')->form());

        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->click() Form submit forms');
    }

    public function testSubmit()
    {
        $client = new TestClient();
        $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>'));
        $crawler = $client->request('GET', 'http://www.example.com/foo/foobar');

        $client->submit($crawler->filter('input')->form());

        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms');
    }

    public function testSubmitPreserveAuth()
    {
        $client = new TestClient(array('PHP_AUTH_USER' => 'foo', 'PHP_AUTH_PW' => 'bar'));
        $client->setNextResponse(new Response('<html><form action="/foo"><input type="submit" /></form></html>'));
        $crawler = $client->request('GET', 'http://www.example.com/foo/foobar');

        $server = $client->getRequest()->getServer();
        $this->assertArrayHasKey('PHP_AUTH_USER', $server);
        $this->assertEquals('foo', $server['PHP_AUTH_USER']);
        $this->assertArrayHasKey('PHP_AUTH_PW', $server);
        $this->assertEquals('bar', $server['PHP_AUTH_PW']);

        $client->submit($crawler->filter('input')->form());

        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->submit() submit forms');

        $server = $client->getRequest()->getServer();
        $this->assertArrayHasKey('PHP_AUTH_USER', $server);
        $this->assertEquals('foo', $server['PHP_AUTH_USER']);
        $this->assertArrayHasKey('PHP_AUTH_PW', $server);
        $this->assertEquals('bar', $server['PHP_AUTH_PW']);
    }

    public function testFollowRedirect()
    {
        $client = new TestClient();
        $client->followRedirects(false);
        $client->request('GET', 'http://www.example.com/foo/foobar');

        try {
            $client->followRedirect();
            $this->fail('->followRedirect() throws a \LogicException if the request was not redirected');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request was not redirected');
        }

        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->followRedirect();

        $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any');

        $client = new TestClient();
        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');

        $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() automatically follows redirects if followRedirects is true');

        $client = new TestClient();
        $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');

        $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->followRedirect() does not follow redirect if HTTP Code is not 30x');

        $client = new TestClient();
        $client->setNextResponse(new Response('', 201, array('Location' => 'http://www.example.com/redirected')));
        $client->followRedirects(false);
        $client->request('GET', 'http://www.example.com/foo/foobar');

        try {
            $client->followRedirect();
            $this->fail('->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request did not respond with 30x HTTP Code');
        }
    }

    public function testFollowRedirectWithMaxRedirects()
    {
        $client = new TestClient();
        $client->setMaxRedirects(1);
        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any');

        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected2')));
        try {
            $client->followRedirect();
            $this->fail('->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->followRedirect() throws a \LogicException if the request was redirected and limit of redirections was reached');
        }

        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows a redirect if any');

        $client->setNextResponse(new Response('', 302, array('Location' => '/redirected')));
        $client->request('GET', 'http://www.example.com/foo/foobar');

        $this->assertEquals('http://www.example.com/redirected', $client->getRequest()->getUri(), '->followRedirect() follows relative URLs');

        $client = new TestClient();
        $client->setNextResponse(new Response('', 302, array('Location' => '//www.example.org/')));
        $client->request('GET', 'https://www.example.com/');

        $this->assertEquals('https://www.example.org/', $client->getRequest()->getUri(), '->followRedirect() follows protocol-relative URLs');

        $client = new TestClient();
        $client->setNextResponse(new Response('', 302, array('Location' => 'http://www.example.com/redirected')));
        $client->request('POST', 'http://www.example.com/foo/foobar', array('name' => 'bar'));

        $this->assertEquals('get', $client->getRequest()->getMethod(), '->followRedirect() uses a get for 302');
        $this->assertEquals(array(), $client->getRequest()->getParameters(), '->followRedirect() does not submit parameters when changing the method');
    }

    public function testFollowRedirectWithCookies()
    {
        $client = new TestClient();
        $client->followRedirects(false);
        $client->setNextResponse(new Response('', 302, array(
            'Location'   => 'http://www.example.com/redirected',
            'Set-Cookie' => 'foo=bar',
        )));
        $client->request('GET', 'http://www.example.com/');
        $this->assertEquals(array(), $client->getRequest()->getCookies());
        $client->followRedirect();
        $this->assertEquals(array('foo' => 'bar'), $client->getRequest()->getCookies());
    }

    public function testFollowRedirectWithHeaders()
    {
        $headers = array(
            'HTTP_HOST'       => 'www.example.com',
            'HTTP_USER_AGENT' => 'Symfony2 BrowserKit',
            'CONTENT_TYPE'    => 'application/vnd.custom+xml',
            'HTTPS'           => false,
        );

        $client = new TestClient();
        $client->followRedirects(false);
        $client->setNextResponse(new Response('', 302, array(
            'Location'    => 'http://www.example.com/redirected',
        )));
        $client->request('GET', 'http://www.example.com/', array(), array(), array(
            'CONTENT_TYPE' => 'application/vnd.custom+xml',
        ));

        $this->assertEquals($headers, $client->getRequest()->getServer());

        $client->followRedirect();

        $headers['HTTP_REFERER'] = 'http://www.example.com/';

        $this->assertEquals($headers, $client->getRequest()->getServer());
    }

    public function testFollowRedirectWithPort()
    {
        $headers = array(
            'HTTP_HOST'       => 'www.example.com:8080',
            'HTTP_USER_AGENT' => 'Symfony2 BrowserKit',
            'HTTPS'           => false
        );

        $client = new TestClient();
        $client->followRedirects(false);
        $client->setNextResponse(new Response('', 302, array(
            'Location'    => 'http://www.example.com:8080/redirected',
        )));
        $client->request('GET', 'http://www.example.com:8080/');

        $this->assertEquals($headers, $client->getRequest()->getServer());
    }

    public function testBack()
    {
        $client = new TestClient();

        $parameters = array('foo' => 'bar');
        $files = array('myfile.foo' => 'baz');
        $server = array('X_TEST_FOO' => 'bazbar');
        $content = 'foobarbaz';

        $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content);
        $client->request('GET', 'http://www.example.com/foo');
        $client->back();

        $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->back() goes back in the history');
        $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->back() keeps parameters');
        $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->back() keeps files');
        $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->back() keeps $_SERVER');
        $this->assertEquals($content, $client->getRequest()->getContent(), '->back() keeps content');
    }

    public function testForward()
    {
        $client = new TestClient();

        $parameters = array('foo' => 'bar');
        $files = array('myfile.foo' => 'baz');
        $server = array('X_TEST_FOO' => 'bazbar');
        $content = 'foobarbaz';

        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->request('GET', 'http://www.example.com/foo', $parameters, $files, $server, $content);
        $client->back();
        $client->forward();

        $this->assertEquals('http://www.example.com/foo', $client->getRequest()->getUri(), '->forward() goes forward in the history');
        $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->forward() keeps parameters');
        $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->forward() keeps files');
        $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->forward() keeps $_SERVER');
        $this->assertEquals($content, $client->getRequest()->getContent(), '->forward() keeps content');
    }

    public function testReload()
    {
        $client = new TestClient();

        $parameters = array('foo' => 'bar');
        $files = array('myfile.foo' => 'baz');
        $server = array('X_TEST_FOO' => 'bazbar');
        $content = 'foobarbaz';

        $client->request('GET', 'http://www.example.com/foo/foobar', $parameters, $files, $server, $content);
        $client->reload();

        $this->assertEquals('http://www.example.com/foo/foobar', $client->getRequest()->getUri(), '->reload() reloads the current page');
        $this->assertArrayHasKey('foo', $client->getRequest()->getParameters(), '->reload() keeps parameters');
        $this->assertArrayHasKey('myfile.foo', $client->getRequest()->getFiles(), '->reload() keeps files');
        $this->assertArrayHasKey('X_TEST_FOO', $client->getRequest()->getServer(), '->reload() keeps $_SERVER');
        $this->assertEquals($content, $client->getRequest()->getContent(), '->reload() keeps content');
    }

    public function testRestart()
    {
        $client = new TestClient();
        $client->request('GET', 'http://www.example.com/foo/foobar');
        $client->restart();

        $this->assertTrue($client->getHistory()->isEmpty(), '->restart() clears the history');
        $this->assertEquals(array(), $client->getCookieJar()->all(), '->restart() clears the cookies');
    }

    public function testInsulatedRequests()
    {
        $client = new TestClient();
        $client->insulate();
        $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar')");
        $client->request('GET', 'http://www.example.com/foo/foobar');

        $this->assertEquals('foobar', $client->getResponse()->getContent(), '->insulate() process the request in a forked process');

        $client->setNextScript("new Symfony\Component\BrowserKit\Response('foobar)");

        try {
            $client->request('GET', 'http://www.example.com/foo/foobar');
            $this->fail('->request() throws a \RuntimeException if the script has an error');
        } catch (\Exception $e) {
            $this->assertInstanceof('RuntimeException', $e, '->request() throws a \RuntimeException if the script has an error');
        }
    }

    public function testGetServerParameter()
    {
        $client = new TestClient();
        $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
        $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT'));
        $this->assertEquals('testvalue', $client->getServerParameter('testkey', 'testvalue'));
    }

    public function testSetServerParameter()
    {
        $client = new TestClient();

        $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
        $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT'));

        $client->setServerParameter('HTTP_HOST', 'testhost');
        $this->assertEquals('testhost', $client->getServerParameter('HTTP_HOST'));

        $client->setServerParameter('HTTP_USER_AGENT', 'testua');
        $this->assertEquals('testua', $client->getServerParameter('HTTP_USER_AGENT'));
    }

    public function testSetServerParameterInRequest()
    {
        $client = new TestClient();

        $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
        $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT'));

        $client->request('GET', 'https://www.example.com/https/www.example.com', array(), array(), array(
            'HTTP_HOST'       => 'testhost',
            'HTTP_USER_AGENT' => 'testua',
            'HTTPS'           => false,
            'NEW_SERVER_KEY'  => 'new-server-key-value'
        ));

        $this->assertEquals('localhost', $client->getServerParameter('HTTP_HOST'));
        $this->assertEquals('Symfony2 BrowserKit', $client->getServerParameter('HTTP_USER_AGENT'));

        $this->assertEquals('http://testhost/https/www.example.com', $client->getRequest()->getUri());

        $server = $client->getRequest()->getServer();

        $this->assertArrayHasKey('HTTP_USER_AGENT', $server);
        $this->assertEquals('testua', $server['HTTP_USER_AGENT']);

        $this->assertArrayHasKey('HTTP_HOST', $server);
        $this->assertEquals('testhost', $server['HTTP_HOST']);

        $this->assertArrayHasKey('NEW_SERVER_KEY', $server);
        $this->assertEquals('new-server-key-value', $server['NEW_SERVER_KEY']);

        $this->assertArrayHasKey('HTTPS', $server);
        $this->assertFalse($server['HTTPS']);
    }
}
PK=1[�ɹ(RR<BrowserKit/Symfony/Component/BrowserKit/Tests/CookieTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\Cookie;

class CookieTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTestsForToFromString
     */
    public function testToFromString($cookie, $url = null)
    {
        $this->assertEquals($cookie, (string) Cookie::fromString($cookie, $url));
    }

    public function getTestsForToFromString()
    {
        return array(
            array('foo=bar; path=/'),
            array('foo=bar; path=/foo'),
            array('foo=bar; domain=google.com; path=/'),
            array('foo=bar; domain=example.com; path=/; secure', 'https://example.com/'),
            array('foo=bar; path=/; httponly'),
            array('foo=bar; domain=google.com; path=/foo; secure; httponly', 'https://google.com/'),
            array('foo=bar=baz; path=/'),
            array('foo=bar%3Dbaz; path=/'),
        );
    }

    public function testFromStringIgnoreSecureFlag()
    {
        $this->assertFalse(Cookie::fromString('foo=bar; secure')->isSecure());
        $this->assertFalse(Cookie::fromString('foo=bar; secure', 'http://example.com/')->isSecure());
    }

    /**
     * @dataProvider getExpireCookieStrings
     */
    public function testFromStringAcceptsSeveralExpiresDateFormats($cookie)
    {
        $this->assertEquals(1596185377, Cookie::fromString($cookie)->getExpiresTime());
    }

    public function getExpireCookieStrings()
    {
        return array(
            array('foo=bar; expires=Fri, 31-Jul-2020 08:49:37 GMT'),
            array('foo=bar; expires=Fri, 31 Jul 2020 08:49:37 GMT'),
            array('foo=bar; expires=Fri, 31-07-2020 08:49:37 GMT'),
            array('foo=bar; expires=Fri, 31-07-20 08:49:37 GMT'),
            array('foo=bar; expires=Friday, 31-Jul-20 08:49:37 GMT'),
            array('foo=bar; expires=Fri Jul 31 08:49:37 2020'),
            array('foo=bar; expires=\'Fri Jul 31 08:49:37 2020\''),
            array('foo=bar; expires=Friday July 31st 2020, 08:49:37 GMT'),
        );
    }

    public function testFromStringWithCapitalization()
    {
        $this->assertEquals('Foo=Bar; path=/', (string) Cookie::fromString('Foo=Bar'));
        $this->assertEquals('foo=bar; expires=Fri, 31 Dec 2010 23:59:59 GMT; path=/', (string) Cookie::fromString('foo=bar; Expires=Fri, 31 Dec 2010 23:59:59 GMT'));
        $this->assertEquals('foo=bar; domain=www.example.org; path=/; httponly', (string) Cookie::fromString('foo=bar; DOMAIN=www.example.org; HttpOnly'));
    }

    public function testFromStringWithUrl()
    {
        $this->assertEquals('foo=bar; domain=www.example.com; path=/', (string) Cookie::FromString('foo=bar', 'http://www.example.com/'));
        $this->assertEquals('foo=bar; domain=www.example.com; path=/foo', (string) Cookie::FromString('foo=bar', 'http://www.example.com/foo/bar'));
        $this->assertEquals('foo=bar; domain=www.example.com; path=/', (string) Cookie::FromString('foo=bar; path=/', 'http://www.example.com/foo/bar'));
        $this->assertEquals('foo=bar; domain=www.myotherexample.com; path=/', (string) Cookie::FromString('foo=bar; domain=www.myotherexample.com', 'http://www.example.com/'));
    }

    public function testFromStringThrowsAnExceptionIfCookieIsNotValid()
    {
        $this->setExpectedException('InvalidArgumentException');
        Cookie::FromString('foo');
    }

    public function testFromStringThrowsAnExceptionIfCookieDateIsNotValid()
    {
        $this->setExpectedException('InvalidArgumentException');
        Cookie::FromString('foo=bar; expires=Flursday July 31st 2020, 08:49:37 GMT');
    }

    public function testFromStringThrowsAnExceptionIfUrlIsNotValid()
    {
        $this->setExpectedException('InvalidArgumentException');
        Cookie::FromString('foo=bar', 'foobar');
    }

    public function testGetName()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertEquals('foo', $cookie->getName(), '->getName() returns the cookie name');
    }

    public function testGetValue()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertEquals('bar', $cookie->getValue(), '->getValue() returns the cookie value');

        $cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true); // raw value
        $this->assertEquals('bar=baz', $cookie->getValue(), '->getValue() returns the urldecoded cookie value');
    }

    public function testGetRawValue()
    {
        $cookie = new Cookie('foo', 'bar=baz'); // decoded value
        $this->assertEquals('bar%3Dbaz', $cookie->getRawValue(), '->getRawValue() returns the urlencoded cookie value');
        $cookie = new Cookie('foo', 'bar%3Dbaz', null, '/', '', false, true, true); // raw value
        $this->assertEquals('bar%3Dbaz', $cookie->getRawValue(), '->getRawValue() returns the non-urldecoded cookie value');
    }

    public function testGetPath()
    {
        $cookie = new Cookie('foo', 'bar', 0);
        $this->assertEquals('/', $cookie->getPath(), '->getPath() returns / is no path is defined');

        $cookie = new Cookie('foo', 'bar', 0, '/foo');
        $this->assertEquals('/foo', $cookie->getPath(), '->getPath() returns the cookie path');
    }

    public function testGetDomain()
    {
        $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com');
        $this->assertEquals('foo.com', $cookie->getDomain(), '->getDomain() returns the cookie domain');
    }

    public function testIsSecure()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertFalse($cookie->isSecure(), '->isSecure() returns false if not defined');

        $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com', true);
        $this->assertTrue($cookie->isSecure(), '->isSecure() returns the cookie secure flag');
    }

    public function testIsHttponly()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns false if not defined');

        $cookie = new Cookie('foo', 'bar', 0, '/', 'foo.com', false, true);
        $this->assertTrue($cookie->isHttpOnly(), '->isHttpOnly() returns the cookie httponly flag');
    }

    public function testGetExpiresTime()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertNull($cookie->getExpiresTime(), '->getExpiresTime() returns the expires time');

        $cookie = new Cookie('foo', 'bar', $time = time() - 86400);
        $this->assertEquals($time, $cookie->getExpiresTime(), '->getExpiresTime() returns the expires time');
    }

    public function testIsExpired()
    {
        $cookie = new Cookie('foo', 'bar');
        $this->assertFalse($cookie->isExpired(), '->isExpired() returns false when the cookie never expires (null as expires time)');

        $cookie = new Cookie('foo', 'bar', time() - 86400);
        $this->assertTrue($cookie->isExpired(), '->isExpired() returns true when the cookie is expired');

        $cookie = new Cookie('foo', 'bar', 0);
        $this->assertFalse($cookie->isExpired());
    }
}
PK=1[K����=BrowserKit/Symfony/Component/BrowserKit/Tests/HistoryTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\History;
use Symfony\Component\BrowserKit\Request;

class HistoryTest extends \PHPUnit_Framework_TestCase
{
    public function testAdd()
    {
        $history = new History();
        $history->add(new Request('http://www.example1.com/', 'get'));
        $this->assertSame('http://www.example1.com/', $history->current()->getUri(), '->add() adds a request to the history');

        $history->add(new Request('http://www.example2.com/', 'get'));
        $this->assertSame('http://www.example2.com/', $history->current()->getUri(), '->add() adds a request to the history');

        $history->add(new Request('http://www.example3.com/', 'get'));
        $history->back();
        $history->add(new Request('http://www.example4.com/', 'get'));
        $this->assertSame('http://www.example4.com/', $history->current()->getUri(), '->add() adds a request to the history');

        $history->back();
        $this->assertSame('http://www.example2.com/', $history->current()->getUri(), '->add() adds a request to the history');
    }

    public function testClearIsEmpty()
    {
        $history = new History();
        $history->add(new Request('http://www.example.com/', 'get'));

        $this->assertFalse($history->isEmpty(), '->isEmpty() returns false if the history is not empty');

        $history->clear();

        $this->assertTrue($history->isEmpty(), '->isEmpty() true if the history is empty');
    }

    public function testCurrent()
    {
        $history = new History();

        try {
            $history->current();
            $this->fail('->current() throws a \LogicException if the history is empty');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->current() throws a \LogicException if the history is empty');
        }

        $history->add(new Request('http://www.example.com/', 'get'));

        $this->assertSame('http://www.example.com/', $history->current()->getUri(), '->current() returns the current request in the history');
    }

    public function testBack()
    {
        $history = new History();
        $history->add(new Request('http://www.example.com/', 'get'));

        try {
            $history->back();
            $this->fail('->back() throws a \LogicException if the history is already on the first page');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->current() throws a \LogicException if the history is already on the first page');
        }

        $history->add(new Request('http://www.example1.com/', 'get'));
        $history->back();

        $this->assertSame('http://www.example.com/', $history->current()->getUri(), '->back() returns the previous request in the history');
    }

    public function testForward()
    {
        $history = new History();
        $history->add(new Request('http://www.example.com/', 'get'));
        $history->add(new Request('http://www.example1.com/', 'get'));

        try {
            $history->forward();
            $this->fail('->forward() throws a \LogicException if the history is already on the last page');
        } catch (\Exception $e) {
            $this->assertInstanceof('LogicException', $e, '->forward() throws a \LogicException if the history is already on the last page');
        }

        $history->back();
        $history->forward();

        $this->assertSame('http://www.example1.com/', $history->current()->getUri(), '->forward() returns the next request in the history');
    }
}
PK=1[{2�w>BrowserKit/Symfony/Component/BrowserKit/Tests/ResponseTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\Response;

class ResponseTest extends \PHPUnit_Framework_TestCase
{
    public function testGetUri()
    {
        $response = new Response('foo');
        $this->assertEquals('foo', $response->getContent(), '->getContent() returns the content of the response');
    }

    public function testGetStatus()
    {
        $response = new Response('foo', 304);
        $this->assertEquals('304', $response->getStatus(), '->getStatus() returns the status of the response');
    }

    public function testGetHeaders()
    {
        $response = new Response('foo', 200, array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $response->getHeaders(), '->getHeaders() returns the headers of the response');
    }

    public function testGetHeader()
    {
        $response = new Response('foo', 200, array(
            'Content-Type' => 'text/html',
            'Set-Cookie'   => array('foo=bar', 'bar=foo'),
        ));

        $this->assertEquals('text/html', $response->getHeader('Content-Type'), '->getHeader() returns a header of the response');
        $this->assertEquals('text/html', $response->getHeader('content-type'), '->getHeader() returns a header of the response');
        $this->assertEquals('text/html', $response->getHeader('content_type'), '->getHeader() returns a header of the response');
        $this->assertEquals('foo=bar', $response->getHeader('Set-Cookie'), '->getHeader() returns the first header value');
        $this->assertEquals(array('foo=bar', 'bar=foo'), $response->getHeader('Set-Cookie', false), '->getHeader() returns all header values if first is false');

        $this->assertNull($response->getHeader('foo'), '->getHeader() returns null if the header is not defined');
        $this->assertEquals(array(), $response->getHeader('foo', false), '->getHeader() returns an empty array if the header is not defined and first is set to false');
    }

    public function testMagicToString()
    {
        $response = new Response('foo', 304, array('foo' => 'bar'));

        $this->assertEquals("foo: bar\n\nfoo", $response->__toString(), '->__toString() returns the headers and the content as a string');
    }

    public function testMagicToStringWithMultipleSetCookieHeader()
    {
        $headers = array(
            'content-type' => 'text/html; charset=utf-8',
            'set-cookie'   => array('foo=bar', 'bar=foo')
        );

        $expected = 'content-type: text/html; charset=utf-8'."\n";
        $expected.= 'set-cookie: foo=bar'."\n";
        $expected.= 'set-cookie: bar=foo'."\n\n";
        $expected.= 'foo';

        $response = new Response('foo', 304, $headers);

        $this->assertEquals($expected, $response->__toString(), '->__toString() returns the headers and the content as a string');
    }
}
PK=1[|����=BrowserKit/Symfony/Component/BrowserKit/Tests/RequestTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\BrowserKit\Tests;

use Symfony\Component\BrowserKit\Request;

class RequestTest extends \PHPUnit_Framework_TestCase
{
    public function testGetUri()
    {
        $request = new Request('http://www.example.com/', 'get');
        $this->assertEquals('http://www.example.com/', $request->getUri(), '->getUri() returns the URI of the request');
    }

    public function testGetMethod()
    {
        $request = new Request('http://www.example.com/', 'get');
        $this->assertEquals('get', $request->getMethod(), '->getMethod() returns the method of the request');
    }

    public function testGetParameters()
    {
        $request = new Request('http://www.example.com/', 'get', array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $request->getParameters(), '->getParameters() returns the parameters of the request');
    }

    public function testGetFiles()
    {
        $request = new Request('http://www.example.com/', 'get', array(), array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $request->getFiles(), '->getFiles() returns the uploaded files of the request');
    }

    public function testGetCookies()
    {
        $request = new Request('http://www.example.com/', 'get', array(), array(), array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $request->getCookies(), '->getCookies() returns the cookies of the request');
    }

    public function testGetServer()
    {
        $request = new Request('http://www.example.com/', 'get', array(), array(), array(), array('foo' => 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $request->getServer(), '->getServer() returns the server parameters of the request');
    }
}
PK@1[�p6ll8BrowserKit/Symfony/Component/BrowserKit/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony BrowserKit Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK@1[?7��EE4Net_IDNA2/tests/draft-josefsson-idn-test-vectors.phpnu�[���<?php
require_once 'Net/IDNA2.php';

// Test cases from https://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html

define('IDNA_ACE_PREFIX', 'xn--');

class IDNATest extends PHPUnit_Framework_TestCase {

    public function setUp() {
        $this->idn = new Net_IDNA2();
    }

    static function unichr($chr) {
        return mb_convert_encoding('&#' . intval($chr) . ';', 'UTF-8', 'HTML-ENTITIES');
    }

    private function hexarray2string($arr) {
        return implode('', array_map(array('self', 'unichr'), $arr));
    }

    public function testDecode1() {
        // Arabic (Egyptian)
        $expected = $this->hexarray2string(array(
            0x0644, 0x064A, 0x0647, 0x0645, 0x0627, 0x0628, 0x062A, 0x0643,
	        0x0644, 0x0645, 0x0648, 0x0634, 0x0639, 0x0631, 0x0628, 0x064A,
	        0x061F
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."egbpdaj6bu4bxfgehfvwxn");
        $this->assertSame($expected, $result);
    }

    public function testDecode2() {
        // Chinese (simplified)
        $expected = $this->hexarray2string(array(
            0x4ED6, 0x4EEC, 0x4E3A, 0x4EC0, 0x4E48, 0x4E0D, 0x8BF4, 0x4E2D, 0x6587
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."ihqwcrb4cv8a8dqg056pqjye");
        $this->assertSame($expected, $result);
    }

    public function testDecode3() {
        // Chinese (traditional)
        $expected = $this->hexarray2string(array(
            0x4ED6, 0x5011, 0x7232, 0x4EC0, 0x9EBD, 0x4E0D, 0x8AAA, 0x4E2D, 0x6587
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."ihqwctvzc91f659drss3x8bo0yb");
        $this->assertSame($expected, $result);
    }

    public function testDecode4() {
        // Czech
        $expected = $this->hexarray2string(array(
            0x0050, 0x0072, 0x006F, 0x010D, 0x0070, 0x0072, 0x006F, 0x0073,
	        0x0074, 0x011B, 0x006E, 0x0065, 0x006D, 0x006C, 0x0075, 0x0076,
	        0x00ED, 0x010D, 0x0065, 0x0073, 0x006B, 0x0079
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."Proprostnemluvesky-uyb24dma41a");
        $this->assertSame($expected, $result);
    }

    public function testDecode5() {
        // Hebrew
        $expected = $this->hexarray2string(array(
            0x05DC, 0x05DE, 0x05D4, 0x05D4, 0x05DD, 0x05E4, 0x05E9, 0x05D5,
	        0x05D8, 0x05DC, 0x05D0, 0x05DE, 0x05D3, 0x05D1, 0x05E8, 0x05D9,
	        0x05DD, 0x05E2, 0x05D1, 0x05E8, 0x05D9, 0x05EA
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."4dbcagdahymbxekheh6e0a7fei0b");
        $this->assertSame($expected, $result);
    }

      public function testDecode6() {
        // Hindi (Devanagari)
        $expected = $this->hexarray2string(array(
            0x092F, 0x0939, 0x0932, 0x094B, 0x0917, 0x0939, 0x093F, 0x0928,
        	0x094D, 0x0926, 0x0940, 0x0915, 0x094D, 0x092F, 0x094B, 0x0902,
	        0x0928, 0x0939, 0x0940, 0x0902, 0x092C, 0x094B, 0x0932, 0x0938,
	        0x0915, 0x0924, 0x0947, 0x0939, 0x0948, 0x0902
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd");
        $this->assertSame($expected, $result);
    }

    public function testDecode7() {
        // Japanese (kanji and hiragana)
        $expected = $this->hexarray2string(array(
            0x306A, 0x305C, 0x307F, 0x3093, 0x306A, 0x65E5, 0x672C, 0x8A9E,
        	0x3092, 0x8A71, 0x3057, 0x3066, 0x304F, 0x308C, 0x306A, 0x3044,
        	0x306E, 0x304B
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa");
        $this->assertSame($expected, $result);
    }

    public function testDecode8() {
        // Russian (Cyrillic)
        $expected = $this->hexarray2string(array(
            0x043F, 0x043E, 0x0447, 0x0435, 0x043C, 0x0443, 0x0436, 0x0435,
        	0x043E, 0x043D, 0x0438, 0x043D, 0x0435, 0x0433, 0x043E, 0x0432,
        	0x043E, 0x0440, 0x044F, 0x0442, 0x043F, 0x043E, 0x0440, 0x0443,
        	0x0441, 0x0441, 0x043A, 0x0438
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."b1abfaaepdrnnbgefbadotcwatmq2g4l");
        $this->assertSame($expected, $result);
    }

    public function testDecode9() {
        // Spanish
        $expected = $this->hexarray2string(array(
            0x0050, 0x006F, 0x0072, 0x0071, 0x0075, 0x00E9, 0x006E, 0x006F,
        	0x0070, 0x0075, 0x0065, 0x0064, 0x0065, 0x006E, 0x0073, 0x0069,
        	0x006D, 0x0070, 0x006C, 0x0065, 0x006D, 0x0065, 0x006E, 0x0074,
        	0x0065, 0x0068, 0x0061, 0x0062, 0x006C, 0x0061, 0x0072, 0x0065,
        	0x006E, 0x0045, 0x0073, 0x0070, 0x0061, 0x00F1, 0x006F, 0x006C
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."PorqunopuedensimplementehablarenEspaol-fmd56a");
        $this->assertSame($expected, $result);
    }

    public function testDecode10() {
        // Vietnamese
        $expected = $this->hexarray2string(array(
            0x0054, 0x1EA1, 0x0069, 0x0073, 0x0061, 0x006F, 0x0068, 0x1ECD,
        	0x006B, 0x0068, 0x00F4, 0x006E, 0x0067, 0x0074, 0x0068, 0x1EC3,
        	0x0063, 0x0068, 0x1EC9, 0x006E, 0x00F3, 0x0069, 0x0074, 0x0069,
        	0x1EBF, 0x006E, 0x0067, 0x0056, 0x0069, 0x1EC7, 0x0074
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g");
        $this->assertSame($expected, $result);
    }

    public function testDecode11() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x0033, 0x5E74, 0x0042, 0x7D44, 0x91D1, 0x516B, 0x5148, 0x751F
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."3B-ww4c5e180e575a65lsy2b");
        $this->assertSame($expected, $result);
    }

    public function testDecode12() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x5B89, 0x5BA4, 0x5948, 0x7F8E, 0x6075, 0x002D, 0x0077, 0x0069,
        	0x0074, 0x0068, 0x002D, 0x0053, 0x0055, 0x0050, 0x0045, 0x0052,
        	0x002D, 0x004D, 0x004F, 0x004E, 0x004B, 0x0045, 0x0059, 0x0053
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n");
        $this->assertSame($expected, $result);
    }

    public function testDecode13() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x0048, 0x0065, 0x006C, 0x006C, 0x006F, 0x002D, 0x0041, 0x006E,
	        0x006F, 0x0074, 0x0068, 0x0065, 0x0072, 0x002D, 0x0057, 0x0061,
        	0x0079, 0x002D, 0x305D, 0x308C, 0x305E, 0x308C, 0x306E, 0x5834,
        	0x6240
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."Hello-Another-Way--fc4qua05auwb3674vfr0b");
        $this->assertSame($expected, $result);
    }

    public function testDecode14() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x3072, 0x3068, 0x3064, 0x5C4B, 0x6839, 0x306E, 0x4E0B, 0x0032
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."2-u9tlzr9756bt3uc0v");
        $this->assertSame($expected, $result);
    }

    public function testDecode15() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x004D, 0x0061, 0x006A, 0x0069, 0x3067, 0x004B, 0x006F, 0x0069,
        	0x3059, 0x308B, 0x0035, 0x79D2, 0x524D
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."MajiKoi5-783gue6qz075azm5e");
        $this->assertSame($expected, $result);
    }

    public function testDecode16() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x30D1, 0x30D5, 0x30A3, 0x30FC, 0x0064, 0x0065, 0x30EB, 0x30F3, 0x30D0
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."de-jg4avhby1noc0d");
        $this->assertSame($expected, $result);
    }

    public function testDecode17() {
        // Japanese
        $expected = $this->hexarray2string(array(
            0x305D, 0x306E, 0x30B9, 0x30D4, 0x30FC, 0x30C9, 0x3067
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."d9juau41awczczp");
        $this->assertSame($expected, $result);
    }

    public function testDecode18() {
        // Greek
        $expected = $this->hexarray2string(array(
            0x03b5, 0x03bb, 0x03bb, 0x03b7, 0x03bd, 0x03b9, 0x03ba, 0x03ac
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."hxargifdar");
        $this->assertSame($expected, $result);
    }

    public function testDecode19() {
        // Maltese (Malti)
        $expected = $this->hexarray2string(array(
            0x0062, 0x006f, 0x006e, 0x0121, 0x0075, 0x0073, 0x0061, 0x0127,
            0x0127, 0x0061
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."bonusaa-5bb1da");
        $this->assertSame($expected, $result);
    }

    public function testDecode20() {
        // Russian (Cyrillic)
        $expected = $this->hexarray2string(array(
            0x043f, 0x043e, 0x0447, 0x0435, 0x043c, 0x0443, 0x0436, 0x0435,
            0x043e, 0x043d, 0x0438, 0x043d, 0x0435, 0x0433, 0x043e, 0x0432,
            0x043e, 0x0440, 0x044f, 0x0442, 0x043f, 0x043e, 0x0440, 0x0443,
            0x0441, 0x0441, 0x043a, 0x0438
	    ));
        $result = $this->idn->decode(IDNA_ACE_PREFIX."b1abfaaepdrnnbgefbadotcwatmq2g4l");
        $this->assertSame($expected, $result);
    }

    public function testEncode1() {
        // Arabic (Egyptian)
        $idna = $this->hexarray2string(array(
            0x0644, 0x064A, 0x0647, 0x0645, 0x0627, 0x0628, 0x062A, 0x0643,
	        0x0644, 0x0645, 0x0648, 0x0634, 0x0639, 0x0631, 0x0628, 0x064A,
	        0x061F
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."egbpdaj6bu4bxfgehfvwxn", $result);
    }

    public function testEncode2() {
        // Chinese (simplified)
        $idna = $this->hexarray2string(array(
            0x4ED6, 0x4EEC, 0x4E3A, 0x4EC0, 0x4E48, 0x4E0D, 0x8BF4, 0x4E2D, 0x6587
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."ihqwcrb4cv8a8dqg056pqjye", $result);
    }

    public function testEncode3() {
        // Chinese (traditional)
        $idna = $this->hexarray2string(array(
            0x4ED6, 0x5011, 0x7232, 0x4EC0, 0x9EBD, 0x4E0D, 0x8AAA, 0x4E2D, 0x6587
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."ihqwctvzc91f659drss3x8bo0yb", $result);
    }

    public function testEncode4() {
        // Czech
        $idna = $this->hexarray2string(array(
            0x0050, 0x0072, 0x006F, 0x010D, 0x0070, 0x0072, 0x006F, 0x0073,
	        0x0074, 0x011B, 0x006E, 0x0065, 0x006D, 0x006C, 0x0075, 0x0076,
	        0x00ED, 0x010D, 0x0065, 0x0073, 0x006B, 0x0079
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."proprostnemluvesky-uyb24dma41a", $result);
    }

    public function testEncode5() {
        // Hebrew
        $idna = $this->hexarray2string(array(
            0x05DC, 0x05DE, 0x05D4, 0x05D4, 0x05DD, 0x05E4, 0x05E9, 0x05D5,
	        0x05D8, 0x05DC, 0x05D0, 0x05DE, 0x05D3, 0x05D1, 0x05E8, 0x05D9,
	        0x05DD, 0x05E2, 0x05D1, 0x05E8, 0x05D9, 0x05EA
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."4dbcagdahymbxekheh6e0a7fei0b", $result);
    }

      public function testEncode6() {
        // Hindi (Devanagari)
        $idna = $this->hexarray2string(array(
            0x092F, 0x0939, 0x0932, 0x094B, 0x0917, 0x0939, 0x093F, 0x0928,
        	0x094D, 0x0926, 0x0940, 0x0915, 0x094D, 0x092F, 0x094B, 0x0902,
	        0x0928, 0x0939, 0x0940, 0x0902, 0x092C, 0x094B, 0x0932, 0x0938,
	        0x0915, 0x0924, 0x0947, 0x0939, 0x0948, 0x0902
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", $result);
    }

    public function testEncode7() {
        // Japanese (kanji and hiragana)
        $idna = $this->hexarray2string(array(
            0x306A, 0x305C, 0x307F, 0x3093, 0x306A, 0x65E5, 0x672C, 0x8A9E,
        	0x3092, 0x8A71, 0x3057, 0x3066, 0x304F, 0x308C, 0x306A, 0x3044,
        	0x306E, 0x304B
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", $result);
    }

    public function testEncode8() {
        // Russian (Cyrillic)
        $idna = $this->hexarray2string(array(
            0x043F, 0x043E, 0x0447, 0x0435, 0x043C, 0x0443, 0x0436, 0x0435,
        	0x043E, 0x043D, 0x0438, 0x043D, 0x0435, 0x0433, 0x043E, 0x0432,
        	0x043E, 0x0440, 0x044F, 0x0442, 0x043F, 0x043E, 0x0440, 0x0443,
        	0x0441, 0x0441, 0x043A, 0x0438
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."b1abfaaepdrnnbgefbadotcwatmq2g4l", $result);
    }

    public function testEncode9() {
        // Spanish
        $idna = $this->hexarray2string(array(
            0x0050, 0x006F, 0x0072, 0x0071, 0x0075, 0x00E9, 0x006E, 0x006F,
        	0x0070, 0x0075, 0x0065, 0x0064, 0x0065, 0x006E, 0x0073, 0x0069,
        	0x006D, 0x0070, 0x006C, 0x0065, 0x006D, 0x0065, 0x006E, 0x0074,
        	0x0065, 0x0068, 0x0061, 0x0062, 0x006C, 0x0061, 0x0072, 0x0065,
        	0x006E, 0x0045, 0x0073, 0x0070, 0x0061, 0x00F1, 0x006F, 0x006C
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."porqunopuedensimplementehablarenespaol-fmd56a", $result);
    }

    public function testEncode10() {
        // Vietnamese
        $idna = $this->hexarray2string(array(
            0x0054, 0x1EA1, 0x0069, 0x0073, 0x0061, 0x006F, 0x0068, 0x1ECD,
        	0x006B, 0x0068, 0x00F4, 0x006E, 0x0067, 0x0074, 0x0068, 0x1EC3,
        	0x0063, 0x0068, 0x1EC9, 0x006E, 0x00F3, 0x0069, 0x0074, 0x0069,
        	0x1EBF, 0x006E, 0x0067, 0x0056, 0x0069, 0x1EC7, 0x0074
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."tisaohkhngthchnitingvit-kjcr8268qyxafd2f1b9g", $result);
    }

    public function testEncode11() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x0033, 0x5E74, 0x0042, 0x7D44, 0x91D1, 0x516B, 0x5148, 0x751F
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."3b-ww4c5e180e575a65lsy2b", $result);
    }

    public function testEncode12() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x5B89, 0x5BA4, 0x5948, 0x7F8E, 0x6075, 0x002D, 0x0077, 0x0069,
        	0x0074, 0x0068, 0x002D, 0x0053, 0x0055, 0x0050, 0x0045, 0x0052,
        	0x002D, 0x004D, 0x004F, 0x004E, 0x004B, 0x0045, 0x0059, 0x0053
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."-with-super-monkeys-pc58ag80a8qai00g7n9n", $result);
    }

    public function testEncode13() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x0048, 0x0065, 0x006C, 0x006C, 0x006F, 0x002D, 0x0041, 0x006E,
	        0x006F, 0x0074, 0x0068, 0x0065, 0x0072, 0x002D, 0x0057, 0x0061,
        	0x0079, 0x002D, 0x305D, 0x308C, 0x305E, 0x308C, 0x306E, 0x5834,
        	0x6240
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."hello-another-way--fc4qua05auwb3674vfr0b", $result);
    }

    public function testEncode14() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x3072, 0x3068, 0x3064, 0x5C4B, 0x6839, 0x306E, 0x4E0B, 0x0032
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."2-u9tlzr9756bt3uc0v", $result);
    }

    public function testEncode15() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x004D, 0x0061, 0x006A, 0x0069, 0x3067, 0x004B, 0x006F, 0x0069,
        	0x3059, 0x308B, 0x0035, 0x79D2, 0x524D
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."majikoi5-783gue6qz075azm5e", $result);
    }

    public function testEncode16() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x30D1, 0x30D5, 0x30A3, 0x30FC, 0x0064, 0x0065, 0x30EB, 0x30F3, 0x30D0
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."de-jg4avhby1noc0d", $result);
    }

    public function testEncode17() {
        // Japanese
        $idna = $this->hexarray2string(array(
            0x305D, 0x306E, 0x30B9, 0x30D4, 0x30FC, 0x30C9, 0x3067
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."d9juau41awczczp", $result);
    }

    public function testEncode18() {
        // Greek
        $idna = $this->hexarray2string(array(
            0x03b5, 0x03bb, 0x03bb, 0x03b7, 0x03bd, 0x03b9, 0x03ba, 0x03ac
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."hxargifdar", $result);
    }

    public function testEncode19() {
        // Maltese (Malti)
        $idna = $this->hexarray2string(array(
            0x0062, 0x006f, 0x006e, 0x0121, 0x0075, 0x0073, 0x0061, 0x0127,
            0x0127, 0x0061
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."bonusaa-5bb1da", $result);
    }

    public function testEncode20() {
        // Russian (Cyrillic)
        $idna = $this->hexarray2string(array(
            0x043f, 0x043e, 0x0447, 0x0435, 0x043c, 0x0443, 0x0436, 0x0435,
            0x043e, 0x043d, 0x0438, 0x043d, 0x0435, 0x0433, 0x043e, 0x0432,
            0x043e, 0x0440, 0x044f, 0x0442, 0x043f, 0x043e, 0x0440, 0x0443,
            0x0441, 0x0441, 0x043a, 0x0438
	    ));
        $result = $this->idn->encode($idna);
        $this->assertSame(IDNA_ACE_PREFIX."b1abfaaepdrnnbgefbadotcwatmq2g4l", $result);
    }

}

PK@1[E��mm!Net_IDNA2/tests/Net_IDNA2Test.phpnu�[���<?php
require_once 'Net/IDNA2.php';

class Net_IDNA2Test extends PHPUnit_Framework_TestCase
{
    /**
     * Initialise tests
     *
     * @return void
     */
    public function setUp()
    {
        $this->idn = new Net_IDNA2();
    }

    /**
     * Test if a complete URL consisting also of port-number etc. will be decoded just fine, test 1
     *
     * @return void
     */
    public function testShouldDecodePortNumbersFragmentsAndUrisCorrectly1()
    {
        $result = $this->idn->decode('http://www.xn--ml-6kctd8d6a.org:8080/test.php?arg1=1&arg2=2#fragment');
        $this->assertSame("http://www.\xD0\xB5\xD1\x85\xD0\xB0m\xD1\x80l\xD0\xB5.org:8080/test.php?arg1=1&arg2=2#fragment", $result);
    }

    /**
     * Test if a complete URL consisting also of port-number etc. will be decoded just fine, test 2
     *
     * @return void
     */
    public function testShouldDecodePortNumbersFragmentsAndUrisCorrectly2()
    {
        $result = $this->idn->decode('http://xn--tst-qla.example.com:8080/test.php?arg1=1&arg2=2#fragment');
        $this->assertSame("http://täst.example.com:8080/test.php?arg1=1&arg2=2#fragment", $result);
    }

    /**
     * Test encoding of German letter Eszett according to the original standard (IDNA2003)
     *
     * @return void
     */
    public function testEncodingForGermanEszettUsingIDNA2003()
    {
        // make sure to use 2003-encoding
        $this->idn->setParams('version', '2003');
        $result = $this->idn->encode('http://www.straße.example.com/');

        $this->assertSame("http://www.strasse.example.com/", $result);
    }

    /**
     * Test encoding of German letter Eszett according to the "new" standard (IDNA2005/IDNAbis)
     *
     * @return void
     */
    public function testEncodingForGermanEszettUsingIDNA2008()
    {
        // make sure to use 2008-encoding
        $this->idn->setParams('version', '2008');
        $result = $this->idn->encode('http://www.straße.example.com/');
        // switch back for other testcases
        $this->idn->setParams('version', '2003');

        $this->assertSame("http://www.xn--strae-oqa.example.com/", $result);
    }
}
PK@1[.��
��XML_RPC/tests/extra-lines.phpnu�[���<?php

/**
 * Tests how the XML_RPC server handles parameters with empty values.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: extra-lines.php 300958 2010-07-02 23:58:51Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.4.4
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC.php';


$input = "First lfs\n\nSecond crlfs\r\n\r\nThird crs\r\rFourth line";

$expect_removed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<methodCall>\r\n<methodName>nada</methodName>\r\n<params>\r\n<param>\r\n<value><string>First lfs\r\nSecond crlfs\r\nThird crs\r\nFourth line</string></value>\r\n</param>\r\n</params>\r\n</methodCall>\r\n";

$expect_not_removed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<methodCall>\r\n<methodName>nada</methodName>\r\n<params>\r\n<param>\r\n<value><string>First lfs\r\n\r\nSecond crlfs\r\n\r\nThird crs\r\n\r\nFourth line</string></value>\r\n</param>\r\n</params>\r\n</methodCall>\r\n";

$msg = new XML_RPC_Message('nada', array(XML_RPC_encode($input)));
$msg->createPayload();
if ($msg->payload == $expect_removed) {
    echo "passed\n";
} else {
    echo "PROBLEM\n";
}

$msg = new XML_RPC_Message('nada', array(XML_RPC_encode($input)));
$msg->remove_extra_lines = false;
$msg->createPayload();
if ($msg->payload == $expect_not_removed) {
    echo "passed\n";
} else {
    echo "PROBLEM\n";
}
PK@1[|�E$XML_RPC/tests/empty-value-struct.phpnu�[���<?php

/**
 * Tests how the XML_RPC server handles a parameter with an empty struct without
 * any spaces in the XML after the empty value.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: empty-value-struct.php 300957 2010-07-02 23:55:00Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.4.4
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC/Server.php';


$GLOBALS['HTTP_RAW_POST_DATA'] = <<<EOPOST
<?xml version="1.0"?>
<methodCall>
 <methodName>allgot</methodName>
  <params>
   <param>
    <value>
     <struct>
      <member>
      <name>fld1</name><value></value></member></struct></value>
   </param>
  </params>
 </methodCall>
EOPOST;

$expect = <<<EOEXP
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value><string>param 0: array (
  'fld1' =&gt; '',
)
</string></value>
</param>
</params>
</methodResponse>
EOEXP;

include './allgot.inc';
PK@1[�3l�**XML_RPC/tests/protoport.phpnu�[���<?php

/**
 * Tests that properties of XML_RPC_Client get properly set
 *
 * Any individual tests that fail will have their name, expected result
 * and actual result printed out.  So seeing no output when executing
 * this file is a good thing.
 *
 * Can be run via CLI or a web server.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: protoport.php 300957 2010-07-02 23:55:00Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.2
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC.php';


/**
 * Compare the test result to the expected result
 *
 * If the test fails, echo out the results.
 *
 * @param array  $expect     the array of object properties you expect
 *                            from the test
 * @param object $actual     the object results from the test
 * @param string $test_name  the name of the test
 *
 * @return void
 */
function compare($expect, $actual, $test_name) {
    $actual = get_object_vars($actual);
    if (count(array_diff($actual, $expect))) {
        echo "$test_name failed.\nExpect: ";
        print_r($expect);
        echo "Actual: ";
        print_r($actual);
        echo "\n";
    }
}

if (php_sapi_name() != 'cli') {
    echo "<pre>\n";
}


$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 80,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver');
compare($x, $c, 'defaults');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 80,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'http://theserver');
compare($x, $c, 'defaults with http');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 443,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'https://theserver');
compare($x, $c, 'defaults with https');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 443,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'ssl://theserver');
compare($x, $c, 'defaults with ssl');


$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 65,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver', 65);
compare($x, $c, 'port 65');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 65,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'http://theserver', 65);
compare($x, $c, 'port 65 with http');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 65,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'https://theserver', 65);
compare($x, $c, 'port 65 with https');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 65,
    'proxy' => '',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'ssl://theserver', 65);
compare($x, $c, 'port 65 with ssl');


$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 80,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver', 0,
                        'theproxy');
compare($x, $c, 'defaults proxy');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 80,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'http://',
    'proxy_port' => 8080,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'http://theserver', 0,
                        'http://theproxy');
compare($x, $c, 'defaults with http proxy');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 443,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 443,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'https://theserver', 0,
                        'https://theproxy');
compare($x, $c, 'defaults with https proxy');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 443,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 443,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'ssl://theserver', 0,
                        'ssl://theproxy');
compare($x, $c, 'defaults with ssl proxy');


$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 65,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'http://',
    'proxy_port' => 6565,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver', 65,
                        'theproxy', 6565);
compare($x, $c, 'port 65 proxy 6565');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 65,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'http://',
    'proxy_port' => 6565,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'http://theserver', 65,
                        'http://theproxy', 6565);
compare($x, $c, 'port 65 with http proxy 6565');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 65,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 6565,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'https://theserver', 65,
                        'https://theproxy', 6565);
compare($x, $c, 'port 65 with https proxy 6565');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 65,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 6565,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'ssl://theserver', 65,
                        'ssl://theproxy', 6565);
compare($x, $c, 'port 65 with ssl proxy 6565');


$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'ssl://',
    'port' => 443,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 443,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver', 443,
                        'theproxy', 443);
compare($x, $c, 'port 443 no protocol and proxy port 443 no protocol');

$x = array(
    'path' => 'thepath',
    'server' => 'theserver',
    'protocol' => 'http://',
    'port' => 80,
    'proxy' => 'theproxy',
    'proxy_protocol' => 'ssl://',
    'proxy_port' => 6565,
    'proxy_user' => '',
    'proxy_pass' => '',
    'errno' => 0,
    'errstring' => '',
    'debug' => 0,
    'username' => '',
    'password' => '',
);
$c = new XML_RPC_Client('thepath', 'theserver', 0,
                        'ssl://theproxy', 6565);
compare($x, $c, 'port 443 no protocol and proxy port 443 no protocol');

echo "\nIf no other output was produced, these tests passed.\n";
PK@1[�B�XML_RPC/tests/allgot.incnu�[���<?php

/**
 * Parses the "return" value from some of our test scripts.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: allgot.inc 293223 2010-01-07 15:32:19Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.4.4
 */

ob_start();

function returnAllGot($params) {
    $out = '';
    $count = count($params->params);
    for ($i = 0; $i < $count; $i++) {
        $param = $params->getParam($i);
        if (!XML_RPC_Value::isValue($param)) {
            $out .= "parameter $i was error: $param\n";
            continue;
        }
        $got = XML_RPC_Decode($param);
        $out .= "param $i: " . var_export($got, true) . "\n";
    }
    $val = new XML_RPC_Value($out, 'string');
    return new XML_RPC_Response($val);
}

$server = new XML_RPC_Server(
    array(
        'allgot' => array(
            'function' => 'returnAllGot',
        ),
    )
);

$got = ob_get_clean();

if ($got == $expect) {
    echo "passed\n";
} else {
    echo "FAILED\n";
    echo "Expected:\n$expect\n";
    echo "Got:\n$got\n";
}
PK@1[��̢�	�	XML_RPC/tests/types.phpnu�[���<?php

/**
 * Tests how the XML_RPC server handles a bunch of different parameter
 * data types.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: types.php 300957 2010-07-02 23:55:00Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.4.4
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC/Server.php';


$GLOBALS['HTTP_RAW_POST_DATA'] = <<<EOPOST
<?xml version="1.0"?>
<methodCall>
 <methodName>allgot</methodName>
  <params>
   <param><value>default to string</value></param>
   <param><value><string>inside string</string></value></param>
   <param><value><int>8</int></value></param>
   <param><value><datetime.iso8601>20050809T01:33:44</datetime.iso8601></value></param>

   <param>
    <value>
     <array>
      <data>
       <value>
        <string>a</string>
       </value>
       <value>
        <string>b</string>
       </value>
      </data>
     </array>
    </value>
   </param>

   <param>
    <value>
     <struct>
      <member>
       <name>a</name>
       <value>
        <string>ay</string>
       </value>
      </member>
      <member>
       <name>b</name>
       <value>
        <string>be</string>
       </value>
      </member>
     </struct>
    </value>
   </param>

  </params>
 </methodCall>
EOPOST;

$expect = <<<EOEXP
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value><string>param 0: 'default to string'
param 1: 'inside string'
param 2: '8'
param 3: '20050809T01:33:44'
param 4: array (
  0 =&gt; 'a',
  1 =&gt; 'b',
)
param 5: array (
  'a' =&gt; 'ay',
  'b' =&gt; 'be',
)
</string></value>
</param>
</params>
</methodResponse>
EOEXP;

include './allgot.inc';
PK@1[J����XML_RPC/tests/encode.phpnu�[���<?php

/**
 * Tests encoding values.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: extra-lines.php 293218 2010-01-07 14:20:08Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.5.3
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC.php';


$input = array(10, 11, 12);

$expect = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
<methodName>nada</methodName>
<params>
<param>
<value><array>
<data>
<value><int>10</int></value>
<value><int>11</int></value>
<value><int>12</int></value>
</data>
</array></value>
</param>
</params>
</methodCall>
EOT;

$expect = trim(preg_replace("/\r\n/", "\n", $expect));

$msg = new XML_RPC_Message('nada', array(XML_RPC_encode($input)));
$msg->createPayload();
$actual = trim(preg_replace("/\r\n/", "\n", $msg->payload));
if ($actual == $expect) {
    echo "passed\n";
} else {
    echo "PROBLEM\n";
    echo $actual;
}

$msg = new XML_RPC_Message('nada',
    array(
        new XML_RPC_Value(
            array(
                new XML_RPC_Value(10, 'int'),
                new XML_RPC_Value(11, 'int'),
                new XML_RPC_Value(12, 'int'),
            ),
            'array'
        )
    )
);
$msg->createPayload();
$actual = trim(preg_replace("/\r\n/", "\n", $msg->payload));
if ($actual == $expect) {
    echo "passed\n";
} else {
    echo "PROBLEM\n";
    echo $actual;
}
PK@1[���XXXML_RPC/tests/test_Dump.phpnu�[���<?php

/**
 * Actually performs an XML_RPC request.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: test_Dump.php 300962 2010-07-03 02:24:24Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC/Dump.php';


$val = new XML_RPC_Value(array(
    'title'    =>new XML_RPC_Value('das ist der Titel', 'string'),
    'startDate'=>new XML_RPC_Value(mktime(0,0,0,13,11,2004), 'dateTime.iso8601'),
    'endDate'  =>new XML_RPC_Value(mktime(0,0,0,15,11,2004), 'dateTime.iso8601'),
    'arkey'    => new XML_RPC_Value( array(
        new XML_RPC_Value('simple string'),
        new XML_RPC_Value(12345, 'int')
        ), 'array')
    )
    ,'struct');

XML_RPC_Dump($val);

echo '==============' . "\r\n";
$val2 = new XML_RPC_Value(44353, 'int');
XML_RPC_Dump($val2);

echo '==============' . "\r\n";
$val3 = new XML_RPC_Value('this should be a string', 'string');
XML_RPC_Dump($val3);

echo '==============' . "\r\n";
$val4 = new XML_RPC_Value(true, 'boolean');
XML_RPC_Dump($val4);

echo '==============' . "\r\n";
echo 'Next we will test the error handling...' . "\r\n";
$val5 = new XML_RPC_Value(array(
    'foo' => 'bar'
    ), 'struct');
XML_RPC_Dump($val5);

echo '==============' . "\r\n";
echo 'DONE' . "\r\n";
PK@1[$]���XML_RPC/tests/empty-value.phpnu�[���<?php

/**
 * Tests how the XML_RPC server handles parameters with empty values.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: empty-value.php 300957 2010-07-02 23:55:00Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.4.4
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC/Server.php';


$GLOBALS['HTTP_RAW_POST_DATA'] = <<<EOPOST
<?xml version="1.0"?>
<methodCall>
 <methodName>allgot</methodName>
  <params>
   <param><value><string></string></value></param>
   <param><value>first</value></param>
   <param><value>  </value></param>
   <param><value></value></param>
  </params>
 </methodCall>
EOPOST;

$expect = <<<EOEXP
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value><string>param 0: ''
param 1: 'first'
param 2: '  '
param 3: ''
</string></value>
</param>
</params>
</methodResponse>
EOEXP;

include './allgot.inc';
PK@1[b��))) XML_RPC/tests/actual-request.phpnu�[���<?php

/**
 * Actually performs an XML_RPC request.
 *
 * PHP versions 4 and 5
 *
 * @category   Web Services
 * @package    XML_RPC
 * @author     Daniel Convissor <danielc@php.net>
 * @copyright  2005-2010 The PHP Group
 * @license    http://www.php.net/license/3_01.txt  PHP License
 * @version    SVN: $Id: actual-request.php 300957 2010-07-02 23:55:00Z danielc $
 * @link       http://pear.php.net/package/XML_RPC
 * @since      File available since Release 1.5.3
 */

/*
 * If the package version number is found in the left hand
 * portion of the if() expression below, that means this file has
 * come from the PEAR installer.  Therefore, let's test the
 * installed version of XML_RPC which should be in the include path.
 *
 * If the version has not been substituted in the if() expression,
 * this file has likely come from a SVN checkout or a .tar file.
 * Therefore, we'll assume the tests should use the version of
 * XML_RPC that has come from there as well.
 */
if ('1.5.5' == '@'.'package_version'.'@') {
    ini_set('include_path', '../'
            . PATH_SEPARATOR . '.' . PATH_SEPARATOR
            . ini_get('include_path')
    );
}
require_once 'XML/RPC/Dump.php';


$debug = 0;

$params = array(
    new XML_RPC_Value('php.net', 'string'),
);
$msg = new XML_RPC_Message('domquery', $params);
$client = new XML_RPC_Client('/api/xmlrpc', 'www.adamsnames.com');
$client->setDebug($debug);

$resp = $client->send($msg);
if (!$resp) {
    echo 'Communication error: ' . $client->errstr;
    exit(1);
}
if ($resp->faultCode()) {
    /*
     * Display problems that have been gracefully cought and
     * reported by the xmlrpc.php script
     */
    echo 'Fault Code: ' . $resp->faultCode() . "\n";
    echo 'Fault Reason: ' . $resp->faultString() . "\n";
    exit(1);
}

$val = $resp->value();
XML_RPC_Dump($val);
PKA1[w�۴��HDomCrawler/Symfony/Component/DomCrawler/Tests/Fixtures/windows-1250.htmlnu�[���<html>
    <head>
        <meta http-equiv="content-type" content="text/html;charset=windows-1250">
    </head>
    <body>
        <p>���</p>
    </body>
</html>
PKA1[�x�CDomCrawler/Symfony/Component/DomCrawler/Tests/Fixtures/no-extensionnu�[���Test
PKA1[l�#8��=DomCrawler/Symfony/Component/DomCrawler/Tests/CrawlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests;

use Symfony\Component\CssSelector\CssSelector;
use Symfony\Component\DomCrawler\Crawler;

class CrawlerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $crawler = new Crawler();
        $this->assertCount(0, $crawler, '__construct() returns an empty crawler');

        $crawler = new Crawler(new \DOMNode());
        $this->assertCount(1, $crawler, '__construct() takes a node as a first argument');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::add
     */
    public function testAdd()
    {
        $crawler = new Crawler();
        $crawler->add($this->createDomDocument());
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMDocument');

        $crawler = new Crawler();
        $crawler->add($this->createNodeList());
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from a \DOMNodeList');

        foreach ($this->createNodeList() as $node) {
            $list[] = $node;
        }
        $crawler = new Crawler();
        $crawler->add($list);
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an array of nodes');

        $crawler = new Crawler();
        $crawler->add($this->createNodeList()->item(0));
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->add() adds nodes from an \DOMNode');

        $crawler = new Crawler();
        $crawler->add('<html><body>Foo</body></html>');
        $this->assertEquals('Foo', $crawler->filterXPath('//body')->text(), '->add() adds nodes from a string');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testAddInvalidNode()
    {
        $crawler = new Crawler();
        $crawler->add(1);
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContent()
    {
        $crawler = new Crawler();
        $crawler->addHtmlContent('<html><div class="foo"></html>', 'UTF-8');

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addHtmlContent() adds nodes from an HTML string');

        $crawler->addHtmlContent('<html><head><base href="http://symfony.com"></head><a href="/contact"></a></html>', 'UTF-8');

        $this->assertEquals('http://symfony.com', $crawler->filterXPath('//base')->attr('href'), '->addHtmlContent() adds nodes from an HTML string');
        $this->assertEquals('http://symfony.com/contact', $crawler->filterXPath('//a')->link()->getUri(), '->addHtmlContent() adds nodes from an HTML string');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContentCharset()
    {
        $crawler = new Crawler();
        $crawler->addHtmlContent('<html><div class="foo">Tiếng Việt</html>', 'UTF-8');

        $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContentInvalidBaseTag()
    {
        $crawler = new Crawler(null, 'http://symfony.com');

        $crawler->addHtmlContent('<html><head><base target="_top"></head><a href="/contact"></a></html>', 'UTF-8');

        $this->assertEquals('http://symfony.com/contact', current($crawler->filterXPath('//a')->links())->getUri(), '->addHtmlContent() correctly handles a non-existent base tag href attribute');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContentUnsupportedCharset()
    {
        $crawler = new Crawler();
        $crawler->addHtmlContent(file_get_contents(__DIR__.'/Fixtures/windows-1250.html'), 'Windows-1250');

        $this->assertEquals('Žťčýů', $crawler->filterXPath('//p')->text());
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContentCharsetGbk()
    {
        $crawler = new Crawler();
        //gbk encode of <html><p>中文</p></html>
        $crawler->addHtmlContent(base64_decode('PGh0bWw+PHA+1tDOxDwvcD48L2h0bWw+'), 'gbk');

        $this->assertEquals('中文', $crawler->filterXPath('//p')->text());
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addHtmlContent
     */
    public function testAddHtmlContentWithErrors()
    {
        $internalErrors = libxml_use_internal_errors(true);

        $crawler = new Crawler();
        $crawler->addHtmlContent(<<<EOF
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <nav><a href="#"><a href="#"></nav>
    </body>
</html>
EOF
        , 'UTF-8');

        $errors = libxml_get_errors();
        $this->assertCount(1, $errors);
        $this->assertEquals("Tag nav invalid\n", $errors[0]->message);

        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent
     */
    public function testAddXmlContent()
    {
        $crawler = new Crawler();
        $crawler->addXmlContent('<html><div class="foo"></div></html>', 'UTF-8');

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addXmlContent() adds nodes from an XML string');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent
     */
    public function testAddXmlContentCharset()
    {
        $crawler = new Crawler();
        $crawler->addXmlContent('<html><div class="foo">Tiếng Việt</div></html>', 'UTF-8');

        $this->assertEquals('Tiếng Việt', $crawler->filterXPath('//div')->text());
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addXmlContent
     */
    public function testAddXmlContentWithErrors()
    {
        $internalErrors = libxml_use_internal_errors(true);

        $crawler = new Crawler();
        $crawler->addXmlContent(<<<EOF
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <nav><a href="#"><a href="#"></nav>
    </body>
</html>
EOF
        , 'UTF-8');

        $this->assertTrue(count(libxml_get_errors()) > 1);

        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addContent
     */
    public function testAddContent()
    {
        $crawler = new Crawler();
        $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8');
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string');

        $crawler = new Crawler();
        $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8; dir=RTL');
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an HTML string with extended content type');

        $crawler = new Crawler();
        $crawler->addContent('<html><div class="foo"></html>');
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() uses text/html as the default type');

        $crawler = new Crawler();
        $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml; charset=UTF-8');
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');

        $crawler = new Crawler();
        $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml');
        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addContent() adds nodes from an XML string');

        $crawler = new Crawler();
        $crawler->addContent('foo bar', 'text/plain');
        $this->assertCount(0, $crawler, '->addContent() does nothing if the type is not (x|ht)ml');

        $crawler = new Crawler();
        $crawler->addContent('<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><span>中文</span></html>');
        $this->assertEquals('中文', $crawler->filterXPath('//span')->text(), '->addContent() guess wrong charset');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addDocument
     */
    public function testAddDocument()
    {
        $crawler = new Crawler();
        $crawler->addDocument($this->createDomDocument());

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addDocument() adds nodes from a \DOMDocument');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addNodeList
     */
    public function testAddNodeList()
    {
        $crawler = new Crawler();
        $crawler->addNodeList($this->createNodeList());

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodeList() adds nodes from a \DOMNodeList');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addNodes
     */
    public function testAddNodes()
    {
        foreach ($this->createNodeList() as $node) {
            $list[] = $node;
        }

        $crawler = new Crawler();
        $crawler->addNodes($list);

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNodes() adds nodes from an array of nodes');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::addNode
     */
    public function testAddNode()
    {
        $crawler = new Crawler();
        $crawler->addNode($this->createNodeList()->item(0));

        $this->assertEquals('foo', $crawler->filterXPath('//div')->attr('class'), '->addNode() adds nodes from an \DOMNode');
    }

    public function testClear()
    {
        $crawler = new Crawler(new \DOMNode());
        $crawler->clear();
        $this->assertCount(0, $crawler, '->clear() removes all the nodes from the crawler');
    }

    public function testEq()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li');
        $this->assertNotSame($crawler, $crawler->eq(0), '->eq() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->eq() returns a new instance of a crawler');

        $this->assertEquals('Two', $crawler->eq(1)->text(), '->eq() returns the nth node of the list');
        $this->assertCount(0, $crawler->eq(100), '->eq() returns an empty crawler if the nth node does not exist');
    }

    public function testEach()
    {
        $data = $this->createTestCrawler()->filterXPath('//ul[1]/li')->each(function ($node, $i) {
            return $i.'-'.$node->text();
        });

        $this->assertEquals(array('0-One', '1-Two', '2-Three'), $data, '->each() executes an anonymous function on each node of the list');
    }

    public function testReduce()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
        $nodes = $crawler->reduce(function ($node, $i) {
            return $i == 1 ? false : true;
        });
        $this->assertNotSame($nodes, $crawler, '->reduce() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $nodes, '->reduce() returns a new instance of a crawler');

        $this->assertCount(2, $nodes, '->reduce() filters the nodes in the list');
    }

    public function testAttr()
    {
        $this->assertEquals('first', $this->createTestCrawler()->filterXPath('//li')->attr('class'), '->attr() returns the attribute of the first element of the node list');

        try {
            $this->createTestCrawler()->filterXPath('//ol')->attr('class');
            $this->fail('->attr() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testMissingAttrValueIsNull()
    {
        $crawler = new Crawler();
        $crawler->addContent('<html><div non-empty-attr="sample value" empty-attr=""></div></html>', 'text/html; charset=UTF-8');
        $div = $crawler->filterXPath('//div');

        $this->assertEquals('sample value', $div->attr('non-empty-attr'), '->attr() reads non-empty attributes correctly');
        $this->assertEquals('', $div->attr('empty-attr'), '->attr() reads empty attributes correctly');
        $this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly');
    }

    public function testText()
    {
        $this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list');

        try {
            $this->createTestCrawler()->filterXPath('//ol')->text();
            $this->fail('->text() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->text() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testHtml()
    {
        $this->assertEquals('<img alt="Bar">', $this->createTestCrawler()->filterXPath('//a[5]')->html());
        $this->assertEquals('<input type="text" value="TextValue" name="TextName"><input type="submit" value="FooValue" name="FooName" id="FooId"><input type="button" value="BarValue" name="BarName" id="BarId"><button value="ButtonValue" name="ButtonName" id="ButtonId"></button>'
            , trim($this->createTestCrawler()->filterXPath('//form[@id="FooFormId"]')->html()));

        try {
            $this->createTestCrawler()->filterXPath('//ol')->html();
            $this->fail('->html() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testExtract()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');

        $this->assertEquals(array('One', 'Two', 'Three'), $crawler->extract('_text'), '->extract() returns an array of extracted data from the node list');
        $this->assertEquals(array(array('One', 'first'), array('Two', ''), array('Three', '')), $crawler->extract(array('_text', 'class')), '->extract() returns an array of extracted data from the node list');

        $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->extract('_text'), '->extract() returns an empty array if the node list is empty');
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::filterXPath
     */
    public function testFilterXPath()
    {
        $crawler = $this->createTestCrawler();
        $this->assertNotSame($crawler, $crawler->filterXPath('//li'), '->filterXPath() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filterXPath() returns a new instance of a crawler');

        $crawler = $this->createTestCrawler()->filterXPath('//ul');

        $this->assertCount(6, $crawler->filterXPath('//li'), '->filterXPath() filters the node list with the XPath expression');
    }

    public function testFilterXPathWithDefaultNamespace()
    {
        $crawler = $this->createTestXmlCrawler()->filterXPath('//default:entry/default:id');
        $this->assertCount(1, $crawler, '->filterXPath() automatically registers a namespace');
        $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
    }

    public function testFilterXPathWithCustomDefaultNamespace()
    {
        $crawler = $this->createTestXmlCrawler();
        $crawler->setDefaultNamespacePrefix('x');
        $crawler = $crawler->filterXPath('//x:entry/x:id');

        $this->assertCount(1, $crawler, '->filterXPath() lets to override the default namespace prefix');
        $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
    }

    public function testFilterXPathWithNamespace()
    {
        $crawler = $this->createTestXmlCrawler()->filterXPath('//yt:accessControl');
        $this->assertCount(2, $crawler, '->filterXPath() automatically registers a namespace');
    }

    public function testFilterXPathWithMultipleNamespaces()
    {
        $crawler = $this->createTestXmlCrawler()->filterXPath('//media:group/yt:aspectRatio');
        $this->assertCount(1, $crawler, '->filterXPath() automatically registers multiple namespaces');
        $this->assertSame('widescreen', $crawler->text());
    }

    public function testFilterXPathWithManuallyRegisteredNamespace()
    {
        $crawler = $this->createTestXmlCrawler();
        $crawler->registerNamespace('m', 'http://search.yahoo.com/mrss/');

        $crawler = $crawler->filterXPath('//m:group/yt:aspectRatio');
        $this->assertCount(1, $crawler, '->filterXPath() uses manually registered namespace');
        $this->assertSame('widescreen', $crawler->text());
    }

    public function testFilterXPathWithAnUrl()
    {
        $crawler = $this->createTestXmlCrawler();

        $crawler = $crawler->filterXPath('//media:category[@scheme="http://gdata.youtube.com/schemas/2007/categories.cat"]');
        $this->assertCount(1, $crawler);
        $this->assertSame('Music', $crawler->text());
    }

    /**
     * @covers Symfony\Component\DomCrawler\Crawler::filter
     */
    public function testFilter()
    {
        $crawler = $this->createTestCrawler();
        $this->assertNotSame($crawler, $crawler->filter('li'), '->filter() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->filter() returns a new instance of a crawler');

        $crawler = $this->createTestCrawler()->filter('ul');

        $this->assertCount(6, $crawler->filter('li'), '->filter() filters the node list with the CSS selector');
    }

    public function testFilterWithDefaultNamespace()
    {
        $crawler = $this->createTestXmlCrawler()->filter('default|entry default|id');
        $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
        $this->assertSame('tag:youtube.com,2008:video:kgZRZmEc9j4', $crawler->text());
    }

    public function testFilterWithNamespace()
    {
        CssSelector::disableHtmlExtension();

        $crawler = $this->createTestXmlCrawler()->filter('yt|accessControl');
        $this->assertCount(2, $crawler, '->filter() automatically registers namespaces');
    }

    public function testFilterWithMultipleNamespaces()
    {
        CssSelector::disableHtmlExtension();

        $crawler = $this->createTestXmlCrawler()->filter('media|group yt|aspectRatio');
        $this->assertCount(1, $crawler, '->filter() automatically registers namespaces');
        $this->assertSame('widescreen', $crawler->text());
    }

    public function testFilterWithDefaultNamespaceOnly()
    {
        $crawler = new Crawler('<?xml version="1.0" encoding="UTF-8"?>
            <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                <url>
                    <loc>http://localhost/foo</loc>
                    <changefreq>weekly</changefreq>
                    <priority>0.5</priority>
                    <lastmod>2012-11-16</lastmod>
               </url>
               <url>
                    <loc>http://localhost/bar</loc>
                    <changefreq>weekly</changefreq>
                    <priority>0.5</priority>
                    <lastmod>2012-11-16</lastmod>
                </url>
            </urlset>
        ');

        $this->assertEquals(2, $crawler->filter('url')->count());
    }

    public function testSelectLink()
    {
        $crawler = $this->createTestCrawler();
        $this->assertNotSame($crawler, $crawler->selectLink('Foo'), '->selectLink() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectLink() returns a new instance of a crawler');

        $this->assertCount(1, $crawler->selectLink('Fabien\'s Foo'), '->selectLink() selects links by the node values');
        $this->assertCount(1, $crawler->selectLink('Fabien\'s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');

        $this->assertCount(2, $crawler->selectLink('Fabien"s Foo'), '->selectLink() selects links by the node values');
        $this->assertCount(2, $crawler->selectLink('Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');

        $this->assertCount(1, $crawler->selectLink('\' Fabien"s Foo'), '->selectLink() selects links by the node values');
        $this->assertCount(1, $crawler->selectLink('\' Fabien"s Bar'), '->selectLink() selects links by the alt attribute of a clickable image');

        $this->assertCount(4, $crawler->selectLink('Foo'), '->selectLink() selects links by the node values');
        $this->assertCount(4, $crawler->selectLink('Bar'), '->selectLink() selects links by the node values');
    }

    public function testSelectButton()
    {
        $crawler = $this->createTestCrawler();
        $this->assertNotSame($crawler, $crawler->selectButton('FooValue'), '->selectButton() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->selectButton() returns a new instance of a crawler');

        $this->assertEquals(1, $crawler->selectButton('FooValue')->count(), '->selectButton() selects buttons');
        $this->assertEquals(1, $crawler->selectButton('FooName')->count(), '->selectButton() selects buttons');
        $this->assertEquals(1, $crawler->selectButton('FooId')->count(), '->selectButton() selects buttons');

        $this->assertEquals(1, $crawler->selectButton('BarValue')->count(), '->selectButton() selects buttons');
        $this->assertEquals(1, $crawler->selectButton('BarName')->count(), '->selectButton() selects buttons');
        $this->assertEquals(1, $crawler->selectButton('BarId')->count(), '->selectButton() selects buttons');

        $this->assertEquals(1, $crawler->selectButton('FooBarValue')->count(), '->selectButton() selects buttons with form attribute too');
        $this->assertEquals(1, $crawler->selectButton('FooBarName')->count(), '->selectButton() selects buttons with form attribute too');
    }

    public function testLink()
    {
        $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $crawler->link(), '->link() returns a Link instance');

        $this->assertEquals('POST', $crawler->link('post')->getMethod(), '->link() takes a method as its argument');

        $crawler = $this->createTestCrawler('http://example.com/bar')->selectLink('GetLink');
        $this->assertEquals('http://example.com/bar?get=param', $crawler->link()->getUri(), '->link() returns a Link instance');

        try {
            $this->createTestCrawler()->filterXPath('//ol')->link();
            $this->fail('->link() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->link() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testLinks()
    {
        $crawler = $this->createTestCrawler('http://example.com/bar/')->selectLink('Foo');
        $this->assertInternalType('array', $crawler->links(), '->links() returns an array');

        $this->assertCount(4, $crawler->links(), '->links() returns an array');
        $links = $crawler->links();
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Link', $links[0], '->links() returns an array of Link instances');

        $this->assertEquals(array(), $this->createTestCrawler()->filterXPath('//ol')->links(), '->links() returns an empty array if the node selection is empty');
    }

    public function testForm()
    {
        $testCrawler = $this->createTestCrawler('http://example.com/bar/');
        $crawler = $testCrawler->selectButton('FooValue');
        $crawler2 = $testCrawler->selectButton('FooBarValue');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler->form(), '->form() returns a Form instance');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Form', $crawler2->form(), '->form() returns a Form instance');

        $this->assertEquals($crawler->form()->getFormNode()->getAttribute('id'), $crawler2->form()->getFormNode()->getAttribute('id'), '->form() works on elements with form attribute');

        $this->assertEquals(array('FooName' => 'FooBar', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form(array('FooName' => 'FooBar'))->getValues(), '->form() takes an array of values to submit as its first argument');
        $this->assertEquals(array('FooName' => 'FooValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler->form()->getValues(), '->getValues() returns correct form values');
        $this->assertEquals(array('FooBarName' => 'FooBarValue', 'TextName' => 'TextValue', 'FooTextName' => 'FooTextValue'), $crawler2->form()->getValues(), '->getValues() returns correct form values');

        try {
            $this->createTestCrawler()->filterXPath('//ol')->form();
            $this->fail('->form() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->form() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testLast()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//ul[1]/li');
        $this->assertNotSame($crawler, $crawler->last(), '->last() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->last() returns a new instance of a crawler');

        $this->assertEquals('Three', $crawler->last()->text());
    }

    public function testFirst()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li');
        $this->assertNotSame($crawler, $crawler->first(), '->first() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->first() returns a new instance of a crawler');

        $this->assertEquals('One', $crawler->first()->text());
    }

    public function testSiblings()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
        $this->assertNotSame($crawler, $crawler->siblings(), '->siblings() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->siblings() returns a new instance of a crawler');

        $nodes = $crawler->siblings();
        $this->assertEquals(2, $nodes->count());
        $this->assertEquals('One', $nodes->eq(0)->text());
        $this->assertEquals('Three', $nodes->eq(1)->text());

        $nodes = $this->createTestCrawler()->filterXPath('//li')->eq(0)->siblings();
        $this->assertEquals(2, $nodes->count());
        $this->assertEquals('Two', $nodes->eq(0)->text());
        $this->assertEquals('Three', $nodes->eq(1)->text());

        try {
            $this->createTestCrawler()->filterXPath('//ol')->siblings();
            $this->fail('->siblings() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->siblings() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testNextAll()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(1);
        $this->assertNotSame($crawler, $crawler->nextAll(), '->nextAll() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->nextAll() returns a new instance of a crawler');

        $nodes = $crawler->nextAll();
        $this->assertEquals(1, $nodes->count());
        $this->assertEquals('Three', $nodes->eq(0)->text());

        try {
            $this->createTestCrawler()->filterXPath('//ol')->nextAll();
            $this->fail('->nextAll() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->nextAll() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testPreviousAll()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li')->eq(2);
        $this->assertNotSame($crawler, $crawler->previousAll(), '->previousAll() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->previousAll() returns a new instance of a crawler');

        $nodes = $crawler->previousAll();
        $this->assertEquals(2, $nodes->count());
        $this->assertEquals('Two', $nodes->eq(0)->text());

        try {
            $this->createTestCrawler()->filterXPath('//ol')->previousAll();
            $this->fail('->previousAll() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->previousAll() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testChildren()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//ul');
        $this->assertNotSame($crawler, $crawler->children(), '->children() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->children() returns a new instance of a crawler');

        $nodes = $crawler->children();
        $this->assertEquals(3, $nodes->count());
        $this->assertEquals('One', $nodes->eq(0)->text());
        $this->assertEquals('Two', $nodes->eq(1)->text());
        $this->assertEquals('Three', $nodes->eq(2)->text());

        try {
            $this->createTestCrawler()->filterXPath('//ol')->children();
            $this->fail('->children() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->children() throws an \InvalidArgumentException if the node list is empty');
        }

        try {
            $crawler = new Crawler('<p></p>');
            $crawler->filter('p')->children();
            $this->assertTrue(true, '->children() does not trigger a notice if the node has no children');
        } catch (\PHPUnit_Framework_Error_Notice $e) {
            $this->fail('->children() does not trigger a notice if the node has no children');
        }
    }

    public function testParents()
    {
        $crawler = $this->createTestCrawler()->filterXPath('//li[1]');
        $this->assertNotSame($crawler, $crawler->parents(), '->parents() returns a new instance of a crawler');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Crawler', $crawler, '->parents() returns a new instance of a crawler');

        $nodes = $crawler->parents();
        $this->assertEquals(3, $nodes->count());

        $nodes = $this->createTestCrawler()->filterXPath('//html')->parents();
        $this->assertEquals(0, $nodes->count());

        try {
            $this->createTestCrawler()->filterXPath('//ol')->parents();
            $this->fail('->parents() throws an \InvalidArgumentException if the node list is empty');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->parents() throws an \InvalidArgumentException if the node list is empty');
        }
    }

    public function testBaseTag()
    {
        $crawler = new Crawler('<html><base href="http://base.com"><a href="link"></a></html>');
        $this->assertEquals('http://base.com/link', $crawler->filterXPath('//a')->link()->getUri());

        $crawler = new Crawler('<html><base href="//base.com"><a href="link"></a></html>', 'https://domain.com');
        $this->assertEquals('https://base.com/link', $crawler->filterXPath('//a')->link()->getUri(), '<base> tag can use a schema-less URL');

        $crawler = new Crawler('<html><base href="path/"><a href="link"></a></html>', 'https://domain.com');
        $this->assertEquals('https://domain.com/path/link', $crawler->filterXPath('//a')->link()->getUri(), '<base> tag can set a path');
    }

    public function createTestCrawler($uri = null)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('
            <html>
                <body>
                    <a href="foo">Foo</a>
                    <a href="/foo">   Fabien\'s Foo   </a>
                    <a href="/foo">Fabien"s Foo</a>
                    <a href="/foo">\' Fabien"s Foo</a>

                    <a href="/bar"><img alt="Bar"/></a>
                    <a href="/bar"><img alt="   Fabien\'s Bar   "/></a>
                    <a href="/bar"><img alt="Fabien&quot;s Bar"/></a>
                    <a href="/bar"><img alt="\' Fabien&quot;s Bar"/></a>

                    <a href="?get=param">GetLink</a>

                    <form action="foo" id="FooFormId">
                        <input type="text" value="TextValue" name="TextName" />
                        <input type="submit" value="FooValue" name="FooName" id="FooId" />
                        <input type="button" value="BarValue" name="BarName" id="BarId" />
                        <button value="ButtonValue" name="ButtonName" id="ButtonId" />
                    </form>

                    <input type="submit" value="FooBarValue" name="FooBarName" form="FooFormId" />
                    <input type="text" value="FooTextValue" name="FooTextName" form="FooFormId" />

                    <ul class="first">
                        <li class="first">One</li>
                        <li>Two</li>
                        <li>Three</li>
                    </ul>
                    <ul>
                        <li>One Bis</li>
                        <li>Two Bis</li>
                        <li>Three Bis</li>
                    </ul>
                </body>
            </html>
        ');

        return new Crawler($dom, $uri);
    }

    protected function createTestXmlCrawler($uri = null)
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>
            <entry xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xmlns:yt="http://gdata.youtube.com/schemas/2007">
                <id>tag:youtube.com,2008:video:kgZRZmEc9j4</id>
                <yt:accessControl action="comment" permission="allowed"/>
                <yt:accessControl action="videoRespond" permission="moderated"/>
                <media:group>
                    <media:title type="plain">Chordates - CrashCourse Biology #24</media:title>
                    <yt:aspectRatio>widescreen</yt:aspectRatio>
                </media:group>
                <media:category label="Music" scheme="http://gdata.youtube.com/schemas/2007/categories.cat">Music</media:category>
            </entry>';

        return new Crawler($xml, $uri);
    }

    protected function createDomDocument()
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<html><div class="foo"></div></html>');

        return $dom;
    }

    protected function createNodeList()
    {
        $dom = new \DOMDocument();
        $dom->loadXML('<html><div class="foo"></div></html>');
        $domxpath = new \DOMXPath($dom);

        return $domxpath->query('//div');
    }
}
PKA1[��Ջ==KDomCrawler/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

use Symfony\Component\DomCrawler\Field\ChoiceFormField;

class ChoiceFormFieldTest extends FormFieldTestCase
{
    public function testInitialize()
    {
        $node = $this->createNode('textarea', '');
        try {
            $field = new ChoiceFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is not an input or a select');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input or a select');
        }

        $node = $this->createNode('input', '', array('type' => 'text'));
        try {
            $field = new ChoiceFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is an input with a type different from checkbox or radio');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is an input with a type different from checkbox or radio');
        }
    }

    public function testGetType()
    {
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $this->assertEquals('radio', $field->getType(), '->getType() returns radio for radio buttons');

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $this->assertEquals('checkbox', $field->getType(), '->getType() returns radio for a checkbox');

        $node = $this->createNode('select', '');
        $field = new ChoiceFormField($node);

        $this->assertEquals('select', $field->getType(), '->getType() returns radio for a select');
    }

    public function testIsMultiple()
    {
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $this->assertFalse($field->isMultiple(), '->isMultiple() returns false for radio buttons');

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $this->assertFalse($field->isMultiple(), '->isMultiple() returns false for checkboxes');

        $node = $this->createNode('select', '');
        $field = new ChoiceFormField($node);

        $this->assertFalse($field->isMultiple(), '->isMultiple() returns false for selects without the multiple attribute');

        $node = $this->createNode('select', '', array('multiple' => 'multiple'));
        $field = new ChoiceFormField($node);

        $this->assertTrue($field->isMultiple(), '->isMultiple() returns true for selects with the multiple attribute');
    }

    public function testSelects()
    {
        $node = $this->createSelectNode(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);

        $this->assertTrue($field->hasValue(), '->hasValue() returns true for selects');
        $this->assertEquals('foo', $field->getValue(), '->getValue() returns the first option if none are selected');
        $this->assertFalse($field->isMultiple(), '->isMultiple() returns false when no multiple attribute is defined');

        $node = $this->createSelectNode(array('foo' => false, 'bar' => true));
        $field = new ChoiceFormField($node);

        $this->assertEquals('bar', $field->getValue(), '->getValue() returns the selected option');

        $field->setValue('foo');
        $this->assertEquals('foo', $field->getValue(), '->setValue() changes the selected option');

        try {
            $field->setValue('foobar');
            $this->fail('->setValue() throws an \InvalidArgumentException if the value is not one of the selected options');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is not one of the selected options');
        }

        try {
            $field->setValue(array('foobar'));
            $this->fail('->setValue() throws an \InvalidArgumentException if the value is an array');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is an array');
        }
    }

    public function testMultipleSelects()
    {
        $node = $this->createSelectNode(array('foo' => false, 'bar' => false), array('multiple' => 'multiple'));
        $field = new ChoiceFormField($node);

        $this->assertEquals(array(), $field->getValue(), '->setValue() returns an empty array if multiple is true and no option is selected');

        $field->setValue('foo');
        $this->assertEquals(array('foo'), $field->getValue(), '->setValue() returns an array of options if multiple is true');

        $field->setValue('bar');
        $this->assertEquals(array('bar'), $field->getValue(), '->setValue() returns an array of options if multiple is true');

        $field->setValue(array('foo', 'bar'));
        $this->assertEquals(array('foo', 'bar'), $field->getValue(), '->setValue() returns an array of options if multiple is true');

        $node = $this->createSelectNode(array('foo' => true, 'bar' => true), array('multiple' => 'multiple'));
        $field = new ChoiceFormField($node);

        $this->assertEquals(array('foo', 'bar'), $field->getValue(), '->getValue() returns the selected options');

        try {
            $field->setValue(array('foobar'));
            $this->fail('->setValue() throws an \InvalidArgumentException if the value is not one of the options');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is not one of the options');
        }
    }

    public function testRadioButtons()
    {
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'bar'));
        $field->addChoice($node);

        $this->assertFalse($field->hasValue(), '->hasValue() returns false when no radio button is selected');
        $this->assertNull($field->getValue(), '->getValue() returns null if no radio button is selected');
        $this->assertFalse($field->isMultiple(), '->isMultiple() returns false for radio buttons');

        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'foo'));
        $field = new ChoiceFormField($node);
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'bar', 'checked' => 'checked'));
        $field->addChoice($node);

        $this->assertTrue($field->hasValue(), '->hasValue() returns true when a radio button is selected');
        $this->assertEquals('bar', $field->getValue(), '->getValue() returns the value attribute of the selected radio button');

        $field->setValue('foo');
        $this->assertEquals('foo', $field->getValue(), '->setValue() changes the selected radio button');

        try {
            $field->setValue('foobar');
            $this->fail('->setValue() throws an \InvalidArgumentException if the value is not one of the radio button values');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is not one of the radio button values');
        }
    }

    public function testRadioButtonIsDisabled()
    {
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'foo', 'disabled' => 'disabled'));
        $field = new ChoiceFormField($node);
        $node = $this->createNode('input', '', array('type' => 'radio', 'name' => 'name', 'value' => 'bar'));
        $field->addChoice($node);

        $field->select('foo');
        $this->assertEquals('foo', $field->getValue(), '->getValue() returns the value attribute of the selected radio button');
        $this->assertTrue($field->isDisabled());

        $field->select('bar');
        $this->assertEquals('bar', $field->getValue(), '->getValue() returns the value attribute of the selected radio button');
        $this->assertFalse($field->isDisabled());
    }

    public function testCheckboxes()
    {
        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name'));
        $field = new ChoiceFormField($node);

        $this->assertFalse($field->hasValue(), '->hasValue() returns false when the checkbox is not checked');
        $this->assertNull($field->getValue(), '->getValue() returns null if the checkbox is not checked');
        $this->assertFalse($field->isMultiple(), '->hasValue() returns false for checkboxes');
        try {
            $field->addChoice(new \DOMNode());
            $this->fail('->addChoice() throws a \LogicException for checkboxes');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException for checkboxes');
        }

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked'));
        $field = new ChoiceFormField($node);

        $this->assertTrue($field->hasValue(), '->hasValue() returns true when the checkbox is checked');
        $this->assertEquals('1', $field->getValue(), '->getValue() returns 1 if the checkbox is checked and has no value attribute');

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $this->assertEquals('foo', $field->getValue(), '->getValue() returns the value attribute if the checkbox is checked');

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked', 'value' => 'foo'));
        $field = new ChoiceFormField($node);

        $field->setValue(false);
        $this->assertNull($field->getValue(), '->setValue() unchecks the checkbox is value is false');

        $field->setValue(true);
        $this->assertEquals('foo', $field->getValue(), '->setValue() checks the checkbox is value is true');

        try {
            $field->setValue('bar');
            $this->fail('->setValue() throws an \InvalidArgumentException if the value is not one from the value attribute');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setValue() throws an \InvalidArgumentException if the value is not one from the value attribute');
        }
    }

    public function testTick()
    {
        $node = $this->createSelectNode(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);

        try {
            $field->tick();
            $this->fail('->tick() throws a \LogicException for select boxes');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->tick() throws a \LogicException for select boxes');
        }

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name'));
        $field = new ChoiceFormField($node);
        $field->tick();
        $this->assertEquals(1, $field->getValue(), '->tick() ticks checkboxes');
    }

    public function testUntick()
    {
        $node = $this->createSelectNode(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);

        try {
            $field->untick();
            $this->fail('->untick() throws a \LogicException for select boxes');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->untick() throws a \LogicException for select boxes');
        }

        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked'));
        $field = new ChoiceFormField($node);
        $field->untick();
        $this->assertNull($field->getValue(), '->untick() unticks checkboxes');
    }

    public function testSelect()
    {
        $node = $this->createNode('input', '', array('type' => 'checkbox', 'name' => 'name', 'checked' => 'checked'));
        $field = new ChoiceFormField($node);
        $field->select(true);
        $this->assertEquals(1, $field->getValue(), '->select() changes the value of the field');
        $field->select(false);
        $this->assertNull($field->getValue(), '->select() changes the value of the field');

        $node = $this->createSelectNode(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);
        $field->select('foo');
        $this->assertEquals('foo', $field->getValue(), '->select() changes the selected option');
    }

    public function testOptionWithNoValue()
    {
        $node = $this->createSelectNodeWithEmptyOption(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);
        $field->select('foo');
        $this->assertEquals('foo', $field->getValue(), '->select() changes the selected option');
    }

    public function testDisableValidation()
    {
        $node = $this->createSelectNode(array('foo' => false, 'bar' => false));
        $field = new ChoiceFormField($node);
        $field->disableValidation();
        $field->setValue('foobar');
        $this->assertEquals('foobar', $field->getValue(), '->disableValidation() allows to set a value which is not in the selected options.');

        $node = $this->createSelectNode(array('foo' => false, 'bar' => false), array('multiple' => 'multiple'));
        $field = new ChoiceFormField($node);
        $field->disableValidation();
        $field->setValue(array('foobar'));
        $this->assertEquals(array('foobar'), $field->getValue(), '->disableValidation() allows to set a value which is not in the selected options.');
    }

    protected function createSelectNode($options, $attributes = array())
    {
        $document = new \DOMDocument();
        $node = $document->createElement('select');

        foreach ($attributes as $name => $value) {
            $node->setAttribute($name, $value);
        }
        $node->setAttribute('name', 'name');

        foreach ($options as $value => $selected) {
            $option = $document->createElement('option', $value);
            $option->setAttribute('value', $value);
            if ($selected) {
                $option->setAttribute('selected', 'selected');
            }
            $node->appendChild($option);
        }

        return $node;
    }

    protected function createSelectNodeWithEmptyOption($options, $attributes = array())
    {
        $document = new \DOMDocument();
        $node = $document->createElement('select');

        foreach ($attributes as $name => $value) {
            $node->setAttribute($name, $value);
        }
        $node->setAttribute('name', 'name');

        foreach ($options as $value => $selected) {
            $option = $document->createElement('option', $value);
            if ($selected) {
                $option->setAttribute('selected', 'selected');
            }
            $node->appendChild($option);
        }

        return $node;
    }
}
PKA1[�n���MDomCrawler/Symfony/Component/DomCrawler/Tests/Field/TextareaFormFieldTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

use Symfony\Component\DomCrawler\Field\TextareaFormField;

class TextareaFormFieldTest extends FormFieldTestCase
{
    public function testInitialize()
    {
        $node = $this->createNode('textarea', 'foo bar');
        $field = new TextareaFormField($node);

        $this->assertEquals('foo bar', $field->getValue(), '->initialize() sets the value of the field to the textarea node value');

        $node = $this->createNode('input', '');
        try {
            $field = new TextareaFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is not a textarea');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is not a textarea');
        }

        // Ensure that valid HTML can be used on a textarea.
        $node = $this->createNode('textarea', 'foo bar <h1>Baz</h1>');
        $field = new TextareaFormField($node);

        $this->assertEquals('foo bar <h1>Baz</h1>', $field->getValue(), '->initialize() sets the value of the field to the textarea node value');

        // Ensure that we don't do any DOM manipulation/validation by passing in
        // "invalid" HTML.
        $node = $this->createNode('textarea', 'foo bar <h1>Baz</h2>');
        $field = new TextareaFormField($node);

        $this->assertEquals('foo bar <h1>Baz</h2>', $field->getValue(), '->initialize() sets the value of the field to the textarea node value');
    }
}
PKA1[�!
D��EDomCrawler/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

use Symfony\Component\DomCrawler\Field\InputFormField;

class FormFieldTest extends FormFieldTestCase
{
    public function testGetName()
    {
        $node = $this->createNode('input', '', array('type' => 'text', 'name' => 'name', 'value' => 'value'));
        $field = new InputFormField($node);

        $this->assertEquals('name', $field->getName(), '->getName() returns the name of the field');
    }

    public function testGetSetHasValue()
    {
        $node = $this->createNode('input', '', array('type' => 'text', 'name' => 'name', 'value' => 'value'));
        $field = new InputFormField($node);

        $this->assertEquals('value', $field->getValue(), '->getValue() returns the value of the field');

        $field->setValue('foo');
        $this->assertEquals('foo', $field->getValue(), '->setValue() sets the value of the field');

        $this->assertTrue($field->hasValue(), '->hasValue() always returns true');
    }
}
PKA1[2$�G��IDomCrawler/Symfony/Component/DomCrawler/Tests/Field/FormFieldTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

class FormFieldTestCase extends \PHPUnit_Framework_TestCase
{
    protected function createNode($tag, $value, $attributes = array())
    {
        $document = new \DOMDocument();
        $node = $document->createElement($tag, $value);

        foreach ($attributes as $name => $value) {
            $node->setAttribute($name, $value);
        }

        return $node;
    }
}
PKA1[���QQJDomCrawler/Symfony/Component/DomCrawler/Tests/Field/InputFormFieldTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

use Symfony\Component\DomCrawler\Field\InputFormField;

class InputFormFieldTest extends FormFieldTestCase
{
    public function testInitialize()
    {
        $node = $this->createNode('input', '', array('type' => 'text', 'name' => 'name', 'value' => 'value'));
        $field = new InputFormField($node);

        $this->assertEquals('value', $field->getValue(), '->initialize() sets the value of the field to the value attribute value');

        $node = $this->createNode('textarea', '');
        try {
            $field = new InputFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is not an input');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input');
        }

        $node = $this->createNode('input', '', array('type' => 'checkbox'));
        try {
            $field = new InputFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is a checkbox');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is a checkbox');
        }

        $node = $this->createNode('input', '', array('type' => 'file'));
        try {
            $field = new InputFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is a file');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is a file');
        }
    }
}
PKA1[�5�||IDomCrawler/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests\Field;

use Symfony\Component\DomCrawler\Field\FileFormField;

class FileFormFieldTest extends FormFieldTestCase
{
    public function testInitialize()
    {
        $node = $this->createNode('input', '', array('type' => 'file'));
        $field = new FileFormField($node);

        $this->assertEquals(array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0), $field->getValue(), '->initialize() sets the value of the field to no file uploaded');

        $node = $this->createNode('textarea', '');
        try {
            $field = new FileFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is not an input field');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is not an input field');
        }

        $node = $this->createNode('input', '', array('type' => 'text'));
        try {
            $field = new FileFormField($node);
            $this->fail('->initialize() throws a \LogicException if the node is not a file input field');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '->initialize() throws a \LogicException if the node is not a file input field');
        }
    }

    /**
     * @dataProvider getSetValueMethods
     */
    public function testSetValue($method)
    {
        $node = $this->createNode('input', '', array('type' => 'file'));
        $field = new FileFormField($node);

        $field->$method(null);
        $this->assertEquals(array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => UPLOAD_ERR_NO_FILE, 'size' => 0), $field->getValue(), "->$method() clears the uploaded file if the value is null");

        $field->$method(__FILE__);
        $value = $field->getValue();

        $this->assertEquals(basename(__FILE__), $value['name'], "->$method() sets the name of the file field");
        $this->assertEquals('', $value['type'], "->$method() sets the type of the file field");
        $this->assertInternalType('string', $value['tmp_name'], "->$method() sets the tmp_name of the file field");
        $this->assertFileExists($value['tmp_name'], "->$method() creates a copy of the file at the tmp_name path");
        $this->assertEquals(0, $value['error'], "->$method() sets the error of the file field");
        $this->assertEquals(filesize(__FILE__), $value['size'], "->$method() sets the size of the file field");

        $origInfo = pathinfo(__FILE__);
        $tmpInfo = pathinfo($value['tmp_name']);
        $this->assertEquals(
            $origInfo['extension'],
            $tmpInfo['extension'],
            "->$method() keeps the same file extension in the tmp_name copy"
        );

        $field->$method(__DIR__.'/../Fixtures/no-extension');
        $value = $field->getValue();

        $this->assertArrayNotHasKey(
            'extension',
            pathinfo($value['tmp_name']),
            "->$method() does not add a file extension in the tmp_name copy"
        );
    }

    public function getSetValueMethods()
    {
        return array(
            array('setValue'),
            array('upload'),
        );
    }

    public function testSetErrorCode()
    {
        $node = $this->createNode('input', '', array('type' => 'file'));
        $field = new FileFormField($node);

        $field->setErrorCode(UPLOAD_ERR_FORM_SIZE);
        $value = $field->getValue();
        $this->assertEquals(UPLOAD_ERR_FORM_SIZE, $value['error'], '->setErrorCode() sets the file input field error code');

        try {
            $field->setErrorCode('foobar');
            $this->fail('->setErrorCode() throws a \InvalidArgumentException if the error code is not valid');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->setErrorCode() throws a \InvalidArgumentException if the error code is not valid');
        }
    }

    public function testSetRawFilePath()
    {
        $node = $this->createNode('input', '', array('type' => 'file'));
        $field = new FileFormField($node);
        $field->setFilePath(__FILE__);

        $this->assertEquals(__FILE__, $field->getValue());
    }

}
PKA1[�3��ʖʖ:DomCrawler/Symfony/Component/DomCrawler/Tests/FormTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests;

use Symfony\Component\DomCrawler\Form;
use Symfony\Component\DomCrawler\FormFieldRegistry;
use Symfony\Component\DomCrawler\Field;

class FormTest extends \PHPUnit_Framework_TestCase
{
    public static function setUpBeforeClass()
    {
        // Ensure that the private helper class FormFieldRegistry is loaded
        class_exists('Symfony\\Component\\DomCrawler\\Form');
    }

    public function testConstructorThrowsExceptionIfTheNodeHasNoFormAncestor()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('
            <html>
                <input type="submit" />
                <form>
                    <input type="foo" />
                </form>
                <button />
            </html>
        ');

        $nodes = $dom->getElementsByTagName('input');

        try {
            $form = new Form($nodes->item(0), 'http://example.com');
            $this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
        }

        try {
            $form = new Form($nodes->item(1), 'http://example.com');
            $this->fail('__construct() throws a \\LogicException if the input type is not submit, button, or image');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '__construct() throws a \\LogicException if the input type is not submit, button, or image');
        }

        $nodes = $dom->getElementsByTagName('button');

        try {
            $form = new Form($nodes->item(0), 'http://example.com');
            $this->fail('__construct() throws a \\LogicException if the node has no form ancestor');
        } catch (\LogicException $e) {
            $this->assertTrue(true, '__construct() throws a \\LogicException if the node has no form ancestor');
        }
    }

    /**
     * __construct() should throw \\LogicException if the form attribute is invalid
     * @expectedException \LogicException
     */
    public function testConstructorThrowsExceptionIfNoRelatedForm()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('
            <html>
                <form id="bar">
                    <input type="submit" form="nonexistent" />
                </form>
                <input type="text" form="nonexistent" />
                <button />
            </html>
        ');

        $nodes = $dom->getElementsByTagName('input');

        $form = new Form($nodes->item(0), 'http://example.com');
        $form = new Form($nodes->item(1), 'http://example.com');
    }

    public function testConstructorHandlesFormAttribute()
    {
        $dom = $this->createTestHtml5Form();

        $inputElements = $dom->getElementsByTagName('input');
        $buttonElements = $dom->getElementsByTagName('button');

        // Tests if submit buttons are correctly assigned to forms
        $form1 = new Form($buttonElements->item(1), 'http://example.com');
        $this->assertSame($dom->getElementsByTagName('form')->item(0), $form1->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');

        $form1 = new Form($inputElements->item(3), 'http://example.com');
        $this->assertSame($dom->getElementsByTagName('form')->item(0), $form1->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');

        $form2 = new Form($buttonElements->item(0), 'http://example.com');
        $this->assertSame($dom->getElementsByTagName('form')->item(1), $form2->getFormNode(), 'HTML5-compliant form attribute handled incorrectly');
    }

    public function testConstructorHandlesFormValues()
    {
        $dom = $this->createTestHtml5Form();

        $inputElements = $dom->getElementsByTagName('input');
        $buttonElements = $dom->getElementsByTagName('button');

        $form1 = new Form($inputElements->item(3), 'http://example.com');
        $form2 = new Form($buttonElements->item(0), 'http://example.com');

        // Tests if form values are correctly assigned to forms
        $values1 = array(
            'apples' => array('1', '2'),
            'form_name' => 'form-1',
            'button_1' => 'Capture fields',
            'outer_field' => 'success'
        );
        $values2 = array(
            'oranges' => array('1', '2', '3'),
            'form_name' => 'form_2',
            'button_2' => '',
            'app_frontend_form_type_contact_form_type' => array('contactType' => '', 'firstName' => 'John')
        );

        $this->assertEquals($values1, $form1->getPhpValues(), 'HTML5-compliant form attribute handled incorrectly');
        $this->assertEquals($values2, $form2->getPhpValues(), 'HTML5-compliant form attribute handled incorrectly');
    }

    public function testMultiValuedFields()
    {
        $form = $this->createForm('<form>
            <input type="text" name="foo[4]" value="foo" disabled="disabled" />
            <input type="text" name="foo" value="foo" disabled="disabled" />
            <input type="text" name="foo[2]" value="foo" disabled="disabled" />
            <input type="text" name="foo[]" value="foo" disabled="disabled" />
            <input type="text" name="bar[foo][]" value="foo" disabled="disabled" />
            <input type="text" name="bar[foo][foobar]" value="foo" disabled="disabled" />
            <input type="submit" />
        </form>
        ');

        $this->assertEquals(
            array_keys($form->all()),
            array('foo[2]', 'foo[3]', 'bar[foo][0]', 'bar[foo][foobar]')
        );

        $this->assertEquals($form->get('foo[2]')->getValue(), 'foo');
        $this->assertEquals($form->get('foo[3]')->getValue(), 'foo');
        $this->assertEquals($form->get('bar[foo][0]')->getValue(), 'foo');
        $this->assertEquals($form->get('bar[foo][foobar]')->getValue(), 'foo');

        $form['foo[2]'] = 'bar';
        $form['foo[3]'] = 'bar';

        $this->assertEquals($form->get('foo[2]')->getValue(), 'bar');
        $this->assertEquals($form->get('foo[3]')->getValue(), 'bar');

        $form['bar'] = array('foo' => array('0' => 'bar', 'foobar' => 'foobar'));

        $this->assertEquals($form->get('bar[foo][0]')->getValue(), 'bar');
        $this->assertEquals($form->get('bar[foo][foobar]')->getValue(), 'foobar');

    }

    /**
     * @dataProvider provideInitializeValues
     */
    public function testConstructor($message, $form, $values)
    {
        $form = $this->createForm('<form>'.$form.'</form>');
        $this->assertEquals(
            $values,
            array_map(function ($field) {
                    $class = get_class($field);

                    return array(substr($class, strrpos($class, '\\') + 1), $field->getValue());
                },
                $form->all()
            ),
            '->getDefaultValues() '.$message
        );
    }

    public function provideInitializeValues()
    {
        return array(
            array(
                'does not take into account input fields without a name attribute',
                '<input type="text" value="foo" />
                 <input type="submit" />',
                array(),
            ),
            array(
                'does not take into account input fields with an empty name attribute value',
                '<input type="text" name="" value="foo" />
                 <input type="submit" />',
                array(),
            ),
            array(
                'takes into account disabled input fields',
                '<input type="text" name="foo" value="foo" disabled="disabled" />
                 <input type="submit" />',
                array('foo' => array('InputFormField', 'foo')),
            ),
            array(
                'appends the submitted button value',
                '<input type="submit" name="bar" value="bar" />',
                array('bar' => array('InputFormField', 'bar')),
            ),
            array(
                'appends the submitted button value for Button element',
                '<button type="submit" name="bar" value="bar">Bar</button>',
                array('bar' => array('InputFormField', 'bar')),
            ),
            array(
                'appends the submitted button value but not other submit buttons',
                '<input type="submit" name="bar" value="bar" />
                 <input type="submit" name="foobar" value="foobar" />',
                 array('foobar' => array('InputFormField', 'foobar')),
            ),
            array(
                'turns an image input into x and y fields',
                '<input type="image" name="bar" />',
                array('bar.x' => array('InputFormField', '0'), 'bar.y' => array('InputFormField', '0')),
            ),
            array(
                'returns textareas',
                '<textarea name="foo">foo</textarea>
                 <input type="submit" />',
                 array('foo' => array('TextareaFormField', 'foo')),
            ),
            array(
                'returns inputs',
                '<input type="text" name="foo" value="foo" />
                 <input type="submit" />',
                 array('foo' => array('InputFormField', 'foo')),
            ),
            array(
                'returns checkboxes',
                '<input type="checkbox" name="foo" value="foo" checked="checked" />
                 <input type="submit" />',
                 array('foo' => array('ChoiceFormField', 'foo')),
            ),
            array(
                'returns not-checked checkboxes',
                '<input type="checkbox" name="foo" value="foo" />
                 <input type="submit" />',
                 array('foo' => array('ChoiceFormField', false)),
            ),
            array(
                'returns radio buttons',
                '<input type="radio" name="foo" value="foo" />
                 <input type="radio" name="foo" value="bar" checked="bar" />
                 <input type="submit" />',
                 array('foo' => array('ChoiceFormField', 'bar')),
            ),
            array(
                'returns file inputs',
                '<input type="file" name="foo" />
                 <input type="submit" />',
                 array('foo' => array('FileFormField', array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))),
            ),
        );
    }

    public function testGetFormNode()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><form><input type="submit" /></form></html>');

        $form = new Form($dom->getElementsByTagName('input')->item(0), 'http://example.com');

        $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
    }

    public function testGetFormNodeFromNamedForm()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><form name="my_form"><input type="submit" /></form></html>');

        $form = new Form($dom->getElementsByTagName('form')->item(0), 'http://example.com');

        $this->assertSame($dom->getElementsByTagName('form')->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
    }

    public function testGetMethod()
    {
        $form = $this->createForm('<form><input type="submit" /></form>');
        $this->assertEquals('GET', $form->getMethod(), '->getMethod() returns get if no method is defined');

        $form = $this->createForm('<form method="post"><input type="submit" /></form>');
        $this->assertEquals('POST', $form->getMethod(), '->getMethod() returns the method attribute value of the form');

        $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'put');
        $this->assertEquals('PUT', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');

        $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'delete');
        $this->assertEquals('DELETE', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');

        $form = $this->createForm('<form method="post"><input type="submit" /></form>', 'patch');
        $this->assertEquals('PATCH', $form->getMethod(), '->getMethod() returns the method defined in the constructor if provided');
    }

    public function testGetSetValue()
    {
        $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');

        $this->assertEquals('foo', $form['foo']->getValue(), '->offsetGet() returns the value of a form field');

        $form['foo'] = 'bar';

        $this->assertEquals('bar', $form['foo']->getValue(), '->offsetSet() changes the value of a form field');

        try {
            $form['foobar'] = 'bar';
            $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
        }

        try {
            $form['foobar'];
            $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the field does not exist');
        }
    }

    public function testSetValueOnMultiValuedFieldsWithMalformedName()
    {
        $form = $this->createForm('<form><input type="text" name="foo[bar]" value="bar" /><input type="text" name="foo[baz]" value="baz" /><input type="submit" /></form>');

        try {
            $form['foo[bar'] = 'bar';
            $this->fail('->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->offsetSet() throws an \InvalidArgumentException exception if the name is malformed.');
        }
    }

    public function testDisableValidation()
    {
        $form = $this->createForm('<form>
            <select name="foo[bar]">
                <option value="bar">bar</option>
            </select>
            <select name="foo[baz]">
                <option value="foo">foo</option>
            </select>
            <input type="submit" />
        </form>');

        $form->disableValidation();

        $form['foo[bar]']->select('foo');
        $form['foo[baz]']->select('bar');
        $this->assertEquals('foo', $form['foo[bar]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.');
        $this->assertEquals('bar', $form['foo[baz]']->getValue(), '->disableValidation() disables validation of all ChoiceFormField.');
    }

    public function testOffsetUnset()
    {
        $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');
        unset($form['foo']);
        $this->assertFalse(isset($form['foo']), '->offsetUnset() removes a field');
    }

    public function testOffsetExists()
    {
        $form = $this->createForm('<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>');

        $this->assertTrue(isset($form['foo']), '->offsetExists() return true if the field exists');
        $this->assertFalse(isset($form['bar']), '->offsetExists() return false if the field does not exist');
    }

    public function testGetValues()
    {
        $form = $this->createForm('<form><input type="text" name="foo[bar]" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('foo[bar]' => 'foo', 'bar' => 'bar'), $form->getValues(), '->getValues() returns all form field values');

        $form = $this->createForm('<form><input type="checkbox" name="foo" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include not-checked checkboxes');

        $form = $this->createForm('<form><input type="file" name="foo" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include file input fields');

        $form = $this->createForm('<form><input type="text" name="foo" value="foo" disabled="disabled" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('bar' => 'bar'), $form->getValues(), '->getValues() does not include disabled fields');
    }

    public function testSetValues()
    {
        $form = $this->createForm('<form><input type="checkbox" name="foo" value="foo" checked="checked" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $form->setValues(array('foo' => false, 'bar' => 'foo'));
        $this->assertEquals(array('bar' => 'foo'), $form->getValues(), '->setValues() sets the values of fields');
    }

    public function testMultiselectSetValues()
    {
        $form = $this->createForm('<form><select multiple="multiple" name="multi"><option value="foo">foo</option><option value="bar">bar</option></select><input type="submit" /></form>');
        $form->setValues(array('multi' => array("foo", "bar")));
        $this->assertEquals(array('multi' => array('foo', 'bar')), $form->getValues(), '->setValue() sets the values of select');
    }

    public function testGetPhpValues()
    {
        $form = $this->createForm('<form><input type="text" name="foo[bar]" value="foo" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('foo' => array('bar' => 'foo'), 'bar' => 'bar'), $form->getPhpValues(), '->getPhpValues() converts keys with [] to arrays');

        $form = $this->createForm('<form><input type="text" name="fo.o[ba.r]" value="foo" /><input type="text" name="ba r" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('fo.o' => array('ba.r' => 'foo'), 'ba r' => 'bar'), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names');

        $form = $this->createForm('<form><input type="text" name="fo.o[ba.r][]" value="foo" /><input type="text" name="fo.o[ba.r][ba.z]" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('fo.o' => array('ba.r' => array('foo', 'ba.z' => 'bar'))), $form->getPhpValues(), '->getPhpValues() preserves periods and spaces in names recursively');
    }

    public function testGetFiles()
    {
        $form = $this->createForm('<form><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array(), $form->getFiles(), '->getFiles() returns an empty array if method is get');

        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for POST');

        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'put');
        $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PUT');

        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'delete');
        $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for DELETE');

        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>', 'patch');
        $this->assertEquals(array('foo[bar]' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)), $form->getFiles(), '->getFiles() only returns file fields for PATCH');

        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" disabled="disabled" /><input type="submit" /></form>');
        $this->assertEquals(array(), $form->getFiles(), '->getFiles() does not include disabled file fields');
    }

    public function testGetPhpFiles()
    {
        $form = $this->createForm('<form method="post"><input type="file" name="foo[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('foo' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() converts keys with [] to arrays');

        $form = $this->createForm('<form method="post"><input type="file" name="f.o o[bar]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('f.o o' => array('bar' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names');

        $form = $this->createForm('<form method="post"><input type="file" name="f.o o[bar][ba.z]" /><input type="file" name="f.o o[bar][]" /><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $this->assertEquals(array('f.o o' => array('bar' => array('ba.z' => array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0), array('name' => '', 'type' => '', 'tmp_name' => '', 'error' => 4, 'size' => 0)))), $form->getPhpFiles(), '->getPhpFiles() preserves periods and spaces in names recursively');
    }

    /**
     * @dataProvider provideGetUriValues
     */
    public function testGetUri($message, $form, $values, $uri, $method = null)
    {
        $form = $this->createForm($form, $method);
        $form->setValues($values);

        $this->assertEquals('http://example.com'.$uri, $form->getUri(), '->getUri() '.$message);
    }

    public function testGetBaseUri()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<form method="post" action="foo.php"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');

        $nodes = $dom->getElementsByTagName('input');
        $form = new Form($nodes->item($nodes->length - 1), 'http://www.foo.com/');
        $this->assertEquals('http://www.foo.com/foo.php', $form->getUri());
    }

    public function testGetUriWithAnchor()
    {
        $form = $this->createForm('<form action="#foo"><input type="submit" /></form>', null, 'http://example.com/id/123');

        $this->assertEquals('http://example.com/id/123#foo', $form->getUri());
    }

    public function testGetUriActionAbsolute()
    {
        $formHtml='<form id="login_form" action="https://login.foo.com/login.php?login_attempt=1" method="POST"><input type="text" name="foo" value="foo" /><input type="submit" /></form>';

        $form = $this->createForm($formHtml);
        $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');

        $form = $this->createForm($formHtml, null, 'https://login.foo.com');
        $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');

        $form = $this->createForm($formHtml, null, 'https://login.foo.com/bar/');
        $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');

        // The action URI haven't the same domain Host have an another domain as Host
        $form = $this->createForm($formHtml, null, 'https://www.foo.com');
        $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');

        $form = $this->createForm($formHtml, null, 'https://www.foo.com/bar/');
        $this->assertEquals('https://login.foo.com/login.php?login_attempt=1', $form->getUri(), '->getUri() returns absolute URIs set in the action form');
    }

    public function testGetUriAbsolute()
    {
        $form = $this->createForm('<form action="foo"><input type="submit" /></form>', null, 'http://localhost/foo/');
        $this->assertEquals('http://localhost/foo/foo', $form->getUri(), '->getUri() returns absolute URIs');

        $form = $this->createForm('<form action="/foo"><input type="submit" /></form>', null, 'http://localhost/foo/');
        $this->assertEquals('http://localhost/foo', $form->getUri(), '->getUri() returns absolute URIs');
    }

    public function testGetUriWithOnlyQueryString()
    {
        $form = $this->createForm('<form action="?get=param"><input type="submit" /></form>', null, 'http://localhost/foo/bar');
        $this->assertEquals('http://localhost/foo/bar?get=param', $form->getUri(), '->getUri() returns absolute URIs only if the host has been defined in the constructor');
    }

    public function testGetUriWithoutAction()
    {
        $form = $this->createForm('<form><input type="submit" /></form>', null, 'http://localhost/foo/bar');
        $this->assertEquals('http://localhost/foo/bar', $form->getUri(), '->getUri() returns path if no action defined');
    }

    public function provideGetUriValues()
    {
        return array(
            array(
                'returns the URI of the form',
                '<form action="/foo"><input type="submit" /></form>',
                array(),
                '/foo'
            ),
            array(
                'appends the form values if the method is get',
                '<form action="/foo"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo?foo=foo'
            ),
            array(
                'appends the form values and merges the submitted values',
                '<form action="/foo"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array('foo' => 'bar'),
                '/foo?foo=bar'
            ),
            array(
                'does not append values if the method is post',
                '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo'
            ),
            array(
                'does not append values if the method is patch',
                '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo',
                'PUT'
            ),
            array(
                'does not append values if the method is delete',
                '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo',
                'DELETE'
            ),
            array(
                'does not append values if the method is put',
                '<form action="/foo" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo',
                'PATCH'
            ),
            array(
                'appends the form values to an existing query string',
                '<form action="/foo?bar=bar"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/foo?bar=bar&foo=foo'
            ),
            array(
                'returns an empty URI if the action is empty',
                '<form><input type="submit" /></form>',
                array(),
                '/',
            ),
            array(
                'appends the form values even if the action is empty',
                '<form><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/?foo=foo',
            ),
            array(
                'chooses the path if the action attribute value is a sharp (#)',
                '<form action="#" method="post"><input type="text" name="foo" value="foo" /><input type="submit" /></form>',
                array(),
                '/#',
            ),
        );
    }

    public function testHas()
    {
        $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');

        $this->assertFalse($form->has('foo'), '->has() returns false if a field is not in the form');
        $this->assertTrue($form->has('bar'), '->has() returns true if a field is in the form');
    }

    public function testRemove()
    {
        $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');
        $form->remove('bar');
        $this->assertFalse($form->has('bar'), '->remove() removes a field');
    }

    public function testGet()
    {
        $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');

        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $form->get('bar'), '->get() returns the field object associated with the given name');

        try {
            $form->get('foo');
            $this->fail('->get() throws an \InvalidArgumentException if the field does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertTrue(true, '->get() throws an \InvalidArgumentException if the field does not exist');
        }
    }

    public function testAll()
    {
        $form = $this->createForm('<form method="post"><input type="text" name="bar" value="bar" /><input type="submit" /></form>');

        $fields = $form->all();
        $this->assertCount(1, $fields, '->all() return an array of form field objects');
        $this->assertInstanceOf('Symfony\\Component\\DomCrawler\\Field\\InputFormField', $fields['bar'], '->all() return an array of form field objects');
    }

    public function testSubmitWithoutAFormButton()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('
            <html>
                <form>
                    <input type="foo" />
                </form>
            </html>
        ');

        $nodes = $dom->getElementsByTagName('form');
        $form = new Form($nodes->item(0), 'http://example.com');
        $this->assertSame($nodes->item(0), $form->getFormNode(), '->getFormNode() returns the form node associated with this form');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistryAddThrowAnExceptionWhenTheNameIsMalformed()
    {
        $registry = new FormFieldRegistry();
        $registry->add($this->getFormFieldMock('[foo]'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistryRemoveThrowAnExceptionWhenTheNameIsMalformed()
    {
        $registry = new FormFieldRegistry();
        $registry->remove('[foo]');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistryGetThrowAnExceptionWhenTheNameIsMalformed()
    {
        $registry = new FormFieldRegistry();
        $registry->get('[foo]');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistryGetThrowAnExceptionWhenTheFieldDoesNotExist()
    {
        $registry = new FormFieldRegistry();
        $registry->get('foo');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistrySetThrowAnExceptionWhenTheNameIsMalformed()
    {
        $registry = new FormFieldRegistry();
        $registry->set('[foo]', null);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testFormFieldRegistrySetThrowAnExceptionWhenTheFieldDoesNotExist()
    {
        $registry = new FormFieldRegistry();
        $registry->set('foo', null);
    }

    public function testFormFieldRegistryHasReturnsTrueWhenTheFQNExists()
    {
        $registry = new FormFieldRegistry();
        $registry->add($this->getFormFieldMock('foo[bar]'));

        $this->assertTrue($registry->has('foo'));
        $this->assertTrue($registry->has('foo[bar]'));
        $this->assertFalse($registry->has('bar'));
        $this->assertFalse($registry->has('foo[foo]'));
    }

    public function testFormRegistryFieldsCanBeRemoved()
    {
        $registry = new FormFieldRegistry();
        $registry->add($this->getFormFieldMock('foo'));
        $registry->remove('foo');
        $this->assertFalse($registry->has('foo'));
    }

    public function testFormRegistrySupportsMultivaluedFields()
    {
        $registry = new FormFieldRegistry();
        $registry->add($this->getFormFieldMock('foo[]'));
        $registry->add($this->getFormFieldMock('foo[]'));
        $registry->add($this->getFormFieldMock('bar[5]'));
        $registry->add($this->getFormFieldMock('bar[]'));
        $registry->add($this->getFormFieldMock('bar[baz]'));

        $this->assertEquals(
            array('foo[0]', 'foo[1]', 'bar[5]', 'bar[6]', 'bar[baz]'),
            array_keys($registry->all())
        );
    }

    public function testFormRegistrySetValues()
    {
        $registry = new FormFieldRegistry();
        $registry->add($f2 = $this->getFormFieldMock('foo[2]'));
        $registry->add($f3 = $this->getFormFieldMock('foo[3]'));
        $registry->add($fbb = $this->getFormFieldMock('foo[bar][baz]'));

        $f2
            ->expects($this->exactly(2))
            ->method('setValue')
            ->with(2)
        ;

        $f3
            ->expects($this->exactly(2))
            ->method('setValue')
            ->with(3)
        ;

        $fbb
            ->expects($this->exactly(2))
            ->method('setValue')
            ->with('fbb')
        ;

        $registry->set('foo[2]', 2);
        $registry->set('foo[3]', 3);
        $registry->set('foo[bar][baz]', 'fbb');

        $registry->set('foo', array(
            2     => 2,
            3     => 3,
            'bar' => array(
                'baz' => 'fbb'
             )
        ));
    }

    protected function getFormFieldMock($name, $value = null)
    {
        $field = $this
            ->getMockBuilder('Symfony\\Component\\DomCrawler\\Field\\FormField')
            ->setMethods(array('getName', 'getValue', 'setValue', 'initialize'))
            ->disableOriginalConstructor()
            ->getMock()
        ;

        $field
            ->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($name))
        ;

        $field
            ->expects($this->any())
            ->method('getValue')
            ->will($this->returnValue($value))
        ;

        return $field;
    }

    protected function createForm($form, $method = null, $currentUri = null)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html>'.$form.'</html>');

        $nodes = $dom->getElementsByTagName('input');
        $xPath = new \DOMXPath($dom);
        $nodes = $xPath->query('//input | //button');

        if (null === $currentUri) {
            $currentUri = 'http://example.com/';
        }

        return new Form($nodes->item($nodes->length - 1), $currentUri, $method);
    }

    protected function createTestHtml5Form()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('
        <html>
            <h1>Hello form</h1>
            <form id="form-1" action="" method="POST">
                <div><input type="checkbox" name="apples[]" value="1" checked /></div>
                <input form="form_2" type="checkbox" name="oranges[]" value="1" checked />
                <div><label></label><input form="form-1" type="hidden" name="form_name" value="form-1" /></div>
                <input form="form-1" type="submit" name="button_1" value="Capture fields" />
                <button form="form_2" type="submit" name="button_2">Submit form_2</button>
            </form>
            <input form="form-1" type="checkbox" name="apples[]" value="2" checked />
            <form id="form_2" action="" method="POST">
                <div><div><input type="checkbox" name="oranges[]" value="2" checked />
                <input type="checkbox" name="oranges[]" value="3" checked /></div></div>
                <input form="form_2" type="hidden" name="form_name" value="form_2" />
                <input form="form-1" type="hidden" name="outer_field" value="success" />
                <button form="form-1" type="submit" name="button_3">Submit from outside the form</button>
                <div>
                    <label for="app_frontend_form_type_contact_form_type_contactType">Message subject</label>
                    <div>
                        <select name="app_frontend_form_type_contact_form_type[contactType]" id="app_frontend_form_type_contact_form_type_contactType"><option selected="selected" value="">Please select subject</option><option id="1">Test type</option></select>
                    </div>
                </div>
                <div>
                    <label for="app_frontend_form_type_contact_form_type_firstName">Firstname</label>
                    <input type="text" name="app_frontend_form_type_contact_form_type[firstName]" value="John" id="app_frontend_form_type_contact_form_type_firstName"/>
                </div>
            </form>
            <button />
        </html>');

        return $dom;
    }
}
PKA1[m�Y���:DomCrawler/Symfony/Component/DomCrawler/Tests/LinkTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DomCrawler\Tests;

use Symfony\Component\DomCrawler\Link;

class LinkTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     */
    public function testConstructorWithANonATag()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><div><div></html>');

        new Link($dom->getElementsByTagName('div')->item(0), 'http://www.example.com/');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructorWithAnInvalidCurrentUri()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><a href="/foo">foo</a></html>');

        new Link($dom->getElementsByTagName('a')->item(0), 'example.com');
    }

    public function testGetNode()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><a href="/foo">foo</a></html>');

        $node = $dom->getElementsByTagName('a')->item(0);
        $link = new Link($node, 'http://example.com/');

        $this->assertEquals($node, $link->getNode(), '->getNode() returns the node associated with the link');
    }

    public function testGetMethod()
    {
        $dom = new \DOMDocument();
        $dom->loadHTML('<html><a href="/foo">foo</a></html>');

        $node = $dom->getElementsByTagName('a')->item(0);
        $link = new Link($node, 'http://example.com/');

        $this->assertEquals('GET', $link->getMethod(), '->getMethod() returns the method of the link');

        $link = new Link($node, 'http://example.com/', 'post');
        $this->assertEquals('POST', $link->getMethod(), '->getMethod() returns the method of the link');
    }

    /**
     * @dataProvider getGetUriTests
     */
    public function testGetUri($url, $currentUri, $expected)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML(sprintf('<html><a href="%s">foo</a></html>', $url));
        $link = new Link($dom->getElementsByTagName('a')->item(0), $currentUri);

        $this->assertEquals($expected, $link->getUri());
    }

    /**
     * @dataProvider getGetUriTests
     */
    public function testGetUriOnArea($url, $currentUri, $expected)
    {
        $dom = new \DOMDocument();
        $dom->loadHTML(sprintf('<html><map><area href="%s" /></map></html>', $url));
        $link = new Link($dom->getElementsByTagName('area')->item(0), $currentUri);

        $this->assertEquals($expected, $link->getUri());
    }

    public function getGetUriTests()
    {
        return array(
            array('/foo', 'http://localhost/bar/foo/', 'http://localhost/foo'),
            array('/foo', 'http://localhost/bar/foo', 'http://localhost/foo'),
            array('
            /foo', 'http://localhost/bar/foo/', 'http://localhost/foo'),
            array('/foo
            ', 'http://localhost/bar/foo', 'http://localhost/foo'),

            array('foo', 'http://localhost/bar/foo/', 'http://localhost/bar/foo/foo'),
            array('foo', 'http://localhost/bar/foo', 'http://localhost/bar/foo'),

            array('', 'http://localhost/bar/', 'http://localhost/bar/'),
            array('#', 'http://localhost/bar/', 'http://localhost/bar/#'),
            array('#bar', 'http://localhost/bar/#foo', 'http://localhost/bar/#bar'),
            array('?a=b', 'http://localhost/bar/', 'http://localhost/bar/?a=b'),

            array('http://login.foo.com/foo', 'http://localhost/bar/', 'http://login.foo.com/foo'),
            array('https://login.foo.com/foo', 'https://localhost/bar/', 'https://login.foo.com/foo'),
            array('mailto:foo@bar.com', 'http://localhost/foo', 'mailto:foo@bar.com'),

            // tests schema relative URL (issue #7169)
            array('//login.foo.com/foo', 'http://localhost/bar/', 'http://login.foo.com/foo'),
            array('//login.foo.com/foo', 'https://localhost/bar/', 'https://login.foo.com/foo'),

            array('?foo=2', 'http://localhost?foo=1', 'http://localhost?foo=2'),
            array('?foo=2', 'http://localhost/?foo=1', 'http://localhost/?foo=2'),
            array('?foo=2', 'http://localhost/bar?foo=1', 'http://localhost/bar?foo=2'),
            array('?foo=2', 'http://localhost/bar/?foo=1', 'http://localhost/bar/?foo=2'),
            array('?bar=2', 'http://localhost?foo=1', 'http://localhost?bar=2'),

            array('foo', 'http://login.foo.com/bar/baz?/query/string', 'http://login.foo.com/bar/foo'),

            array('.', 'http://localhost/foo/bar/baz', 'http://localhost/foo/bar/'),
            array('./', 'http://localhost/foo/bar/baz', 'http://localhost/foo/bar/'),
            array('./foo', 'http://localhost/foo/bar/baz', 'http://localhost/foo/bar/foo'),
            array('..', 'http://localhost/foo/bar/baz', 'http://localhost/foo/'),
            array('../', 'http://localhost/foo/bar/baz', 'http://localhost/foo/'),
            array('../foo', 'http://localhost/foo/bar/baz', 'http://localhost/foo/foo'),
            array('../..', 'http://localhost/foo/bar/baz', 'http://localhost/'),
            array('../../', 'http://localhost/foo/bar/baz', 'http://localhost/'),
            array('../../foo', 'http://localhost/foo/bar/baz', 'http://localhost/foo'),
            array('../../foo', 'http://localhost/bar/foo/', 'http://localhost/foo'),
            array('../bar/../../foo', 'http://localhost/bar/foo/', 'http://localhost/foo'),
            array('../bar/./../../foo', 'http://localhost/bar/foo/', 'http://localhost/foo'),
            array('../../', 'http://localhost/', 'http://localhost/'),
            array('../../', 'http://localhost', 'http://localhost/'),

            array('/foo', 'file:///', 'file:///foo'),
            array('/foo', 'file:///bar/baz', 'file:///foo'),
            array('foo', 'file:///', 'file:///foo'),
            array('foo', 'file:///bar/baz', 'file:///bar/foo'),
        );
    }
}
PKA1[)q0�ll8DomCrawler/Symfony/Component/DomCrawler/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony DomCrawler Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKB1[��H�77GCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/ids.htmlnu�[���<html id="html"><head>
  <link id="link-href" href="foo" />
  <link id="link-nohref" />
</head><body>
<div id="outer-div">
 <a id="name-anchor" name="foo"></a>
 <a id="tag-anchor" rel="tag" href="http://localhost/foo">link</a>
 <a id="nofollow-anchor" rel="nofollow" href="https://example.org">
    link</a>
 <ol id="first-ol" class="a b c">
   <li id="first-li">content</li>
   <li id="second-li" lang="En-us">
     <div id="li-div">
     </div>
   </li>
   <li id="third-li" class="ab c"></li>
   <li id="fourth-li" class="ab
c"></li>
   <li id="fifth-li"></li>
   <li id="sixth-li"></li>
   <li id="seventh-li">  </li>
 </ol>
 <p id="paragraph">
   <b id="p-b">hi</b> <em id="p-em">there</em>
   <b id="p-b2">guy</b>
   <input type="checkbox" id="checkbox-unchecked" />
   <input type="checkbox" id="checkbox-disabled" disabled="" />
   <input type="text" id="text-checked" checked="checked" />
   <input type="hidden" />
   <input type="hidden" disabled="disabled" />
   <input type="checkbox" id="checkbox-checked" checked="checked" />
   <input type="checkbox" id="checkbox-disabled-checked"
          disabled="disabled" checked="checked" />
   <fieldset id="fieldset" disabled="disabled">
     <input type="checkbox" id="checkbox-fieldset-disabled" />
     <input type="hidden" />
   </fieldset>
 </p>
 <ol id="second-ol">
 </ol>
 <map name="dummymap">
   <area shape="circle" coords="200,250,25" href="foo.html" id="area-href" />
   <area shape="default" id="area-nohref" />
 </map>
</div>
<div id="foobar-div" foobar="ab bc
cde"><span id="foobar-span"></span></div>
</body></html>
PKB1[miĪ:�:NCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/shakespear.htmlnu�[���<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" debug="true">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
	<div id="test">
	<div class="dialog">
	<h2>As You Like It</h2>
	<div id="playwright">
	  by William Shakespeare
	</div>
	<div class="dialog scene thirdClass" id="scene1">
	  <h3>ACT I, SCENE III. A room in the palace.</h3>
	  <div class="dialog">
	  <div class="direction">Enter CELIA and ROSALIND</div>
	  </div>
	  <div id="speech1" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.1">Why, cousin! why, Rosalind! Cupid have mercy! not a word?</div>
	  </div>
	  <div id="speech2" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.2">Not one to throw at a dog.</div>
	  </div>
	  <div id="speech3" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.3">No, thy words are too precious to be cast away upon</div>
	  <div id="scene1.3.4">curs; throw some of them at me; come, lame me with reasons.</div>
	  </div>
	  <div id="speech4" class="character">ROSALIND</div>
	  <div id="speech5" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.8">But is all this for your father?</div>
	  </div>
	  <div class="dialog">
	  <div id="scene1.3.5">Then there were two cousins laid up; when the one</div>
	  <div id="scene1.3.6">should be lamed with reasons and the other mad</div>
	  <div id="scene1.3.7">without any.</div>
	  </div>
	  <div id="speech6" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.9">No, some of it is for my child's father. O, how</div>
	  <div id="scene1.3.10">full of briers is this working-day world!</div>
	  </div>
	  <div id="speech7" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.11">They are but burs, cousin, thrown upon thee in</div>
	  <div id="scene1.3.12">holiday foolery: if we walk not in the trodden</div>
	  <div id="scene1.3.13">paths our very petticoats will catch them.</div>
	  </div>
	  <div id="speech8" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.14">I could shake them off my coat: these burs are in my heart.</div>
	  </div>
	  <div id="speech9" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.15">Hem them away.</div>
	  </div>
	  <div id="speech10" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.16">I would try, if I could cry 'hem' and have him.</div>
	  </div>
	  <div id="speech11" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.17">Come, come, wrestle with thy affections.</div>
	  </div>
	  <div id="speech12" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.18">O, they take the part of a better wrestler than myself!</div>
	  </div>
	  <div id="speech13" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.19">O, a good wish upon you! you will try in time, in</div>
	  <div id="scene1.3.20">despite of a fall. But, turning these jests out of</div>
	  <div id="scene1.3.21">service, let us talk in good earnest: is it</div>
	  <div id="scene1.3.22">possible, on such a sudden, you should fall into so</div>
	  <div id="scene1.3.23">strong a liking with old Sir Rowland's youngest son?</div>
	  </div>
	  <div id="speech14" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.24">The duke my father loved his father dearly.</div>
	  </div>
	  <div id="speech15" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.25">Doth it therefore ensue that you should love his son</div>
	  <div id="scene1.3.26">dearly? By this kind of chase, I should hate him,</div>
	  <div id="scene1.3.27">for my father hated his father dearly; yet I hate</div>
	  <div id="scene1.3.28">not Orlando.</div>
	  </div>
	  <div id="speech16" class="character">ROSALIND</div>
	  <div title="wtf" class="dialog">
	  <div id="scene1.3.29">No, faith, hate him not, for my sake.</div>
	  </div>
	  <div id="speech17" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.30">Why should I not? doth he not deserve well?</div>
	  </div>
	  <div id="speech18" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.31">Let me love him for that, and do you love him</div>
	  <div id="scene1.3.32">because I do. Look, here comes the duke.</div>
	  </div>
	  <div id="speech19" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.33">With his eyes full of anger.</div>
	  <div class="direction">Enter DUKE FREDERICK, with Lords</div>
	  </div>
	  <div id="speech20" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.34">Mistress, dispatch you with your safest haste</div>
	  <div id="scene1.3.35">And get you from our court.</div>
	  </div>
	  <div id="speech21" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.36">Me, uncle?</div>
	  </div>
	  <div id="speech22" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.37">You, cousin</div>
	  <div id="scene1.3.38">Within these ten days if that thou be'st found</div>
	  <div id="scene1.3.39">So near our public court as twenty miles,</div>
	  <div id="scene1.3.40">Thou diest for it.</div>
	  </div>
	  <div id="speech23" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.41">                  I do beseech your grace,</div>
	  <div id="scene1.3.42">Let me the knowledge of my fault bear with me:</div>
	  <div id="scene1.3.43">If with myself I hold intelligence</div>
	  <div id="scene1.3.44">Or have acquaintance with mine own desires,</div>
	  <div id="scene1.3.45">If that I do not dream or be not frantic,--</div>
	  <div id="scene1.3.46">As I do trust I am not--then, dear uncle,</div>
	  <div id="scene1.3.47">Never so much as in a thought unborn</div>
	  <div id="scene1.3.48">Did I offend your highness.</div>
	  </div>
	  <div id="speech24" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.49">Thus do all traitors:</div>
	  <div id="scene1.3.50">If their purgation did consist in words,</div>
	  <div id="scene1.3.51">They are as innocent as grace itself:</div>
	  <div id="scene1.3.52">Let it suffice thee that I trust thee not.</div>
	  </div>
	  <div id="speech25" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.53">Yet your mistrust cannot make me a traitor:</div>
	  <div id="scene1.3.54">Tell me whereon the likelihood depends.</div>
	  </div>
	  <div id="speech26" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.55">Thou art thy father's daughter; there's enough.</div>
	  </div>
	  <div id="speech27" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.56">So was I when your highness took his dukedom;</div>
	  <div id="scene1.3.57">So was I when your highness banish'd him:</div>
	  <div id="scene1.3.58">Treason is not inherited, my lord;</div>
	  <div id="scene1.3.59">Or, if we did derive it from our friends,</div>
	  <div id="scene1.3.60">What's that to me? my father was no traitor:</div>
	  <div id="scene1.3.61">Then, good my liege, mistake me not so much</div>
	  <div id="scene1.3.62">To think my poverty is treacherous.</div>
	  </div>
	  <div id="speech28" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.63">Dear sovereign, hear me speak.</div>
	  </div>
	  <div id="speech29" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.64">Ay, Celia; we stay'd her for your sake,</div>
	  <div id="scene1.3.65">Else had she with her father ranged along.</div>
	  </div>
	  <div id="speech30" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.66">I did not then entreat to have her stay;</div>
	  <div id="scene1.3.67">It was your pleasure and your own remorse:</div>
	  <div id="scene1.3.68">I was too young that time to value her;</div>
	  <div id="scene1.3.69">But now I know her: if she be a traitor,</div>
	  <div id="scene1.3.70">Why so am I; we still have slept together,</div>
	  <div id="scene1.3.71">Rose at an instant, learn'd, play'd, eat together,</div>
	  <div id="scene1.3.72">And wheresoever we went, like Juno's swans,</div>
	  <div id="scene1.3.73">Still we went coupled and inseparable.</div>
	  </div>
	  <div id="speech31" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.74">She is too subtle for thee; and her smoothness,</div>
	  <div id="scene1.3.75">Her very silence and her patience</div>
	  <div id="scene1.3.76">Speak to the people, and they pity her.</div>
	  <div id="scene1.3.77">Thou art a fool: she robs thee of thy name;</div>
	  <div id="scene1.3.78">And thou wilt show more bright and seem more virtuous</div>
	  <div id="scene1.3.79">When she is gone. Then open not thy lips:</div>
	  <div id="scene1.3.80">Firm and irrevocable is my doom</div>
	  <div id="scene1.3.81">Which I have pass'd upon her; she is banish'd.</div>
	  </div>
	  <div id="speech32" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.82">Pronounce that sentence then on me, my liege:</div>
	  <div id="scene1.3.83">I cannot live out of her company.</div>
	  </div>
	  <div id="speech33" class="character">DUKE FREDERICK</div>
	  <div class="dialog">
	  <div id="scene1.3.84">You are a fool. You, niece, provide yourself:</div>
	  <div id="scene1.3.85">If you outstay the time, upon mine honour,</div>
	  <div id="scene1.3.86">And in the greatness of my word, you die.</div>
	  <div class="direction">Exeunt DUKE FREDERICK and Lords</div>
	  </div>
	  <div id="speech34" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.87">O my poor Rosalind, whither wilt thou go?</div>
	  <div id="scene1.3.88">Wilt thou change fathers? I will give thee mine.</div>
	  <div id="scene1.3.89">I charge thee, be not thou more grieved than I am.</div>
	  </div>
	  <div id="speech35" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.90">I have more cause.</div>
	  </div>
	  <div id="speech36" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.91">                  Thou hast not, cousin;</div>
	  <div id="scene1.3.92">Prithee be cheerful: know'st thou not, the duke</div>
	  <div id="scene1.3.93">Hath banish'd me, his daughter?</div>
	  </div>
	  <div id="speech37" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.94">That he hath not.</div>
	  </div>
	  <div id="speech38" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.95">No, hath not? Rosalind lacks then the love</div>
	  <div id="scene1.3.96">Which teacheth thee that thou and I am one:</div>
	  <div id="scene1.3.97">Shall we be sunder'd? shall we part, sweet girl?</div>
	  <div id="scene1.3.98">No: let my father seek another heir.</div>
	  <div id="scene1.3.99">Therefore devise with me how we may fly,</div>
	  <div id="scene1.3.100">Whither to go and what to bear with us;</div>
	  <div id="scene1.3.101">And do not seek to take your change upon you,</div>
	  <div id="scene1.3.102">To bear your griefs yourself and leave me out;</div>
	  <div id="scene1.3.103">For, by this heaven, now at our sorrows pale,</div>
	  <div id="scene1.3.104">Say what thou canst, I'll go along with thee.</div>
	  </div>
	  <div id="speech39" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.105">Why, whither shall we go?</div>
	  </div>
	  <div id="speech40" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.106">To seek my uncle in the forest of Arden.</div>
	  </div>
	  <div id="speech41" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.107">Alas, what danger will it be to us,</div>
	  <div id="scene1.3.108">Maids as we are, to travel forth so far!</div>
	  <div id="scene1.3.109">Beauty provoketh thieves sooner than gold.</div>
	  </div>
	  <div id="speech42" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.110">I'll put myself in poor and mean attire</div>
	  <div id="scene1.3.111">And with a kind of umber smirch my face;</div>
	  <div id="scene1.3.112">The like do you: so shall we pass along</div>
	  <div id="scene1.3.113">And never stir assailants.</div>
	  </div>
	  <div id="speech43" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.114">Were it not better,</div>
	  <div id="scene1.3.115">Because that I am more than common tall,</div>
	  <div id="scene1.3.116">That I did suit me all points like a man?</div>
	  <div id="scene1.3.117">A gallant curtle-axe upon my thigh,</div>
	  <div id="scene1.3.118">A boar-spear in my hand; and--in my heart</div>
	  <div id="scene1.3.119">Lie there what hidden woman's fear there will--</div>
	  <div id="scene1.3.120">We'll have a swashing and a martial outside,</div>
	  <div id="scene1.3.121">As many other mannish cowards have</div>
	  <div id="scene1.3.122">That do outface it with their semblances.</div>
	  </div>
	  <div id="speech44" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.123">What shall I call thee when thou art a man?</div>
	  </div>
	  <div id="speech45" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.124">I'll have no worse a name than Jove's own page;</div>
	  <div id="scene1.3.125">And therefore look you call me Ganymede.</div>
	  <div id="scene1.3.126">But what will you be call'd?</div>
	  </div>
	  <div id="speech46" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.127">Something that hath a reference to my state</div>
	  <div id="scene1.3.128">No longer Celia, but Aliena.</div>
	  </div>
	  <div id="speech47" class="character">ROSALIND</div>
	  <div class="dialog">
	  <div id="scene1.3.129">But, cousin, what if we assay'd to steal</div>
	  <div id="scene1.3.130">The clownish fool out of your father's court?</div>
	  <div id="scene1.3.131">Would he not be a comfort to our travel?</div>
	  </div>
	  <div id="speech48" class="character">CELIA</div>
	  <div class="dialog">
	  <div id="scene1.3.132">He'll go along o'er the wide world with me;</div>
	  <div id="scene1.3.133">Leave me alone to woo him. Let's away,</div>
	  <div id="scene1.3.134">And get our jewels and our wealth together,</div>
	  <div id="scene1.3.135">Devise the fittest time and safest way</div>
	  <div id="scene1.3.136">To hide us from pursuit that will be made</div>
	  <div id="scene1.3.137">After my flight. Now go we in content</div>
	  <div id="scene1.3.138">To liberty and not to banishment.</div>
	  <div class="direction">Exeunt</div>
	  </div>
	</div>
	</div>
</div>
</body>
</html>
PKB1[�B�==GCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/lang.xmlnu�[���<test>
  <a id="first" xml:lang="en">a</a>
  <b id="second" xml:lang="en-US">b</b>
  <c id="third" xml:lang="en-Nz">c</c>
  <d id="fourth" xml:lang="En-us">d</d>
  <e id="fifth" xml:lang="fr">e</e>
  <f id="sixth" xml:lang="ru">f</f>
  <g id="seventh" xml:lang="de">
    <h id="eighth" xml:lang="zh"/>
  </g>
</test>
PKB1[1�HCHCHCssSelector/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\XPath;

use Symfony\Component\CssSelector\XPath\Extension\HtmlExtension;
use Symfony\Component\CssSelector\XPath\Translator;

class TranslatorTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getXpathLiteralTestData */
    public function testXpathLiteral($value, $literal)
    {
        $this->assertEquals($literal, Translator::getXpathLiteral($value));
    }

    /** @dataProvider getCssToXPathTestData */
    public function testCssToXPath($css, $xpath)
    {
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $this->assertEquals($xpath, $translator->cssToXPath($css, ''));
    }

    /** @dataProvider getXmlLangTestData */
    public function testXmlLang($css, array $elementsId)
    {
        $translator = new Translator();
        $document = new \SimpleXMLElement(file_get_contents(__DIR__.'/Fixtures/lang.xml'));
        $elements = $document->xpath($translator->cssToXPath($css));
        $this->assertEquals(count($elementsId), count($elements));
        foreach ($elements as $element) {
            $this->assertTrue(in_array($element->attributes()->id, $elementsId));
        }
    }

    /** @dataProvider getHtmlIdsTestData */
    public function testHtmlIds($css, array $elementsId)
    {
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $document = new \DOMDocument();
        $document->strictErrorChecking = false;
        $internalErrors = libxml_use_internal_errors(true);
        $document->loadHTMLFile(__DIR__.'/Fixtures/ids.html');
        $document = simplexml_import_dom($document);
        $elements = $document->xpath($translator->cssToXPath($css));
        $this->assertCount(count($elementsId), $elementsId);
        foreach ($elements as $element) {
            if (null !== $element->attributes()->id) {
                $this->assertTrue(in_array($element->attributes()->id, $elementsId));
            }
        }
        libxml_clear_errors();
        libxml_use_internal_errors($internalErrors);
    }

    /** @dataProvider getHtmlShakespearTestData */
    public function testHtmlShakespear($css, $count)
    {
        $translator = new Translator();
        $translator->registerExtension(new HtmlExtension($translator));
        $document = new \DOMDocument();
        $document->strictErrorChecking = false;
        $document->loadHTMLFile(__DIR__.'/Fixtures/shakespear.html');
        $document = simplexml_import_dom($document);
        $bodies = $document->xpath('//body');
        $elements = $bodies[0]->xpath($translator->cssToXPath($css));
        $this->assertEquals($count, count($elements));
    }

    public function getXpathLiteralTestData()
    {
        return array(
            array('foo', "'foo'"),
            array("foo's bar", '"foo\'s bar"'),
            array("foo's \"middle\" bar", 'concat(\'foo\', "\'", \'s "middle" bar\')'),
            array("foo's 'middle' \"bar\"", 'concat(\'foo\', "\'", \'s \', "\'", \'middle\', "\'", \' "bar"\')'),
        );
    }

    public function getCssToXPathTestData()
    {
        return array(
            array('*', "*"),
            array('e', "e"),
            array('*|e', "e"),
            array('e|f', "e:f"),
            array('e[foo]', "e[@foo]"),
            array('e[foo|bar]', "e[@foo:bar]"),
            array('e[foo="bar"]', "e[@foo = 'bar']"),
            array('e[foo~="bar"]', "e[@foo and contains(concat(' ', normalize-space(@foo), ' '), ' bar ')]"),
            array('e[foo^="bar"]', "e[@foo and starts-with(@foo, 'bar')]"),
            array('e[foo$="bar"]', "e[@foo and substring(@foo, string-length(@foo)-2) = 'bar']"),
            array('e[foo*="bar"]', "e[@foo and contains(@foo, 'bar')]"),
            array('e[hreflang|="en"]', "e[@hreflang and (@hreflang = 'en' or starts-with(@hreflang, 'en-'))]"),
            array('e:nth-child(1)', "*/*[name() = 'e' and (position() = 1)]"),
            array('e:nth-last-child(1)', "*/*[name() = 'e' and (position() = last() - 0)]"),
            array('e:nth-last-child(2n+2)', "*/*[name() = 'e' and (last() - position() - 1 >= 0 and (last() - position() - 1) mod 2 = 0)]"),
            array('e:nth-of-type(1)', "*/e[position() = 1]"),
            array('e:nth-last-of-type(1)', "*/e[position() = last() - 0]"),
            array('div e:nth-last-of-type(1) .aclass', "div/descendant-or-self::*/e[position() = last() - 0]/descendant-or-self::*/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' aclass ')]"),
            array('e:first-child', "*/*[name() = 'e' and (position() = 1)]"),
            array('e:last-child', "*/*[name() = 'e' and (position() = last())]"),
            array('e:first-of-type', "*/e[position() = 1]"),
            array('e:last-of-type', "*/e[position() = last()]"),
            array('e:only-child', "*/*[name() = 'e' and (last() = 1)]"),
            array('e:only-of-type', "e[last() = 1]"),
            array('e:empty', "e[not(*) and not(string-length())]"),
            array('e:EmPTY', "e[not(*) and not(string-length())]"),
            array('e:root', "e[not(parent::*)]"),
            array('e:hover', "e[0]"),
            array('e:contains("foo")', "e[contains(string(.), 'foo')]"),
            array('e:ConTains(foo)', "e[contains(string(.), 'foo')]"),
            array('e.warning', "e[@class and contains(concat(' ', normalize-space(@class), ' '), ' warning ')]"),
            array('e#myid', "e[@id = 'myid']"),
            array('e:not(:nth-child(odd))', "e[not(position() - 1 >= 0 and (position() - 1) mod 2 = 0)]"),
            array('e:nOT(*)', "e[0]"),
            array('e f', "e/descendant-or-self::*/f"),
            array('e > f', "e/f"),
            array('e + f', "e/following-sibling::*[name() = 'f' and (position() = 1)]"),
            array('e ~ f', "e/following-sibling::f"),
            array('div#container p', "div[@id = 'container']/descendant-or-self::*/p"),
        );
    }

    public function getXmlLangTestData()
    {
        return array(
            array(':lang("EN")', array('first', 'second', 'third', 'fourth')),
            array(':lang("en-us")', array('second', 'fourth')),
            array(':lang(en-nz)', array('third')),
            array(':lang(fr)', array('fifth')),
            array(':lang(ru)', array('sixth')),
            array(":lang('ZH')", array('eighth')),
            array(':lang(de) :lang(zh)', array('eighth')),
            array(':lang(en), :lang(zh)', array('first', 'second', 'third', 'fourth', 'eighth')),
            array(':lang(es)', array()),
        );
    }

    public function getHtmlIdsTestData()
    {
        return array(
            array('div', array('outer-div', 'li-div', 'foobar-div')),
            array('DIV', array('outer-div', 'li-div', 'foobar-div')),  // case-insensitive in HTML
            array('div div', array('li-div')),
            array('div, div div', array('outer-div', 'li-div', 'foobar-div')),
            array('a[name]', array('name-anchor')),
            array('a[NAme]', array('name-anchor')), // case-insensitive in HTML:
            array('a[rel]', array('tag-anchor', 'nofollow-anchor')),
            array('a[rel="tag"]', array('tag-anchor')),
            array('a[href*="localhost"]', array('tag-anchor')),
            array('a[href*=""]', array()),
            array('a[href^="http"]', array('tag-anchor', 'nofollow-anchor')),
            array('a[href^="http:"]', array('tag-anchor')),
            array('a[href^=""]', array()),
            array('a[href$="org"]', array('nofollow-anchor')),
            array('a[href$=""]', array()),
            array('div[foobar~="bc"]', array('foobar-div')),
            array('div[foobar~="cde"]', array('foobar-div')),
            array('[foobar~="ab bc"]', array('foobar-div')),
            array('[foobar~=""]', array()),
            array('[foobar~=" \t"]', array()),
            array('div[foobar~="cd"]', array()),
            array('*[lang|="En"]', array('second-li')),
            array('[lang|="En-us"]', array('second-li')),
            // Attribute values are case sensitive
            array('*[lang|="en"]', array()),
            array('[lang|="en-US"]', array()),
            array('*[lang|="e"]', array()),
            // ... :lang() is not.
            array(':lang("EN")', array('second-li', 'li-div')),
            array('*:lang(en-US)', array('second-li', 'li-div')),
            array(':lang("e")', array()),
            array('li:nth-child(3)', array('third-li')),
            array('li:nth-child(10)', array()),
            array('li:nth-child(2n)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-child(even)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-child(2n+0)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-child(+2n+1)', array('first-li', 'third-li', 'fifth-li', 'seventh-li')),
            array('li:nth-child(odd)', array('first-li', 'third-li', 'fifth-li', 'seventh-li')),
            array('li:nth-child(2n+4)', array('fourth-li', 'sixth-li')),
            array('li:nth-child(3n+1)', array('first-li', 'fourth-li', 'seventh-li')),
            array('li:nth-child(n)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-child(n-1)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-child(n+1)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-child(n+3)', array('third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-child(-n)', array()),
            array('li:nth-child(-n-1)', array()),
            array('li:nth-child(-n+1)', array('first-li')),
            array('li:nth-child(-n+3)', array('first-li', 'second-li', 'third-li')),
            array('li:nth-last-child(0)', array()),
            array('li:nth-last-child(2n)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-last-child(even)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-last-child(2n+2)', array('second-li', 'fourth-li', 'sixth-li')),
            array('li:nth-last-child(n)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-last-child(n-1)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-last-child(n-3)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-last-child(n+1)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li', 'sixth-li', 'seventh-li')),
            array('li:nth-last-child(n+3)', array('first-li', 'second-li', 'third-li', 'fourth-li', 'fifth-li')),
            array('li:nth-last-child(-n)', array()),
            array('li:nth-last-child(-n-1)', array()),
            array('li:nth-last-child(-n+1)', array('seventh-li')),
            array('li:nth-last-child(-n+3)', array('fifth-li', 'sixth-li', 'seventh-li')),
            array('ol:first-of-type', array('first-ol')),
            array('ol:nth-child(1)', array('first-ol')),
            array('ol:nth-of-type(2)', array('second-ol')),
            array('ol:nth-last-of-type(1)', array('second-ol')),
            array('span:only-child', array('foobar-span')),
            array('li div:only-child', array('li-div')),
            array('div *:only-child', array('li-div', 'foobar-span')),
            array('p:only-of-type', array('paragraph')),
            array('a:empty', array('name-anchor')),
            array('a:EMpty', array('name-anchor')),
            array('li:empty', array('third-li', 'fourth-li', 'fifth-li', 'sixth-li')),
            array(':root', array('html')),
            array('html:root', array('html')),
            array('li:root', array()),
            array('* :root', array()),
            array('*:contains("link")', array('html', 'outer-div', 'tag-anchor', 'nofollow-anchor')),
            array(':CONtains("link")', array('html', 'outer-div', 'tag-anchor', 'nofollow-anchor')),
            array('*:contains("LInk")', array()),  // case sensitive
            array('*:contains("e")', array('html', 'nil', 'outer-div', 'first-ol', 'first-li', 'paragraph', 'p-em')),
            array('*:contains("E")', array()),  // case-sensitive
            array('.a', array('first-ol')),
            array('.b', array('first-ol')),
            array('*.a', array('first-ol')),
            array('ol.a', array('first-ol')),
            array('.c', array('first-ol', 'third-li', 'fourth-li')),
            array('*.c', array('first-ol', 'third-li', 'fourth-li')),
            array('ol *.c', array('third-li', 'fourth-li')),
            array('ol li.c', array('third-li', 'fourth-li')),
            array('li ~ li.c', array('third-li', 'fourth-li')),
            array('ol > li.c', array('third-li', 'fourth-li')),
            array('#first-li', array('first-li')),
            array('li#first-li', array('first-li')),
            array('*#first-li', array('first-li')),
            array('li div', array('li-div')),
            array('li > div', array('li-div')),
            array('div div', array('li-div')),
            array('div > div', array()),
            array('div>.c', array('first-ol')),
            array('div > .c', array('first-ol')),
            array('div + div', array('foobar-div')),
            array('a ~ a', array('tag-anchor', 'nofollow-anchor')),
            array('a[rel="tag"] ~ a', array('nofollow-anchor')),
            array('ol#first-ol li:last-child', array('seventh-li')),
            array('ol#first-ol *:last-child', array('li-div', 'seventh-li')),
            array('#outer-div:first-child', array('outer-div')),
            array('#outer-div :first-child', array('name-anchor', 'first-li', 'li-div', 'p-b', 'checkbox-fieldset-disabled', 'area-href')),
            array('a[href]', array('tag-anchor', 'nofollow-anchor')),
            array(':not(*)', array()),
            array('a:not([href])', array('name-anchor')),
            array('ol :Not(li[class])', array('first-li', 'second-li', 'li-div', 'fifth-li', 'sixth-li', 'seventh-li')),
            // HTML-specific
            array(':link', array('link-href', 'tag-anchor', 'nofollow-anchor', 'area-href')),
            array(':visited', array()),
            array(':enabled', array('link-href', 'tag-anchor', 'nofollow-anchor', 'checkbox-unchecked', 'text-checked', 'checkbox-checked', 'area-href')),
            array(':disabled', array('checkbox-disabled', 'checkbox-disabled-checked', 'fieldset', 'checkbox-fieldset-disabled')),
            array(':checked', array('checkbox-checked', 'checkbox-disabled-checked')),
        );
    }

    public function getHtmlShakespearTestData()
    {
        return array(
            array('*', 246),
            array('div:contains(CELIA)', 26),
            array('div:only-child', 22), // ?
            array('div:nth-child(even)', 106),
            array('div:nth-child(2n)', 106),
            array('div:nth-child(odd)', 137),
            array('div:nth-child(2n+1)', 137),
            array('div:nth-child(n)', 243),
            array('div:last-child', 53),
            array('div:first-child', 51),
            array('div > div', 242),
            array('div + div', 190),
            array('div ~ div', 190),
            array('body', 1),
            array('body div', 243),
            array('div', 243),
            array('div div', 242),
            array('div div div', 241),
            array('div, div, div', 243),
            array('div, a, span', 243),
            array('.dialog', 51),
            array('div.dialog', 51),
            array('div .dialog', 51),
            array('div.character, div.dialog', 99),
            array('div.direction.dialog', 0),
            array('div.dialog.direction', 0),
            array('div.dialog.scene', 1),
            array('div.scene.scene', 1),
            array('div.scene .scene', 0),
            array('div.direction .dialog ', 0),
            array('div .dialog .direction', 4),
            array('div.dialog .dialog .direction', 4),
            array('#speech5', 1),
            array('div#speech5', 1),
            array('div #speech5', 1),
            array('div.scene div.dialog', 49),
            array('div#scene1 div.dialog div', 142),
            array('#scene1 #speech1', 1),
            array('div[class]', 103),
            array('div[class=dialog]', 50),
            array('div[class^=dia]', 51),
            array('div[class$=log]', 50),
            array('div[class*=sce]', 1),
            array('div[class|=dialog]', 50), // ? Seems right
            array('div[class!=madeup]', 243), // ? Seems right
            array('div[class~=dialog]', 51), // ? Seems right
        );
    }
}
PKB1[o,q��HCssSelector/Symfony/Component/CssSelector/Tests/Node/ElementNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ElementNode;

class ElementNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new ElementNode(), 'Element[*]'),
            array(new ElementNode(null, 'element'), 'Element[element]'),
            array(new ElementNode('namespace', 'element'), 'Element[namespace|element]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new ElementNode(), 0),
            array(new ElementNode(null, 'element'), 1),
            array(new ElementNode('namespace', 'element'),1),
        );
    }
}
PKB1[�BնVVECssSelector/Symfony/Component/CssSelector/Tests/Node/HashNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\HashNode;
use Symfony\Component\CssSelector\Node\ElementNode;

class HashNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new HashNode(new ElementNode(), 'id'), 'Hash[Element[*]#id]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new HashNode(new ElementNode(), 'id'), 100),
            array(new HashNode(new ElementNode(null, 'id'), 'class'), 101),
        );
    }
}
PKB1[V=��hhFCssSelector/Symfony/Component/CssSelector/Tests/Node/ClassNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ClassNode;
use Symfony\Component\CssSelector\Node\ElementNode;

class ClassNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new ClassNode(new ElementNode(), 'class'), 'Class[Element[*].class]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new ClassNode(new ElementNode(), 'class'), 10),
            array(new ClassNode(new ElementNode(null, 'element'), 'class'), 11),
        );
    }
}
PKB1[g$i���ICssSelector/Symfony/Component/CssSelector/Tests/Node/NegationNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ClassNode;
use Symfony\Component\CssSelector\Node\NegationNode;
use Symfony\Component\CssSelector\Node\ElementNode;

class NegationNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new NegationNode(new ElementNode(), new ClassNode(new ElementNode(), 'class')), 'Negation[Element[*]:not(Class[Element[*].class])]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new NegationNode(new ElementNode(), new ClassNode(new ElementNode(), 'class')), 10),
        );
    }
}
PKB1[j�
��QCssSelector/Symfony/Component/CssSelector/Tests/Node/CombinedSelectorNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\CombinedSelectorNode;
use Symfony\Component\CssSelector\Node\ElementNode;

class CombinedSelectorNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new CombinedSelectorNode(new ElementNode(), '>', new ElementNode()), 'CombinedSelector[Element[*] > Element[*]]'),
            array(new CombinedSelectorNode(new ElementNode(), ' ', new ElementNode()), 'CombinedSelector[Element[*] <followed> Element[*]]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new CombinedSelectorNode(new ElementNode(), '>', new ElementNode()), 0),
            array(new CombinedSelectorNode(new ElementNode(null, 'element'), '>', new ElementNode()), 1),
            array(new CombinedSelectorNode(new ElementNode(null, 'element'), '>', new ElementNode(null, 'element')), 2),
        );
    }
}
PKB1[�(yآ�ICssSelector/Symfony/Component/CssSelector/Tests/Node/FunctionNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ElementNode;
use Symfony\Component\CssSelector\Node\FunctionNode;
use Symfony\Component\CssSelector\Parser\Token;

class FunctionNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new FunctionNode(new ElementNode(), 'function'), 'Function[Element[*]:function()]'),
            array(new FunctionNode(new ElementNode(), 'function', array(
                new Token(Token::TYPE_IDENTIFIER, 'value', 0),
            )), "Function[Element[*]:function(['value'])]"),
            array(new FunctionNode(new ElementNode(), 'function', array(
                new Token(Token::TYPE_STRING, 'value1', 0),
                new Token(Token::TYPE_NUMBER, 'value2', 0),
            )), "Function[Element[*]:function(['value1', 'value2'])]"),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new FunctionNode(new ElementNode(), 'function'), 10),
            array(new FunctionNode(new ElementNode(), 'function', array(
                new Token(Token::TYPE_IDENTIFIER, 'value', 0),
            )), 10),
            array(new FunctionNode(new ElementNode(), 'function', array(
                new Token(Token::TYPE_STRING, 'value1', 0),
                new Token(Token::TYPE_NUMBER, 'value2', 0),
            )), 10),
        );
    }
}
PKB1[�Y���ICssSelector/Symfony/Component/CssSelector/Tests/Node/AbstractNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\NodeInterface;

abstract class AbstractNodeTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getToStringConversionTestData */
    public function testToStringConversion(NodeInterface $node, $representation)
    {
        $this->assertEquals($representation, (string) $node);
    }

    /** @dataProvider getSpecificityValueTestData */
    public function testSpecificityValue(NodeInterface $node, $value)
    {
        $this->assertEquals($value, $node->getSpecificity()->getValue());
    }

    abstract public function getToStringConversionTestData();
    abstract public function getSpecificityValueTestData();
}
PKB1[_�Ӵ�ICssSelector/Symfony/Component/CssSelector/Tests/Node/SelectorNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ElementNode;
use Symfony\Component\CssSelector\Node\SelectorNode;

class SelectorNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new SelectorNode(new ElementNode()), 'Selector[Element[*]]'),
            array(new SelectorNode(new ElementNode(), 'pseudo'), 'Selector[Element[*]::pseudo]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new SelectorNode(new ElementNode()), 0),
            array(new SelectorNode(new ElementNode(), 'pseudo'), 1),
        );
    }
}
PKB1[���uuHCssSelector/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\Specificity;

class SpecificityTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getValueTestData */
    public function testValue(Specificity $specificity, $value)
    {
        $this->assertEquals($value, $specificity->getValue());
    }

    /** @dataProvider getValueTestData */
    public function testPlusValue(Specificity $specificity, $value)
    {
        $this->assertEquals($value + 123, $specificity->plus(new Specificity(1, 2, 3))->getValue());
    }

    public function getValueTestData()
    {
        return array(
            array(new Specificity(0, 0, 0), 0),
            array(new Specificity(0, 0, 2), 2),
            array(new Specificity(0, 3, 0), 30),
            array(new Specificity(4, 0, 0), 400),
            array(new Specificity(4, 3, 2), 432),
        );
    }
}
PKB1[� _ӽ�JCssSelector/Symfony/Component/CssSelector/Tests/Node/AttributeNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\AttributeNode;
use Symfony\Component\CssSelector\Node\ElementNode;

class AttributeNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new AttributeNode(new ElementNode(), null, 'attribute', 'exists', null), 'Attribute[Element[*][attribute]]'),
            array(new AttributeNode(new ElementNode(), null, 'attribute', '$=', 'value'), "Attribute[Element[*][attribute $= 'value']]"),
            array(new AttributeNode(new ElementNode(), 'namespace', 'attribute', '$=', 'value'), "Attribute[Element[*][namespace|attribute $= 'value']]"),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new AttributeNode(new ElementNode(), null, 'attribute', 'exists', null), 10),
            array(new AttributeNode(new ElementNode(null, 'element'), null, 'attribute', 'exists', null), 11),
            array(new AttributeNode(new ElementNode(), null, 'attribute', '$=', 'value'), 10),
            array(new AttributeNode(new ElementNode(), 'namespace', 'attribute', '$=', 'value'), 10),
        );
    }
}
PKB1[�WDGCssSelector/Symfony/Component/CssSelector/Tests/Node/PseudoNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Node;

use Symfony\Component\CssSelector\Node\ElementNode;
use Symfony\Component\CssSelector\Node\PseudoNode;

class PseudoNodeTest extends AbstractNodeTest
{
    public function getToStringConversionTestData()
    {
        return array(
            array(new PseudoNode(new ElementNode(), 'pseudo'), 'Pseudo[Element[*]:pseudo]'),
        );
    }

    public function getSpecificityValueTestData()
    {
        return array(
            array(new PseudoNode(new ElementNode(), 'pseudo'), 10),
        );
    }
}
PKB1[�/D�CCssSelector/Symfony/Component/CssSelector/Tests/CssSelectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests;

use Symfony\Component\CssSelector\CssSelector;

class CssSelectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCssToXPath()
    {
        $this->assertEquals('descendant-or-self::*', CssSelector::toXPath(''));
        $this->assertEquals('descendant-or-self::h1', CssSelector::toXPath('h1'));
        $this->assertEquals("descendant-or-self::h1[@id = 'foo']", CssSelector::toXPath('h1#foo'));
        $this->assertEquals("descendant-or-self::h1[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]", CssSelector::toXPath('h1.foo'));
        $this->assertEquals('descendant-or-self::foo:h1', CssSelector::toXPath('foo|h1'));
    }

    /** @dataProvider getCssToXPathWithoutPrefixTestData */
    public function testCssToXPathWithoutPrefix($css, $xpath)
    {
        $this->assertEquals($xpath, CssSelector::toXPath($css, ''), '->parse() parses an input string and returns a node');
    }

    public function testParseExceptions()
    {
        try {
            CssSelector::toXPath('h1:');
            $this->fail('->parse() throws an Exception if the css selector is not valid');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\Symfony\Component\CssSelector\Exception\ParseException', $e, '->parse() throws an Exception if the css selector is not valid');
            $this->assertEquals("Expected identifier, but <eof at 3> found.", $e->getMessage(), '->parse() throws an Exception if the css selector is not valid');
        }
    }

    public function getCssToXPathWithoutPrefixTestData()
    {
        return array(
            array('h1', "h1"),
            array('foo|h1', "foo:h1"),
            array('h1, h2, h3', "h1 | h2 | h3"),
            array('h1:nth-child(3n+1)', "*/*[name() = 'h1' and (position() - 1 >= 0 and (position() - 1) mod 3 = 0)]"),
            array('h1 > p', "h1/p"),
            array('h1#foo', "h1[@id = 'foo']"),
            array('h1.foo', "h1[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
            array('h1[class*="foo bar"]', "h1[@class and contains(@class, 'foo bar')]"),
            array('h1[foo|class*="foo bar"]', "h1[@foo:class and contains(@foo:class, 'foo bar')]"),
            array('h1[class]', "h1[@class]"),
            array('h1 .foo', "h1/descendant-or-self::*/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
            array('h1 #foo', "h1/descendant-or-self::*/*[@id = 'foo']"),
            array('h1 [class*=foo]', "h1/descendant-or-self::*/*[@class and contains(@class, 'foo')]"),
            array('div>.foo', "div/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
            array('div > .foo', "div/*[@class and contains(concat(' ', normalize-space(@class), ' '), ' foo ')]"),
        );
    }
}
PKB1[�u̱��UCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/ElementParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Shortcut;

use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\Shortcut\ElementParser;

/**
 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
 */
class ElementParserTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getParseTestData */
    public function testParse($source, $representation)
    {
        $parser = new ElementParser();
        $selectors = $parser->parse($source);
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals($representation, (string) $selector->getTree());
    }

    public function getParseTestData()
    {
        return array(
            array('*', 'Element[*]'),
            array('testel', 'Element[testel]'),
            array('testns|*', 'Element[testns|*]'),
            array('testns|testel', 'Element[testns|testel]'),
        );
    }
}
PKB1[[�nы�SCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/ClassParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Shortcut;

use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\Shortcut\ClassParser;

/**
 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
 */
class ClassParserTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getParseTestData */
    public function testParse($source, $representation)
    {
        $parser = new ClassParser();
        $selectors = $parser->parse($source);
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals($representation, (string) $selector->getTree());
    }

    public function getParseTestData()
    {
        return array(
            array('.testclass', 'Class[Element[*].testclass]'),
            array('testel.testclass', 'Class[Element[testel].testclass]'),
            array('testns|.testclass', 'Class[Element[testns|*].testclass]'),
            array('testns|*.testclass', 'Class[Element[testns|*].testclass]'),
            array('testns|testel.testclass', 'Class[Element[testns|testel].testclass]'),
        );
    }
}
PKB1[>�]��YCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/EmptyStringParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Shortcut;

use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\Shortcut\EmptyStringParser;

/**
 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
 */
class EmptyStringParserTest extends \PHPUnit_Framework_TestCase
{
    public function testParse()
    {
        $parser = new EmptyStringParser();
        $selectors = $parser->parse('');
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals('Element[*]', (string) $selector->getTree());

        $selectors = $parser->parse('this will produce an empty array');
        $this->assertCount(0, $selectors);
    }
}
PKB1[[N�eeRCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/HashParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Shortcut;

use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\Shortcut\HashParser;

/**
 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
 */
class HashParserTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getParseTestData */
    public function testParse($source, $representation)
    {
        $parser = new HashParser();
        $selectors = $parser->parse($source);
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals($representation, (string) $selector->getTree());
    }

    public function getParseTestData()
    {
        return array(
            array('#testid', 'Hash[Element[*]#testid]'),
            array('testel#testid', 'Hash[Element[testel]#testid]'),
            array('testns|#testid', 'Hash[Element[testns|*]#testid]'),
            array('testns|*#testid', 'Hash[Element[testns|*]#testid]'),
            array('testns|testel#testid', 'Hash[Element[testns|testel]#testid]'),
        );
    }
}
PKB1[^���2�2ECssSelector/Symfony/Component/CssSelector/Tests/Parser/ParserTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser;

use Symfony\Component\CssSelector\Exception\SyntaxErrorException;
use Symfony\Component\CssSelector\Node\FunctionNode;
use Symfony\Component\CssSelector\Node\SelectorNode;
use Symfony\Component\CssSelector\Parser\Parser;
use Symfony\Component\CssSelector\Parser\Token;

class ParserTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getParserTestData */
    public function testParser($source, $representation)
    {
        $parser = new Parser();

        $this->assertEquals($representation, array_map(function (SelectorNode $node) {
            return (string) $node->getTree();
        }, $parser->parse($source)));
    }

    /** @dataProvider getParserExceptionTestData */
    public function testParserException($source, $message)
    {
        $parser = new Parser();

        try {
            $parser->parse($source);
            $this->fail('Parser should throw a SyntaxErrorException.');
        } catch (SyntaxErrorException $e) {
            $this->assertEquals($message, $e->getMessage());
        }
    }

    /** @dataProvider getPseudoElementsTestData */
    public function testPseudoElements($source, $element, $pseudo)
    {
        $parser = new Parser();
        $selectors = $parser->parse($source);
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals($element, (string) $selector->getTree());
        $this->assertEquals($pseudo, (string) $selector->getPseudoElement());
    }

    /** @dataProvider getSpecificityTestData */
    public function testSpecificity($source, $value)
    {
        $parser = new Parser();
        $selectors = $parser->parse($source);
        $this->assertCount(1, $selectors);

        /** @var SelectorNode $selector */
        $selector = $selectors[0];
        $this->assertEquals($value, $selector->getSpecificity()->getValue());
    }

    /** @dataProvider getParseSeriesTestData */
    public function testParseSeries($series, $a, $b)
    {
        $parser = new Parser();
        $selectors = $parser->parse(sprintf(':nth-child(%s)', $series));
        $this->assertCount(1, $selectors);

        /** @var FunctionNode $function */
        $function = $selectors[0]->getTree();
        $this->assertEquals(array($a, $b), Parser::parseSeries($function->getArguments()));
    }

    /** @dataProvider getParseSeriesExceptionTestData */
    public function testParseSeriesException($series)
    {
        $parser = new Parser();
        $selectors = $parser->parse(sprintf(':nth-child(%s)', $series));
        $this->assertCount(1, $selectors);

        /** @var FunctionNode $function */
        $function = $selectors[0]->getTree();
        $this->setExpectedException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');
        Parser::parseSeries($function->getArguments());
    }

    public function getParserTestData()
    {
        return array(
            array('*', array('Element[*]')),
            array('*|*', array('Element[*]')),
            array('*|foo', array('Element[foo]')),
            array('foo|*', array('Element[foo|*]')),
            array('foo|bar', array('Element[foo|bar]')),
            array('#foo#bar', array('Hash[Hash[Element[*]#foo]#bar]')),
            array('div>.foo', array('CombinedSelector[Element[div] > Class[Element[*].foo]]')),
            array('div> .foo', array('CombinedSelector[Element[div] > Class[Element[*].foo]]')),
            array('div >.foo', array('CombinedSelector[Element[div] > Class[Element[*].foo]]')),
            array('div > .foo', array('CombinedSelector[Element[div] > Class[Element[*].foo]]')),
            array("div \n>  \t \t .foo", array('CombinedSelector[Element[div] > Class[Element[*].foo]]')),
            array('td.foo,.bar', array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array('td.foo, .bar', array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array("td.foo\t\r\n\f ,\t\r\n\f .bar", array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array('td.foo,.bar', array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array('td.foo, .bar', array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array("td.foo\t\r\n\f ,\t\r\n\f .bar", array('Class[Element[td].foo]', 'Class[Element[*].bar]')),
            array('div, td.foo, div.bar span', array('Element[div]', 'Class[Element[td].foo]', 'CombinedSelector[Class[Element[div].bar] <followed> Element[span]]')),
            array('div > p', array('CombinedSelector[Element[div] > Element[p]]')),
            array('td:first', array('Pseudo[Element[td]:first]')),
            array('td :first', array('CombinedSelector[Element[td] <followed> Pseudo[Element[*]:first]]')),
            array('a[name]', array('Attribute[Element[a][name]]')),
            array("a[ name\t]", array('Attribute[Element[a][name]]')),
            array('a [name]', array('CombinedSelector[Element[a] <followed> Attribute[Element[*][name]]]')),
            array('a[rel="include"]', array("Attribute[Element[a][rel = 'include']]")),
            array('a[rel = include]', array("Attribute[Element[a][rel = 'include']]")),
            array("a[hreflang |= 'en']", array("Attribute[Element[a][hreflang |= 'en']]")),
            array('a[hreflang|=en]', array("Attribute[Element[a][hreflang |= 'en']]")),
            array('div:nth-child(10)', array("Function[Element[div]:nth-child(['10'])]")),
            array(':nth-child(2n+2)', array("Function[Element[*]:nth-child(['2', 'n', '+2'])]")),
            array('div:nth-of-type(10)', array("Function[Element[div]:nth-of-type(['10'])]")),
            array('div div:nth-of-type(10) .aclass', array("CombinedSelector[CombinedSelector[Element[div] <followed> Function[Element[div]:nth-of-type(['10'])]] <followed> Class[Element[*].aclass]]")),
            array('label:only', array('Pseudo[Element[label]:only]')),
            array('a:lang(fr)', array("Function[Element[a]:lang(['fr'])]")),
            array('div:contains("foo")', array("Function[Element[div]:contains(['foo'])]")),
            array('div#foobar', array('Hash[Element[div]#foobar]')),
            array('div:not(div.foo)', array('Negation[Element[div]:not(Class[Element[div].foo])]')),
            array('td ~ th', array('CombinedSelector[Element[td] ~ Element[th]]')),
            array('.foo[data-bar][data-baz=0]', array("Attribute[Attribute[Class[Element[*].foo][data-bar]][data-baz = '0']]")),
        );
    }

    public function getParserExceptionTestData()
    {
        return array(
            array('attributes(href)/html/body/a', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '(', 10))->getMessage()),
            array('attributes(href)', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '(', 10))->getMessage()),
            array('html/body/a', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '/', 4))->getMessage()),
            array(' ', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_FILE_END, '', 1))->getMessage()),
            array('div, ', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_FILE_END, '', 5))->getMessage()),
            array(' , div', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, ',', 1))->getMessage()),
            array('p, , div', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, ',', 3))->getMessage()),
            array('div > ', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_FILE_END, '', 6))->getMessage()),
            array('  > div', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '>', 2))->getMessage()),
            array('foo|#bar', SyntaxErrorException::unexpectedToken('identifier or "*"', new Token(Token::TYPE_HASH, 'bar', 4))->getMessage()),
            array('#.foo', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '#', 0))->getMessage()),
            array('.#foo', SyntaxErrorException::unexpectedToken('identifier', new Token(Token::TYPE_HASH, 'foo', 1))->getMessage()),
            array(':#foo', SyntaxErrorException::unexpectedToken('identifier', new Token(Token::TYPE_HASH, 'foo', 1))->getMessage()),
            array('[*]', SyntaxErrorException::unexpectedToken('"|"', new Token(Token::TYPE_DELIMITER, ']', 2))->getMessage()),
            array('[foo|]', SyntaxErrorException::unexpectedToken('identifier', new Token(Token::TYPE_DELIMITER, ']', 5))->getMessage()),
            array('[#]', SyntaxErrorException::unexpectedToken('identifier or "*"', new Token(Token::TYPE_DELIMITER, '#', 1))->getMessage()),
            array('[foo=#]', SyntaxErrorException::unexpectedToken('string or identifier', new Token(Token::TYPE_DELIMITER, '#', 5))->getMessage()),
            array(':nth-child()', SyntaxErrorException::unexpectedToken('at least one argument', new Token(Token::TYPE_DELIMITER, ')', 11))->getMessage()),
            array('[href]a', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_IDENTIFIER, 'a', 6))->getMessage()),
            array('[rel:stylesheet]', SyntaxErrorException::unexpectedToken('operator', new Token(Token::TYPE_DELIMITER, ':', 4))->getMessage()),
            array('[rel=stylesheet', SyntaxErrorException::unexpectedToken('"]"', new Token(Token::TYPE_FILE_END, '', 15))->getMessage()),
            array(':lang(fr', SyntaxErrorException::unexpectedToken('an argument', new Token(Token::TYPE_FILE_END, '', 8))->getMessage()),
            array(':contains("foo', SyntaxErrorException::unclosedString(10)->getMessage()),
            array('foo!', SyntaxErrorException::unexpectedToken('selector', new Token(Token::TYPE_DELIMITER, '!', 3))->getMessage()),
        );
    }

    public function getPseudoElementsTestData()
    {
        return array(
            array('foo', 'Element[foo]', ''),
            array('*', 'Element[*]', ''),
            array(':empty', 'Pseudo[Element[*]:empty]', ''),
            array(':BEfore', 'Element[*]', 'before'),
            array(':aftER', 'Element[*]', 'after'),
            array(':First-Line', 'Element[*]', 'first-line'),
            array(':First-Letter', 'Element[*]', 'first-letter'),
            array('::befoRE', 'Element[*]', 'before'),
            array('::AFter', 'Element[*]', 'after'),
            array('::firsT-linE', 'Element[*]', 'first-line'),
            array('::firsT-letteR', 'Element[*]', 'first-letter'),
            array('::Selection', 'Element[*]', 'selection'),
            array('foo:after', 'Element[foo]', 'after'),
            array('foo::selection', 'Element[foo]', 'selection'),
            array('lorem#ipsum ~ a#b.c[href]:empty::selection', 'CombinedSelector[Hash[Element[lorem]#ipsum] ~ Pseudo[Attribute[Class[Hash[Element[a]#b].c][href]]:empty]]', 'selection'),
        );
    }

    public function getSpecificityTestData()
    {
        return array(
            array('*', 0),
            array(' foo', 1),
            array(':empty ', 10),
            array(':before', 1),
            array('*:before', 1),
            array(':nth-child(2)', 10),
            array('.bar', 10),
            array('[baz]', 10),
            array('[baz="4"]', 10),
            array('[baz^="4"]', 10),
            array('#lipsum', 100),
            array(':not(*)', 0),
            array(':not(foo)', 1),
            array(':not(.foo)', 10),
            array(':not([foo])', 10),
            array(':not(:empty)', 10),
            array(':not(#foo)', 100),
            array('foo:empty', 11),
            array('foo:before', 2),
            array('foo::before', 2),
            array('foo:empty::before', 12),
            array('#lorem + foo#ipsum:first-child > bar:first-line', 213),
        );
    }

    public function getParseSeriesTestData()
    {
        return array(
            array('1n+3', 1, 3),
            array('1n +3', 1, 3),
            array('1n + 3', 1, 3),
            array('1n+ 3', 1, 3),
            array('1n-3', 1, -3),
            array('1n -3', 1, -3),
            array('1n - 3', 1, -3),
            array('1n- 3', 1, -3),
            array('n-5', 1, -5),
            array('odd', 2, 1),
            array('even', 2, 0),
            array('3n', 3, 0),
            array('n', 1, 0),
            array('+n', 1, 0),
            array('-n', -1, 0),
            array('5', 0, 5),
        );
    }

    public function getParseSeriesExceptionTestData()
    {
        return array(
            array('foo'),
            array('n+'),
        );
    }
}
PKB1[+��̭�TCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/NumberHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\NumberHandler;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns;

class NumberHandlerTest extends AbstractHandlerTest
{
    public function getHandleValueTestData()
    {
        return array(
            array('12', new Token(Token::TYPE_NUMBER, '12', 0), ''),
            array('12.34', new Token(Token::TYPE_NUMBER, '12.34', 0), ''),
            array('+12.34', new Token(Token::TYPE_NUMBER, '+12.34', 0), ''),
            array('-12.34', new Token(Token::TYPE_NUMBER, '-12.34', 0), ''),

            array('12 arg', new Token(Token::TYPE_NUMBER, '12', 0), ' arg'),
            array('12]', new Token(Token::TYPE_NUMBER, '12', 0), ']'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('hello'),
            array('>'),
            array('+'),
            array(' '),
            array('/* comment */'),
        );
    }

    protected function generateHandler()
    {
        $patterns = new TokenizerPatterns();

        return new NumberHandler($patterns);
    }
}
PKB1[��˶XCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/IdentifierHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\IdentifierHandler;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping;

class IdentifierHandlerTest extends AbstractHandlerTest
{
    public function getHandleValueTestData()
    {
        return array(
            array('foo', new Token(Token::TYPE_IDENTIFIER, 'foo', 0), ''),
            array('foo|bar', new Token(Token::TYPE_IDENTIFIER, 'foo', 0), '|bar'),
            array('foo.class', new Token(Token::TYPE_IDENTIFIER, 'foo', 0), '.class'),
            array('foo[attr]', new Token(Token::TYPE_IDENTIFIER, 'foo', 0), '[attr]'),
            array('foo bar', new Token(Token::TYPE_IDENTIFIER, 'foo', 0), ' bar'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('>'),
            array('+'),
            array(' '),
            array('*|foo'),
            array('/* comment */'),
        );
    }

    protected function generateHandler()
    {
        $patterns = new TokenizerPatterns();

        return new IdentifierHandler($patterns, new TokenizerEscaping($patterns));
    }
}
PKB1[��_/RRUCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/CommentHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\CommentHandler;
use Symfony\Component\CssSelector\Parser\Reader;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\TokenStream;

class CommentHandlerTest extends AbstractHandlerTest
{
    /** @dataProvider getHandleValueTestData */
    public function testHandleValue($value, Token $unusedArgument, $remainingContent)
    {
        $reader = new Reader($value);
        $stream = new TokenStream();

        $this->assertTrue($this->generateHandler()->handle($reader, $stream));
        // comments are ignored (not pushed as token in stream)
        $this->assertStreamEmpty($stream);
        $this->assertRemainingContent($reader, $remainingContent);
    }

    public function getHandleValueTestData()
    {
        return array(
            // 2nd argument only exists for inherited method compatibility
            array('/* comment */', new Token(null, null, null), ''),
            array('/* comment */foo', new Token(null, null, null), 'foo'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('>'),
            array('+'),
            array(' '),
        );
    }

    protected function generateHandler()
    {
        return new CommentHandler();
    }
}
PKB1[Ĉ���VCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/AbstractHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Reader;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\TokenStream;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
abstract class AbstractHandlerTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getHandleValueTestData */
    public function testHandleValue($value, Token $expectedToken, $remainingContent)
    {
        $reader = new Reader($value);
        $stream = new TokenStream();

        $this->assertTrue($this->generateHandler()->handle($reader, $stream));
        $this->assertEquals($expectedToken, $stream->getNext());
        $this->assertRemainingContent($reader, $remainingContent);
    }

    /** @dataProvider getDontHandleValueTestData */
    public function testDontHandleValue($value)
    {
        $reader = new Reader($value);
        $stream = new TokenStream();

        $this->assertFalse($this->generateHandler()->handle($reader, $stream));
        $this->assertStreamEmpty($stream);
        $this->assertRemainingContent($reader, $value);
    }

    abstract public function getHandleValueTestData();
    abstract public function getDontHandleValueTestData();
    abstract protected function generateHandler();

    protected function assertStreamEmpty(TokenStream $stream)
    {
        $property = new \ReflectionProperty($stream, 'tokens');
        $property->setAccessible(true);

        $this->assertEquals(array(), $property->getValue($stream));
    }

    protected function assertRemainingContent(Reader $reader, $remainingContent)
    {
        if ('' === $remainingContent) {
            $this->assertEquals(0, $reader->getRemainingLength());
            $this->assertTrue($reader->isEOF());
        } else {
            $this->assertEquals(strlen($remainingContent), $reader->getRemainingLength());
            $this->assertEquals(0, $reader->getOffset($remainingContent));
        }
    }
}
PKB1[ ���XCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/WhitespaceHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\WhitespaceHandler;
use Symfony\Component\CssSelector\Parser\Token;

class WhitespaceHandlerTest extends AbstractHandlerTest
{
    public function getHandleValueTestData()
    {
        return array(
            array(' ', new Token(Token::TYPE_WHITESPACE, ' ', 0), ''),
            array("\n", new Token(Token::TYPE_WHITESPACE, "\n", 0), ''),
            array("\t", new Token(Token::TYPE_WHITESPACE, "\t", 0), ''),

            array(' foo', new Token(Token::TYPE_WHITESPACE, ' ', 0), 'foo'),
            array(' .foo', new Token(Token::TYPE_WHITESPACE, ' ', 0), '.foo'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('>'),
            array('1'),
            array('a'),
        );
    }

    protected function generateHandler()
    {
        return new WhitespaceHandler();
    }
}
PKB1[�쓱��TCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/StringHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\StringHandler;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping;

class StringHandlerTest extends AbstractHandlerTest
{
    public function getHandleValueTestData()
    {
        return array(
            array('"hello"', new Token(Token::TYPE_STRING, 'hello', 1), ''),
            array('"1"', new Token(Token::TYPE_STRING, '1', 1), ''),
            array('" "', new Token(Token::TYPE_STRING, ' ', 1), ''),
            array('""', new Token(Token::TYPE_STRING, '', 1), ''),
            array("'hello'", new Token(Token::TYPE_STRING, 'hello', 1), ''),

            array("'foo'bar", new Token(Token::TYPE_STRING, 'foo', 1), 'bar'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('hello'),
            array('>'),
            array('1'),
            array(' '),
        );
    }

    protected function generateHandler()
    {
        $patterns = new TokenizerPatterns();

        return new StringHandler($patterns, new TokenizerEscaping($patterns));
    }
}
PKB1[C�U�rrRCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/HashHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser\Handler;

use Symfony\Component\CssSelector\Parser\Handler\HashHandler;
use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerPatterns;
use Symfony\Component\CssSelector\Parser\Tokenizer\TokenizerEscaping;

class HashHandlerTest extends AbstractHandlerTest
{
    public function getHandleValueTestData()
    {
        return array(
            array('#id', new Token(Token::TYPE_HASH, 'id', 0), ''),
            array('#123', new Token(Token::TYPE_HASH, '123', 0), ''),

            array('#id.class', new Token(Token::TYPE_HASH, 'id', 0), '.class'),
            array('#id element', new Token(Token::TYPE_HASH, 'id', 0), ' element'),
        );
    }

    public function getDontHandleValueTestData()
    {
        return array(
            array('id'),
            array('123'),
            array('<'),
            array('<'),
            array('#'),
        );
    }

    protected function generateHandler()
    {
        $patterns = new TokenizerPatterns();

        return new HashHandler($patterns, new TokenizerEscaping($patterns));
    }
}
PKB1[%9�j~~ECssSelector/Symfony/Component/CssSelector/Tests/Parser/ReaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser;

use Symfony\Component\CssSelector\Parser\Reader;

class ReaderTest extends \PHPUnit_Framework_TestCase
{
    public function testIsEOF()
    {
        $reader = new Reader('');
        $this->assertTrue($reader->isEOF());

        $reader = new Reader('hello');
        $this->assertFalse($reader->isEOF());

        $this->assignPosition($reader, 2);
        $this->assertFalse($reader->isEOF());

        $this->assignPosition($reader, 5);
        $this->assertTrue($reader->isEOF());
    }

    public function testGetRemainingLength()
    {
        $reader = new Reader('hello');
        $this->assertEquals(5, $reader->getRemainingLength());

        $this->assignPosition($reader, 2);
        $this->assertEquals(3, $reader->getRemainingLength());

        $this->assignPosition($reader, 5);
        $this->assertEquals(0, $reader->getRemainingLength());
    }

    public function testGetSubstring()
    {
        $reader = new Reader('hello');
        $this->assertEquals('he', $reader->getSubstring(2));
        $this->assertEquals('el', $reader->getSubstring(2, 1));

        $this->assignPosition($reader, 2);
        $this->assertEquals('ll', $reader->getSubstring(2));
        $this->assertEquals('lo', $reader->getSubstring(2, 1));
    }

    public function testGetOffset()
    {
        $reader = new Reader('hello');
        $this->assertEquals(2, $reader->getOffset('ll'));
        $this->assertFalse($reader->getOffset('w'));

        $this->assignPosition($reader, 2);
        $this->assertEquals(0, $reader->getOffset('ll'));
        $this->assertFalse($reader->getOffset('he'));
    }

    public function testFindPattern()
    {
        $reader = new Reader('hello');

        $this->assertFalse($reader->findPattern('/world/'));
        $this->assertEquals(array('hello', 'h'), $reader->findPattern('/^([a-z]).*/'));

        $this->assignPosition($reader, 2);
        $this->assertFalse($reader->findPattern('/^h.*/'));
        $this->assertEquals(array('llo'), $reader->findPattern('/^llo$/'));
    }

    public function testMoveForward()
    {
        $reader = new Reader('hello');
        $this->assertEquals(0, $reader->getPosition());

        $reader->moveForward(2);
        $this->assertEquals(2, $reader->getPosition());
    }

    public function testToEnd()
    {
        $reader = new Reader('hello');
        $reader->moveToEnd();
        $this->assertTrue($reader->isEOF());
    }

    private function assignPosition(Reader $reader, $value)
    {
        $position = new \ReflectionProperty($reader, 'position');
        $position->setAccessible(true);
        $position->setValue($reader, $value);
    }
}
PKB1[�}��qqJCssSelector/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\CssSelector\Tests\Parser;

use Symfony\Component\CssSelector\Parser\Token;
use Symfony\Component\CssSelector\Parser\TokenStream;

class TokenStreamTest extends \PHPUnit_Framework_TestCase
{
    public function testGetNext()
    {
        $stream = new TokenStream();
        $stream->push($t1 = new Token(Token::TYPE_IDENTIFIER, 'h1', 0));
        $stream->push($t2 = new Token(Token::TYPE_DELIMITER, '.', 2));
        $stream->push($t3 = new Token(Token::TYPE_IDENTIFIER, 'title', 3));

        $this->assertSame($t1, $stream->getNext());
        $this->assertSame($t2, $stream->getNext());
        $this->assertSame($t3, $stream->getNext());
    }

    public function testGetPeek()
    {
        $stream = new TokenStream();
        $stream->push($t1 = new Token(Token::TYPE_IDENTIFIER, 'h1', 0));
        $stream->push($t2 = new Token(Token::TYPE_DELIMITER, '.', 2));
        $stream->push($t3 = new Token(Token::TYPE_IDENTIFIER, 'title', 3));

        $this->assertSame($t1, $stream->getPeek());
        $this->assertSame($t1, $stream->getNext());
        $this->assertSame($t2, $stream->getPeek());
        $this->assertSame($t2, $stream->getPeek());
        $this->assertSame($t2, $stream->getNext());
    }

    public function testGetNextIdentifier()
    {
        $stream = new TokenStream();
        $stream->push(new Token(Token::TYPE_IDENTIFIER, 'h1', 0));

        $this->assertEquals('h1', $stream->getNextIdentifier());
    }

    public function testFailToGetNextIdentifier()
    {
        $this->setExpectedException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');

        $stream = new TokenStream();
        $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2));
        $stream->getNextIdentifier();
    }

    public function testGetNextIdentifierOrStar()
    {
        $stream = new TokenStream();

        $stream->push(new Token(Token::TYPE_IDENTIFIER, 'h1', 0));
        $this->assertEquals('h1', $stream->getNextIdentifierOrStar());

        $stream->push(new Token(Token::TYPE_DELIMITER, '*', 0));
        $this->assertNull($stream->getNextIdentifierOrStar());
    }

    public function testFailToGetNextIdentifierOrStar()
    {
        $this->setExpectedException('Symfony\Component\CssSelector\Exception\SyntaxErrorException');

        $stream = new TokenStream();
        $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2));
        $stream->getNextIdentifierOrStar();
    }

    public function testSkipWhitespace()
    {
        $stream = new TokenStream();
        $stream->push($t1 = new Token(Token::TYPE_IDENTIFIER, 'h1', 0));
        $stream->push($t2 = new Token(Token::TYPE_WHITESPACE, ' ', 2));
        $stream->push($t3 = new Token(Token::TYPE_IDENTIFIER, 'h1', 3));

        $stream->skipWhitespace();
        $this->assertSame($t1, $stream->getNext());

        $stream->skipWhitespace();
        $this->assertSame($t3, $stream->getNext());
    }
}
PKC1[���Hmm:CssSelector/Symfony/Component/CssSelector/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony CssSelector Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKC1[�X,�/�/OEventDispatcher/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class EventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    /* Some pseudo events */
    const preFoo = 'pre.foo';
    const postFoo = 'post.foo';
    const preBar = 'pre.bar';
    const postBar = 'post.bar';

    /**
     * @var EventDispatcher
     */
    private $dispatcher;

    private $listener;

    protected function setUp()
    {
        $this->dispatcher = new EventDispatcher();
        $this->listener = new TestEventListener();
    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->listener = null;
    }

    public function testInitialState()
    {
        $this->assertEquals(array(), $this->dispatcher->getListeners());
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
        $this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testAddListener()
    {
        $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'));
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
        $this->assertCount(1, $this->dispatcher->getListeners(self::preFoo));
        $this->assertCount(1, $this->dispatcher->getListeners(self::postFoo));
        $this->assertCount(2, $this->dispatcher->getListeners());
    }

    public function testGetListenersSortsByPriority()
    {
        $listener1 = new TestEventListener();
        $listener2 = new TestEventListener();
        $listener3 = new TestEventListener();
        $listener1->name = '1';
        $listener2->name = '2';
        $listener3->name = '3';

        $this->dispatcher->addListener('pre.foo', array($listener1, 'preFoo'), -10);
        $this->dispatcher->addListener('pre.foo', array($listener2, 'preFoo'), 10);
        $this->dispatcher->addListener('pre.foo', array($listener3, 'preFoo'));

        $expected = array(
            array($listener2, 'preFoo'),
            array($listener3, 'preFoo'),
            array($listener1, 'preFoo'),
        );

        $this->assertSame($expected, $this->dispatcher->getListeners('pre.foo'));
    }

    public function testGetAllListenersSortsByPriority()
    {
        $listener1 = new TestEventListener();
        $listener2 = new TestEventListener();
        $listener3 = new TestEventListener();
        $listener4 = new TestEventListener();
        $listener5 = new TestEventListener();
        $listener6 = new TestEventListener();

        $this->dispatcher->addListener('pre.foo', $listener1, -10);
        $this->dispatcher->addListener('pre.foo', $listener2);
        $this->dispatcher->addListener('pre.foo', $listener3, 10);
        $this->dispatcher->addListener('post.foo', $listener4, -10);
        $this->dispatcher->addListener('post.foo', $listener5);
        $this->dispatcher->addListener('post.foo', $listener6, 10);

        $expected = array(
            'pre.foo'  => array($listener3, $listener2, $listener1),
            'post.foo' => array($listener6, $listener5, $listener4),
        );

        $this->assertSame($expected, $this->dispatcher->getListeners());
    }

    public function testDispatch()
    {
        $this->dispatcher->addListener('pre.foo', array($this->listener, 'preFoo'));
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'));
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertTrue($this->listener->preFooInvoked);
        $this->assertFalse($this->listener->postFooInvoked);
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch('noevent'));
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Event', $this->dispatcher->dispatch(self::preFoo));
        $event = new Event();
        $return = $this->dispatcher->dispatch(self::preFoo, $event);
        $this->assertEquals('pre.foo', $event->getName());
        $this->assertSame($event, $return);
    }

    public function testDispatchForClosure()
    {
        $invoked = 0;
        $listener = function () use (&$invoked) {
            $invoked++;
        };
        $this->dispatcher->addListener('pre.foo', $listener);
        $this->dispatcher->addListener('post.foo', $listener);
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertEquals(1, $invoked);
    }

    public function testStopEventPropagation()
    {
        $otherListener = new TestEventListener();

        // postFoo() stops the propagation, so only one listener should
        // be executed
        // Manually set priority to enforce $this->listener to be called first
        $this->dispatcher->addListener('post.foo', array($this->listener, 'postFoo'), 10);
        $this->dispatcher->addListener('post.foo', array($otherListener, 'preFoo'));
        $this->dispatcher->dispatch(self::postFoo);
        $this->assertTrue($this->listener->postFooInvoked);
        $this->assertFalse($otherListener->postFooInvoked);
    }

    public function testDispatchByPriority()
    {
        $invoked = array();
        $listener1 = function () use (&$invoked) {
            $invoked[] = '1';
        };
        $listener2 = function () use (&$invoked) {
            $invoked[] = '2';
        };
        $listener3 = function () use (&$invoked) {
            $invoked[] = '3';
        };
        $this->dispatcher->addListener('pre.foo', $listener1, -10);
        $this->dispatcher->addListener('pre.foo', $listener2);
        $this->dispatcher->addListener('pre.foo', $listener3, 10);
        $this->dispatcher->dispatch(self::preFoo);
        $this->assertEquals(array('3', '2', '1'), $invoked);
    }

    public function testRemoveListener()
    {
        $this->dispatcher->addListener('pre.bar', $this->listener);
        $this->assertTrue($this->dispatcher->hasListeners(self::preBar));
        $this->dispatcher->removeListener('pre.bar', $this->listener);
        $this->assertFalse($this->dispatcher->hasListeners(self::preBar));
        $this->dispatcher->removeListener('notExists', $this->listener);
    }

    public function testAddSubscriber()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testAddSubscriberWithPriorities()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $eventSubscriber = new TestEventSubscriberWithPriorities();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $listeners = $this->dispatcher->getListeners('pre.foo');
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $listeners);
        $this->assertInstanceOf('Symfony\Component\EventDispatcher\Tests\TestEventSubscriberWithPriorities', $listeners[0][0]);
    }

    public function testAddSubscriberWithMultipleListeners()
    {
        $eventSubscriber = new TestEventSubscriberWithMultipleListeners();
        $this->dispatcher->addSubscriber($eventSubscriber);

        $listeners = $this->dispatcher->getListeners('pre.foo');
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $listeners);
        $this->assertEquals('preFoo2', $listeners[0][1]);
    }

    public function testRemoveSubscriber()
    {
        $eventSubscriber = new TestEventSubscriber();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertTrue($this->dispatcher->hasListeners(self::postFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
        $this->assertFalse($this->dispatcher->hasListeners(self::postFoo));
    }

    public function testRemoveSubscriberWithPriorities()
    {
        $eventSubscriber = new TestEventSubscriberWithPriorities();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
    }

    public function testRemoveSubscriberWithMultipleListeners()
    {
        $eventSubscriber = new TestEventSubscriberWithMultipleListeners();
        $this->dispatcher->addSubscriber($eventSubscriber);
        $this->assertTrue($this->dispatcher->hasListeners(self::preFoo));
        $this->assertCount(2, $this->dispatcher->getListeners(self::preFoo));
        $this->dispatcher->removeSubscriber($eventSubscriber);
        $this->assertFalse($this->dispatcher->hasListeners(self::preFoo));
    }

    public function testEventReceivesTheDispatcherInstance()
    {
        $dispatcher = null;
        $this->dispatcher->addListener('test', function ($event) use (&$dispatcher) {
            $dispatcher = $event->getDispatcher();
        });
        $this->dispatcher->dispatch('test');
        $this->assertSame($this->dispatcher, $dispatcher);
    }

    public function testEventReceivesTheDispatcherInstanceAsArgument()
    {
        $listener = new TestWithDispatcher();
        $this->dispatcher->addListener('test', array($listener, 'foo'));
        $this->assertNull($listener->name);
        $this->assertNull($listener->dispatcher);
        $this->dispatcher->dispatch('test');
        $this->assertEquals('test', $listener->name);
        $this->assertSame($this->dispatcher, $listener->dispatcher);
    }

    /**
     * @see https://bugs.php.net/bug.php?id=62976
     *
     * This bug affects:
     *  - The PHP 5.3 branch for versions < 5.3.18
     *  - The PHP 5.4 branch for versions < 5.4.8
     *  - The PHP 5.5 branch is not affected
     */
    public function testWorkaroundForPhpBug62976()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener('bug.62976', new CallableClass());
        $dispatcher->removeListener('bug.62976', function () {});
        $this->assertTrue($dispatcher->hasListeners('bug.62976'));
    }
}

class CallableClass
{
    public function __invoke()
    {
    }
}

class TestEventListener
{
    public $preFooInvoked = false;
    public $postFooInvoked = false;

    /* Listener methods */

    public function preFoo(Event $e)
    {
        $this->preFooInvoked = true;
    }

    public function postFoo(Event $e)
    {
        $this->postFooInvoked = true;

        $e->stopPropagation();
    }
}

class TestWithDispatcher
{
    public $name;
    public $dispatcher;

    public function foo(Event $e, $name, $dispatcher)
    {
        $this->name = $name;
        $this->dispatcher = $dispatcher;
    }
}

class TestEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('pre.foo' => 'preFoo', 'post.foo' => 'postFoo');
    }
}

class TestEventSubscriberWithPriorities implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'pre.foo' => array('preFoo', 10),
            'post.foo' => array('postFoo'),
            );
    }
}

class TestEventSubscriberWithMultipleListeners implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('pre.foo' => array(
            array('preFoo1'),
            array('preFoo2', 10)
        ));
    }
}
PKC1[���aaXEventDispatcher/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\ImmutableEventDispatcher;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class ImmutableEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $innerDispatcher;

    /**
     * @var ImmutableEventDispatcher
     */
    private $dispatcher;

    protected function setUp()
    {
        $this->innerDispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $this->dispatcher = new ImmutableEventDispatcher($this->innerDispatcher);
    }

    public function testDispatchDelegates()
    {
        $event = new Event();

        $this->innerDispatcher->expects($this->once())
            ->method('dispatch')
            ->with('event', $event)
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->dispatch('event', $event));
    }

    public function testGetListenersDelegates()
    {
        $this->innerDispatcher->expects($this->once())
            ->method('getListeners')
            ->with('event')
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->getListeners('event'));
    }

    public function testHasListenersDelegates()
    {
        $this->innerDispatcher->expects($this->once())
            ->method('hasListeners')
            ->with('event')
            ->will($this->returnValue('result'));

        $this->assertSame('result', $this->dispatcher->hasListeners('event'));
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testAddListenerDisallowed()
    {
        $this->dispatcher->addListener('event', function () { return 'foo'; });
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testAddSubscriberDisallowed()
    {
        $subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface');

        $this->dispatcher->addSubscriber($subscriber);
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testRemoveListenerDisallowed()
    {
        $this->dispatcher->removeListener('event', function () { return 'foo'; });
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testRemoveSubscriberDisallowed()
    {
        $subscriber = $this->getMock('Symfony\Component\EventDispatcher\EventSubscriberInterface');

        $this->dispatcher->removeSubscriber($subscriber);
    }
}
PKC1[YQ_AA]EventDispatcher/Symfony/Component/EventDispatcher/Tests/ContainerAwareEventDispatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ContainerAwareEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    public function testAddAListenerService()
    {
        $event = new Event();

        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->dispatch('onEvent', $event);
    }

    public function testAddASubscriberService()
    {
        $event = new Event();

        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\SubscriberService');

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.subscriber', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addSubscriberService('service.subscriber', 'Symfony\Component\EventDispatcher\Tests\SubscriberService');

        $dispatcher->dispatch('onEvent', $event);
    }

    public function testPreventDuplicateListenerService()
    {
        $event = new Event();

        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 5);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'), 10);

        $dispatcher->dispatch('onEvent', $event);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testTriggerAListenerServiceOutOfScope()
    {
        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $scope = new Scope('scope');
        $container = new Container();
        $container->addScope($scope);
        $container->enterScope('scope');

        $container->set('service.listener', $service, 'scope');

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $container->leaveScope('scope');
        $dispatcher->dispatch('onEvent');
    }

    public function testReEnteringAScope()
    {
        $event = new Event();

        $service1 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $service1
            ->expects($this->exactly(2))
            ->method('onEvent')
            ->with($event)
        ;

        $scope = new Scope('scope');
        $container = new Container();
        $container->addScope($scope);
        $container->enterScope('scope');

        $container->set('service.listener', $service1, 'scope');

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));
        $dispatcher->dispatch('onEvent', $event);

        $service2 = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $service2
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $container->enterScope('scope');
        $container->set('service.listener', $service2, 'scope');

        $dispatcher->dispatch('onEvent', $event);

        $container->leaveScope('scope');

        $dispatcher->dispatch('onEvent');
    }

    public function testHasListenersOnLazyLoad()
    {
        $event = new Event();

        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $event->setDispatcher($dispatcher);
        $event->setName('onEvent');

        $service
            ->expects($this->once())
            ->method('onEvent')
            ->with($event)
        ;

        $this->assertTrue($dispatcher->hasListeners());

        if ($dispatcher->hasListeners('onEvent')) {
            $dispatcher->dispatch('onEvent');
        }
    }

    public function testGetListenersOnLazyLoad()
    {
        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $listeners = $dispatcher->getListeners();

        $this->assertTrue(isset($listeners['onEvent']));

        $this->assertCount(1, $dispatcher->getListeners('onEvent'));
    }

    public function testRemoveAfterDispatch()
    {
        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->dispatch('onEvent', new Event());
        $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent'));
        $this->assertFalse($dispatcher->hasListeners('onEvent'));
    }

    public function testRemoveBeforeDispatch()
    {
        $service = $this->getMock('Symfony\Component\EventDispatcher\Tests\Service');

        $container = new Container();
        $container->set('service.listener', $service);

        $dispatcher = new ContainerAwareEventDispatcher($container);
        $dispatcher->addListenerService('onEvent', array('service.listener', 'onEvent'));

        $dispatcher->removeListener('onEvent', array($container->get('service.listener'), 'onEvent'));
        $this->assertFalse($dispatcher->hasListeners('onEvent'));
    }
}

class Service
{
    public function onEvent(Event $e)
    {
    }
}

class SubscriberService implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'onEvent' => 'onEvent',
            'onEvent' => array('onEvent', 10),
            'onEvent' => array('onEvent'),
        );
    }

    public function onEvent(Event $e)
    {
    }
}
PKC1[��nuEEventDispatcher/Symfony/Component/EventDispatcher/Tests/EventTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 * Test class for Event.
 */
class EventTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Symfony\Component\EventDispatcher\Event
     */
    protected $event;

    /**
     * @var \Symfony\Component\EventDispatcher\EventDispatcher
     */
    protected $dispatcher;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->event = new Event();
        $this->dispatcher = new EventDispatcher();
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown()
    {
        $this->event = null;
        $this->dispatcher = null;
    }

    public function testIsPropagationStopped()
    {
        $this->assertFalse($this->event->isPropagationStopped());
    }

    public function testStopPropagationAndIsPropagationStopped()
    {
        $this->event->stopPropagation();
        $this->assertTrue($this->event->isPropagationStopped());
    }

    public function testSetDispatcher()
    {
        $this->event->setDispatcher($this->dispatcher);
        $this->assertSame($this->dispatcher, $this->event->getDispatcher());
    }

    public function testGetDispatcher()
    {
        $this->assertNull($this->event->getDispatcher());
    }

    public function testGetName()
    {
        $this->assertNull($this->event->getName());
    }

    public function testSetName()
    {
        $this->event->setName('foo');
        $this->assertEquals('foo', $this->event->getName());
    }
}
PKC1[\2��
�
LEventDispatcher/Symfony/Component/EventDispatcher/Tests/GenericEventTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\EventDispatcher\Tests;

use Symfony\Component\EventDispatcher\GenericEvent;

/**
 * Test class for Event.
 */
class GenericEventTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var GenericEvent
     */
    private $event;

    private $subject;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp()
    {
        parent::setUp();

        $this->subject = new \stdClass();
        $this->event = new GenericEvent($this->subject, array('name' => 'Event'), 'foo');
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown()
    {
        $this->subject = null;
        $this->event = null;

        parent::tearDown();
    }

    public function testConstruct()
    {
        $this->assertEquals($this->event, new GenericEvent($this->subject, array('name' => 'Event')));
    }

    /**
     * Tests Event->getArgs()
     */
    public function testGetArguments()
    {
        // test getting all
        $this->assertSame(array('name' => 'Event'), $this->event->getArguments());
    }

    public function testSetArguments()
    {
        $result = $this->event->setArguments(array('foo' => 'bar'));
        $this->assertAttributeSame(array('foo' => 'bar'), 'arguments', $this->event);
        $this->assertSame($this->event, $result);
    }

    public function testSetArgument()
    {
        $result = $this->event->setArgument('foo2', 'bar2');
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
        $this->assertEquals($this->event, $result);
    }

    public function testGetArgument()
    {
        // test getting key
        $this->assertEquals('Event', $this->event->getArgument('name'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetArgException()
    {
        $this->event->getArgument('nameNotExist');
    }

    public function testOffsetGet()
    {
        // test getting key
        $this->assertEquals('Event', $this->event['name']);

        // test getting invalid arg
        $this->setExpectedException('InvalidArgumentException');
        $this->assertFalse($this->event['nameNotExist']);
    }

    public function testOffsetSet()
    {
        $this->event['foo2'] = 'bar2';
        $this->assertAttributeSame(array('name' => 'Event', 'foo2' => 'bar2'), 'arguments', $this->event);
    }

    public function testOffsetUnset()
    {
        unset($this->event['name']);
        $this->assertAttributeSame(array(), 'arguments', $this->event);
    }

    public function testOffsetIsset()
    {
        $this->assertTrue(isset($this->event['name']));
        $this->assertFalse(isset($this->event['nameNotExist']));
    }

    public function testHasArgument()
    {
        $this->assertTrue($this->event->hasArgument('name'));
        $this->assertFalse($this->event->hasArgument('nameNotExist'));
    }

    public function testGetSubject()
    {
        $this->assertSame($this->subject, $this->event->getSubject());
    }

    public function testHasIterator()
    {
        $data = array();
        foreach ($this->event as $key => $value) {
            $data[$key] = $value;
        }
        $this->assertEquals(array('name' => 'Event'), $data);
    }
}
PKC1[�MqqBEventDispatcher/Symfony/Component/EventDispatcher/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony EventDispatcher Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKC1[��C	C	CConsole/Symfony/Component/Console/Tests/Command/ListCommandTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Command;

use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Application;

class ListCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testExecuteListsCommands()
    {
        $application = new Application();
        $commandTester = new CommandTester($command = $application->get('list'));
        $commandTester->execute(array('command' => $command->getName()), array('decorated' => false));

        $this->assertRegExp('/help   Displays help for a command/', $commandTester->getDisplay(), '->execute() returns a list of available commands');
    }

    public function testExecuteListsCommandsWithXmlOption()
    {
        $application = new Application();
        $commandTester = new CommandTester($command = $application->get('list'));
        $commandTester->execute(array('command' => $command->getName(), '--format' => 'xml'));
        $this->assertRegExp('/<command id="list" name="list">/', $commandTester->getDisplay(), '->execute() returns a list of available commands in XML if --xml is passed');
    }

    public function testExecuteListsCommandsWithRawOption()
    {
        $application = new Application();
        $commandTester = new CommandTester($command = $application->get('list'));
        $commandTester->execute(array('command' => $command->getName(), '--raw' => true));
        $output = <<<EOF
help   Displays help for a command
list   Lists commands

EOF;

        $this->assertEquals($output, $commandTester->getDisplay(true));
    }

    public function testExecuteListsCommandsWithNamespaceArgument()
    {

        require_once(realpath(__DIR__.'/../Fixtures/FooCommand.php'));
        $application = new Application();
        $application->add(new \FooCommand());
        $commandTester = new CommandTester($command = $application->get('list'));
        $commandTester->execute(array('command' => $command->getName(), 'namespace' => 'foo', '--raw' => true));
        $output = <<<EOF
foo:bar   The foo:bar command

EOF;

        $this->assertEquals($output, $commandTester->getDisplay(true));
    }
}
PKC1[o�"�Z9Z9?Console/Symfony/Component/Console/Tests/Command/CommandTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Tester\CommandTester;

class CommandTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = __DIR__.'/../Fixtures/';
        require_once self::$fixturesPath.'/TestCommand.php';
    }

    public function testConstructor()
    {
        $command = new Command('foo:bar');
        $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage The command name cannot be empty.
     */
    public function testCommandNameCannotBeEmpty()
    {
        new Command();
    }

    public function testSetApplication()
    {
        $application = new Application();
        $command = new \TestCommand();
        $command->setApplication($application);
        $this->assertEquals($application, $command->getApplication(), '->setApplication() sets the current application');
    }

    public function testSetGetDefinition()
    {
        $command = new \TestCommand();
        $ret = $command->setDefinition($definition = new InputDefinition());
        $this->assertEquals($command, $ret, '->setDefinition() implements a fluent interface');
        $this->assertEquals($definition, $command->getDefinition(), '->setDefinition() sets the current InputDefinition instance');
        $command->setDefinition(array(new InputArgument('foo'), new InputOption('bar')));
        $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
        $this->assertTrue($command->getDefinition()->hasOption('bar'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
        $command->setDefinition(new InputDefinition());
    }

    public function testAddArgument()
    {
        $command = new \TestCommand();
        $ret = $command->addArgument('foo');
        $this->assertEquals($command, $ret, '->addArgument() implements a fluent interface');
        $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->addArgument() adds an argument to the command');
    }

    public function testAddOption()
    {
        $command = new \TestCommand();
        $ret = $command->addOption('foo');
        $this->assertEquals($command, $ret, '->addOption() implements a fluent interface');
        $this->assertTrue($command->getDefinition()->hasOption('foo'), '->addOption() adds an option to the command');
    }

    public function testGetNamespaceGetNameSetName()
    {
        $command = new \TestCommand();
        $this->assertEquals('namespace:name', $command->getName(), '->getName() returns the command name');
        $command->setName('foo');
        $this->assertEquals('foo', $command->getName(), '->setName() sets the command name');

        $ret = $command->setName('foobar:bar');
        $this->assertEquals($command, $ret, '->setName() implements a fluent interface');
        $this->assertEquals('foobar:bar', $command->getName(), '->setName() sets the command name');
    }

    /**
     * @dataProvider provideInvalidCommandNames
     */
    public function testInvalidCommandNames($name)
    {
        $this->setExpectedException('InvalidArgumentException', sprintf('Command name "%s" is invalid.', $name));

        $command = new \TestCommand();
        $command->setName($name);
    }

    public function provideInvalidCommandNames()
    {
        return array(
            array(''),
            array('foo:')
        );
    }

    public function testGetSetDescription()
    {
        $command = new \TestCommand();
        $this->assertEquals('description', $command->getDescription(), '->getDescription() returns the description');
        $ret = $command->setDescription('description1');
        $this->assertEquals($command, $ret, '->setDescription() implements a fluent interface');
        $this->assertEquals('description1', $command->getDescription(), '->setDescription() sets the description');
    }

    public function testGetSetHelp()
    {
        $command = new \TestCommand();
        $this->assertEquals('help', $command->getHelp(), '->getHelp() returns the help');
        $ret = $command->setHelp('help1');
        $this->assertEquals($command, $ret, '->setHelp() implements a fluent interface');
        $this->assertEquals('help1', $command->getHelp(), '->setHelp() sets the help');
    }

    public function testGetProcessedHelp()
    {
        $command = new \TestCommand();
        $command->setHelp('The %command.name% command does... Example: php %command.full_name%.');
        $this->assertContains('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly');
        $this->assertNotContains('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name%');
    }

    public function testGetSetAliases()
    {
        $command = new \TestCommand();
        $this->assertEquals(array('name'), $command->getAliases(), '->getAliases() returns the aliases');
        $ret = $command->setAliases(array('name1'));
        $this->assertEquals($command, $ret, '->setAliases() implements a fluent interface');
        $this->assertEquals(array('name1'), $command->getAliases(), '->setAliases() sets the aliases');
    }

    public function testGetSynopsis()
    {
        $command = new \TestCommand();
        $command->addOption('foo');
        $command->addArgument('foo');
        $this->assertEquals('namespace:name [--foo] [foo]', $command->getSynopsis(), '->getSynopsis() returns the synopsis');
    }

    public function testGetHelper()
    {
        $application = new Application();
        $command = new \TestCommand();
        $command->setApplication($application);
        $formatterHelper = new FormatterHelper();
        $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->getHelper() returns the correct helper');
    }

    public function testGet()
    {
        $application = new Application();
        $command = new \TestCommand();
        $command->setApplication($application);
        $formatterHelper = new FormatterHelper();
        $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->__get() returns the correct helper');
    }

    public function testMergeApplicationDefinition()
    {
        $application1 = new Application();
        $application1->getDefinition()->addArguments(array(new InputArgument('foo')));
        $application1->getDefinition()->addOptions(array(new InputOption('bar')));
        $command = new \TestCommand();
        $command->setApplication($application1);
        $command->setDefinition($definition = new InputDefinition(array(new InputArgument('bar'), new InputOption('foo'))));

        $r = new \ReflectionObject($command);
        $m = $r->getMethod('mergeApplicationDefinition');
        $m->setAccessible(true);
        $m->invoke($command);
        $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
        $this->assertTrue($command->getDefinition()->hasArgument('bar'), '->mergeApplicationDefinition() merges the application arguments and the command arguments');
        $this->assertTrue($command->getDefinition()->hasOption('foo'), '->mergeApplicationDefinition() merges the application options and the command options');
        $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition() merges the application options and the command options');

        $m->invoke($command);
        $this->assertEquals(3, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments and options');
    }

    public function testMergeApplicationDefinitionWithoutArgsThenWithArgsAddsArgs()
    {
        $application1 = new Application();
        $application1->getDefinition()->addArguments(array(new InputArgument('foo')));
        $application1->getDefinition()->addOptions(array(new InputOption('bar')));
        $command = new \TestCommand();
        $command->setApplication($application1);
        $command->setDefinition($definition = new InputDefinition(array()));

        $r = new \ReflectionObject($command);
        $m = $r->getMethod('mergeApplicationDefinition');
        $m->setAccessible(true);
        $m->invoke($command, false);
        $this->assertTrue($command->getDefinition()->hasOption('bar'), '->mergeApplicationDefinition(false) merges the application and the commmand options');
        $this->assertFalse($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(false) does not merge the application arguments');

        $m->invoke($command, true);
        $this->assertTrue($command->getDefinition()->hasArgument('foo'), '->mergeApplicationDefinition(true) merges the application arguments and the command arguments');

        $m->invoke($command);
        $this->assertEquals(2, $command->getDefinition()->getArgumentCount(), '->mergeApplicationDefinition() does not try to merge twice the application arguments');
    }

    public function testRunInteractive()
    {
        $tester = new CommandTester(new \TestCommand());

        $tester->execute(array(), array('interactive' => true));

        $this->assertEquals('interact called'.PHP_EOL.'execute called'.PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive');
    }

    public function testRunNonInteractive()
    {
        $tester = new CommandTester(new \TestCommand());

        $tester->execute(array(), array('interactive' => false));

        $this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage You must override the execute() method in the concrete command class.
     */
    public function testExecuteMethodNeedsToBeOverriden()
    {
        $command = new Command('foo');
        $command->run(new StringInput(''), new NullOutput());
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "--bar" option does not exist.
     */
    public function testRunWithInvalidOption()
    {
        $command = new \TestCommand();
        $tester = new CommandTester($command);
        $tester->execute(array('--bar' => true));
    }

    public function testRunReturnsIntegerExitCode()
    {
        $command = new \TestCommand();
        $exitCode = $command->run(new StringInput(''), new NullOutput());
        $this->assertSame(0, $exitCode, '->run() returns integer exit code (treats null as 0)');

        $command = $this->getMock('TestCommand', array('execute'));
        $command->expects($this->once())
             ->method('execute')
             ->will($this->returnValue('2.3'));
        $exitCode = $command->run(new StringInput(''), new NullOutput());
        $this->assertSame(2, $exitCode, '->run() returns integer exit code (casts numeric to int)');
    }

    public function testRunReturnsAlwaysInteger()
    {
        $command = new \TestCommand();

        $this->assertSame(0, $command->run(new StringInput(''), new NullOutput()));
    }

    public function testSetCode()
    {
        $command = new \TestCommand();
        $ret = $command->setCode(function (InputInterface $input, OutputInterface $output) {
            $output->writeln('from the code...');
        });
        $this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
        $tester = new CommandTester($command);
        $tester->execute(array());
        $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
    }

    public function testSetCodeWithNonClosureCallable()
    {
        $command = new \TestCommand();
        $ret = $command->setCode(array($this, 'callableMethodCommand'));
        $this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
        $tester = new CommandTester($command);
        $tester->execute(array());
        $this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage Invalid callable provided to Command::setCode.
     */
    public function testSetCodeWithNonCallable()
    {
        $command = new \TestCommand();
        $command->setCode(array($this, 'nonExistentMethod'));
    }

    public function callableMethodCommand(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('from the code...');
    }

    public function testAsText()
    {
        $command = new \TestCommand();
        $command->setApplication(new Application());
        $tester = new CommandTester($command);
        $tester->execute(array('command' => $command->getName()));
        $this->assertStringEqualsFile(self::$fixturesPath.'/command_astext.txt', $command->asText(), '->asText() returns a text representation of the command');
    }

    public function testAsXml()
    {
        $command = new \TestCommand();
        $command->setApplication(new Application());
        $tester = new CommandTester($command);
        $tester->execute(array('command' => $command->getName()));
        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/command_asxml.txt', $command->asXml(), '->asXml() returns an XML representation of the command');
    }
}
PKC1[b�y�11CConsole/Symfony/Component/Console/Tests/Command/HelpCommandTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Command;

use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Console\Command\HelpCommand;
use Symfony\Component\Console\Command\ListCommand;
use Symfony\Component\Console\Application;

class HelpCommandTest extends \PHPUnit_Framework_TestCase
{
    public function testExecuteForCommandAlias()
    {
        $command = new HelpCommand();
        $command->setApplication(new Application());
        $commandTester = new CommandTester($command);
        $commandTester->execute(array('command_name' => 'li'));
        $this->assertRegExp('/list \[--xml\] \[--raw\] \[--format="\.\.\."\] \[namespace\]/', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias');
    }

    public function testExecuteForCommand()
    {
        $command = new HelpCommand();
        $commandTester = new CommandTester($command);
        $command->setCommand(new ListCommand());
        $commandTester->execute(array());
        $this->assertRegExp('/list \[--xml\] \[--raw\] \[--format="\.\.\."\] \[namespace\]/', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
    }

    public function testExecuteForCommandWithXmlOption()
    {
        $command = new HelpCommand();
        $commandTester = new CommandTester($command);
        $command->setCommand(new ListCommand());
        $commandTester->execute(array('--format' => 'xml'));
        $this->assertRegExp('/<command/', $commandTester->getDisplay(), '->execute() returns an XML help text if --xml is passed');
    }

    public function testExecuteForApplicationCommand()
    {
        $application = new Application();
        $commandTester = new CommandTester($application->get('help'));
        $commandTester->execute(array('command_name' => 'list'));
        $this->assertRegExp('/list \[--xml\] \[--raw\] \[--format="\.\.\."\] \[namespace\]/', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
    }

    public function testExecuteForApplicationCommandWithXmlOption()
    {
        $application = new Application();
        $commandTester = new CommandTester($application->get('help'));
        $commandTester->execute(array('command_name' => 'list', '--format' => 'xml'));
        $this->assertRegExp('/list \[--xml\] \[--raw\] \[--format="\.\.\."\] \[namespace\]/', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
        $this->assertRegExp('/<command/', $commandTester->getDisplay(), '->execute() returns an XML help text if --format=xml is passed');
    }
}
PKC1[u��d��HConsole/Symfony/Component/Console/Tests/Fixtures/application_astext1.txtnu�[���<info>Console Tool</info>

<comment>Usage:</comment>
  [options] command [arguments]

<comment>Options:</comment>
  <info>--help</info>           <info>-h</info> Display this help message.
  <info>--quiet</info>          <info>-q</info> Do not output any message.
  <info>--verbose</info>        <info>-v|vv|vvv</info> Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  <info>--version</info>        <info>-V</info> Display this application version.
  <info>--ansi</info>              Force ANSI output.
  <info>--no-ansi</info>           Disable ANSI output.
  <info>--no-interaction</info> <info>-n</info> Do not ask any interactive question.

<comment>Available commands:</comment>
  <info>afoobar  </info> The foo:bar command
  <info>help     </info> Displays help for a command
  <info>list     </info> Lists commands
<comment>foo</comment>
  <info>foo:bar  </info> The foo:bar command
PKC1[��c��BConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.mdnu�[���**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: yes
* Is value required: yes
* Is multiple: no
* Description: option description
* Default: `NULL`
PKC1[���ooFConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.jsonnu�[���{"name":"argument_name","is_required":false,"is_array":true,"description":"argument description","default":[]}
PKC1[��f���EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<argument name="argument_name" is_required="0" is_array="1">
  <description>argument description</description>
  <defaults/>
</argument>
PKC1[9y�X��=Console/Symfony/Component/Console/Tests/Fixtures/command_1.mdnu�[���descriptor:command1
-------------------

* Description: command 1 description
* Usage: `descriptor:command1`
* Aliases: `alias1`, `alias2`

command 1 help
PKC1[�S��BConsole/Symfony/Component/Console/Tests/Fixtures/command_asxml.txtnu�[���<?xml version="1.0" encoding="UTF-8"?>
<command id="namespace:name" name="namespace:name">
  <usage>namespace:name</usage>
  <description>description</description>
  <help>help</help>
  <aliases>
    <alias>name</alias>
  </aliases>
  <arguments>
    <argument name="command" is_required="1" is_array="0">
      <description>The command to execute</description>
      <defaults/>
    </argument>
  </arguments>
  <options>
    <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Display this help message.</description>
    </option>
    <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Do not output any message.</description>
    </option>
    <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
    </option>
    <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Display this application version.</description>
    </option>
    <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Force ANSI output.</description>
    </option>
    <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Disable ANSI output.</description>
    </option>
    <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Do not ask any interactive question.</description>
    </option>
  </options>
</command>
PKC1[�^t�^^GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<definition>
  <arguments/>
  <options/>
</definition>
PKC1[P����BConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.mdnu�[���**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: yes
* Is value required: no
* Is multiple: yes
* Description: option description
* Default: `array ()`
PKC1[���BConsole/Symfony/Component/Console/Tests/Fixtures/BarBucCommand.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;

class BarBucCommand extends Command
{
    protected function configure()
    {
        $this->setName('bar:buc');
    }
}
PKC1[W'��GConsole/Symfony/Component/Console/Tests/Fixtures/application_asxml2.txtnu�[���<?xml version="1.0" encoding="UTF-8"?>
<symfony>
  <commands namespace="foo">
    <command id="foo:bar" name="foo:bar">
  <usage>foo:bar</usage>
  <description>The foo:bar command</description>
  <help/>
  <aliases>
    <alias>afoobar</alias>
  </aliases>
  <arguments/>
    <options>
      <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Display this help message.</description>
      </option>
      <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Do not output any message.</description>
      </option>
      <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
      </option>
      <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Display this application version.</description>
      </option>
      <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Force ANSI output.</description>
      </option>
      <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Disable ANSI output.</description>
      </option>
      <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Do not ask any interactive question.</description>
      </option>
    </options>
</command>
  </commands>
</symfony>
PKC1[&���QConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception1.txtnu�[���

                                 
  [InvalidArgumentException]     
  Command "foo" is not defined.  
                                 


PKC1[��XX��CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<option name="--option_name" shortcut="-o" accept_value="1" is_value_required="1" is_multiple="0">
  <description>option description</description>
  <defaults/>
</option>
PKC1[��G��CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<option name="--option_name" shortcut="-o" accept_value="0" is_value_required="0" is_multiple="0">
  <description></description>
</option>
PKC1[Y'�A��GConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand1.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Fixtures;

use Symfony\Component\Console\Command\Command;

class DescriptorCommand1 extends Command
{
    protected function configure()
    {
        $this
            ->setName('descriptor:command1')
            ->setAliases(array('alias1', 'alias2'))
            ->setDescription('command 1 description')
            ->setHelp('command 1 help')
        ;
    }
}
PKC1[CQu��GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<definition>
  <arguments>
    <argument name="argument_name" is_required="1" is_array="0">
      <description></description>
      <defaults/>
    </argument>
  </arguments>
  <options>
    <option name="--option_name" shortcut="-o" accept_value="0" is_value_required="0" is_multiple="0">
      <description></description>
    </option>
  </options>
</definition>
PKC1[�!�"��EConsole/Symfony/Component/Console/Tests/Fixtures/application_run3.txtnu�[���Usage:
 list [--xml] [--raw] [--format="..."] [namespace]

Arguments:
 namespace  The namespace name

Options:
 --xml      To output list as XML
 --raw      To output raw command list
 --format   To output list in other formats (default: "txt")

Help:
 The list command lists all commands:
 
   php app/console list
 
 You can also display the commands for a specific namespace:
 
   php app/console list test
 
 You can also output the information in other formats by using the --format option:
 
   php app/console list --format=xml
 
 It's also possible to get raw list of commands (useful for embedding command runner):
 
   php app/console list --raw
PKC1[�e�d��@Console/Symfony/Component/Console/Tests/Fixtures/Foo4Command.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;

class Foo4Command extends Command
{
    protected function configure()
    {
        $this->setName('foo3:bar:toh');
    }
}
PKC1[z�Ռ��DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.mdnu�[���**argument_name:**

* Name: argument_name
* Is required: no
* Is array: yes
* Description: argument description
* Default: `array ()`
PKC1[�t;�aaCConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.txtnu�[��� <info>--option_name</info> (-o) option description<comment> (multiple values allowed)</comment>
PKC1[ a���DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.jsonnu�[���{"name":"--option_name","shortcut":"-o","accept_value":true,"is_value_required":false,"is_multiple":true,"description":"option description","default":[]}
PKC1[�F:cGConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<definition>
  <arguments/>
  <options>
    <option name="--option_name" shortcut="-o" accept_value="0" is_value_required="0" is_multiple="0">
      <description></description>
    </option>
  </options>
</definition>
PKC1[oY���CConsole/Symfony/Component/Console/Tests/Fixtures/application_1.jsonnu�[���{"commands":[{"name":"help","usage":"help [--xml] [--format=\"...\"] [--raw] [command_name]","description":"Displays help for a command","help":"The <info>help<\/info> command displays help for a given command:\n\n  <info>php app\/console help list<\/info>\n\nYou can also output the help in other formats by using the <comment>--format<\/comment> option:\n\n  <info>php app\/console help --format=xml list<\/info>\n\nTo display the list of available commands, please use the <info>list<\/info> command.","aliases":[],"definition":{"arguments":{"command_name":{"name":"command_name","is_required":false,"is_array":false,"description":"The command name","default":"help"}},"options":{"xml":{"name":"--xml","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output help as XML","default":false},"format":{"name":"--format","shortcut":"","accept_value":true,"is_value_required":true,"is_multiple":false,"description":"To output help in other formats","default":"txt"},"raw":{"name":"--raw","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output raw command help","default":false},"help":{"name":"--help","shortcut":"-h","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this help message.","default":false},"quiet":{"name":"--quiet","shortcut":"-q","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not output any message.","default":false},"verbose":{"name":"--verbose","shortcut":"-v|-vv|-vvv","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug","default":false},"version":{"name":"--version","shortcut":"-V","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this application version.","default":false},"ansi":{"name":"--ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Force ANSI output.","default":false},"no-ansi":{"name":"--no-ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Disable ANSI output.","default":false},"no-interaction":{"name":"--no-interaction","shortcut":"-n","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not ask any interactive question.","default":false}}}},{"name":"list","usage":"list [--xml] [--raw] [--format=\"...\"] [namespace]","description":"Lists commands","help":"The <info>list<\/info> command lists all commands:\n\n  <info>php app\/console list<\/info>\n\nYou can also display the commands for a specific namespace:\n\n  <info>php app\/console list test<\/info>\n\nYou can also output the information in other formats by using the <comment>--format<\/comment> option:\n\n  <info>php app\/console list --format=xml<\/info>\n\nIt's also possible to get raw list of commands (useful for embedding command runner):\n\n  <info>php app\/console list --raw<\/info>","aliases":[],"definition":{"arguments":{"namespace":{"name":"namespace","is_required":false,"is_array":false,"description":"The namespace name","default":null}},"options":{"xml":{"name":"--xml","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output list as XML","default":false},"raw":{"name":"--raw","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output raw command list","default":false},"format":{"name":"--format","shortcut":"","accept_value":true,"is_value_required":true,"is_multiple":false,"description":"To output list in other formats","default":"txt"}}}}],"namespaces":[{"id":"_global","commands":["help","list"]}]}
PKC1[#��"��?Console/Symfony/Component/Console/Tests/Fixtures/command_2.jsonnu�[���{"name":"descriptor:command2","usage":"descriptor:command2 [-o|--option_name] argument_name","description":"command 2 description","help":"command 2 help","aliases":[],"definition":{"arguments":{"argument_name":{"name":"argument_name","is_required":true,"is_array":false,"description":"","default":null}},"options":{"option_name":{"name":"--option_name","shortcut":"-o","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"","default":false}}}}
PKC1[9�*A��@Console/Symfony/Component/Console/Tests/Fixtures/TestCommand.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class TestCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('namespace:name')
            ->setAliases(array('name'))
            ->setDescription('description')
            ->setHelp('help')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('execute called');
    }

    protected function interact(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('interact called');
    }
}
PKD1[�'�̒�>Console/Symfony/Component/Console/Tests/Fixtures/command_1.txtnu�[���<comment>Usage:</comment>
 descriptor:command1

<comment>Aliases:</comment> <info>alias1, alias2</info>

<comment>Help:</comment>
 command 1 help
PKD1[<|�4UU@Console/Symfony/Component/Console/Tests/Fixtures/Foo1Command.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Foo1Command extends Command
{
    public $input;
    public $output;

    protected function configure()
    {
        $this
            ->setName('foo:bar1')
            ->setDescription('The foo:bar1 command')
            ->setAliases(array('afoobar1'))
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
    }
}
PKD1[GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.txtnu�[���PKD1[��<]]FConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.jsonnu�[���{"name":"argument_name","is_required":true,"is_array":false,"description":"","default":null}
PKD1[۴�2��DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.jsonnu�[���{"name":"--option_name","shortcut":"-o","accept_value":true,"is_value_required":false,"is_multiple":false,"description":"option description","default":"default_value"}
PKD1[�q+��KConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication1.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Fixtures;

use Symfony\Component\Console\Application;

class DescriptorApplication1 extends Application
{
}
PKD1[��[���FConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.mdnu�[���### Arguments:

**argument_name:**

* Name: argument_name
* Is required: yes
* Is array: no
* Description: <none>
* Default: `NULL`
PKD1[��#��AConsole/Symfony/Component/Console/Tests/Fixtures/application_2.mdnu�[���My Symfony application
======================

* alias1
* alias2
* help
* list

**descriptor:**

* descriptor:command1
* descriptor:command2

help
----

* Description: Displays help for a command
* Usage: `help [--xml] [--format="..."] [--raw] [command_name]`
* Aliases: <none>

The <info>help</info> command displays help for a given command:

  <info>php app/console help list</info>

You can also output the help in other formats by using the <comment>--format</comment> option:

  <info>php app/console help --format=xml list</info>

To display the list of available commands, please use the <info>list</info> command.

### Arguments:

**command_name:**

* Name: command_name
* Is required: no
* Is array: no
* Description: The command name
* Default: `'help'`

### Options:

**xml:**

* Name: `--xml`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output help as XML
* Default: `false`

**format:**

* Name: `--format`
* Shortcut: <none>
* Accept value: yes
* Is value required: yes
* Is multiple: no
* Description: To output help in other formats
* Default: `'txt'`

**raw:**

* Name: `--raw`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output raw command help
* Default: `false`

**help:**

* Name: `--help`
* Shortcut: `-h`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this help message.
* Default: `false`

**quiet:**

* Name: `--quiet`
* Shortcut: `-q`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not output any message.
* Default: `false`

**verbose:**

* Name: `--verbose`
* Shortcut: `-v|-vv|-vvv`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
* Default: `false`

**version:**

* Name: `--version`
* Shortcut: `-V`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this application version.
* Default: `false`

**ansi:**

* Name: `--ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Force ANSI output.
* Default: `false`

**no-ansi:**

* Name: `--no-ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Disable ANSI output.
* Default: `false`

**no-interaction:**

* Name: `--no-interaction`
* Shortcut: `-n`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not ask any interactive question.
* Default: `false`

list
----

* Description: Lists commands
* Usage: `list [--xml] [--raw] [--format="..."] [namespace]`
* Aliases: <none>

The <info>list</info> command lists all commands:

  <info>php app/console list</info>

You can also display the commands for a specific namespace:

  <info>php app/console list test</info>

You can also output the information in other formats by using the <comment>--format</comment> option:

  <info>php app/console list --format=xml</info>

It's also possible to get raw list of commands (useful for embedding command runner):

  <info>php app/console list --raw</info>

### Arguments:

**namespace:**

* Name: namespace
* Is required: no
* Is array: no
* Description: The namespace name
* Default: `NULL`

### Options:

**xml:**

* Name: `--xml`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output list as XML
* Default: `false`

**raw:**

* Name: `--raw`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output raw command list
* Default: `false`

**format:**

* Name: `--format`
* Shortcut: <none>
* Accept value: yes
* Is value required: yes
* Is multiple: no
* Description: To output list in other formats
* Default: `'txt'`

descriptor:command1
-------------------

* Description: command 1 description
* Usage: `descriptor:command1`
* Aliases: `alias1`, `alias2`

command 1 help

### Options:

**help:**

* Name: `--help`
* Shortcut: `-h`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this help message.
* Default: `false`

**quiet:**

* Name: `--quiet`
* Shortcut: `-q`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not output any message.
* Default: `false`

**verbose:**

* Name: `--verbose`
* Shortcut: `-v|-vv|-vvv`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
* Default: `false`

**version:**

* Name: `--version`
* Shortcut: `-V`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this application version.
* Default: `false`

**ansi:**

* Name: `--ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Force ANSI output.
* Default: `false`

**no-ansi:**

* Name: `--no-ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Disable ANSI output.
* Default: `false`

**no-interaction:**

* Name: `--no-interaction`
* Shortcut: `-n`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not ask any interactive question.
* Default: `false`

descriptor:command2
-------------------

* Description: command 2 description
* Usage: `descriptor:command2 [-o|--option_name] argument_name`
* Aliases: <none>

command 2 help

### Arguments:

**argument_name:**

* Name: argument_name
* Is required: yes
* Is array: no
* Description: <none>
* Default: `NULL`

### Options:

**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: <none>
* Default: `false`

**help:**

* Name: `--help`
* Shortcut: `-h`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this help message.
* Default: `false`

**quiet:**

* Name: `--quiet`
* Shortcut: `-q`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not output any message.
* Default: `false`

**verbose:**

* Name: `--verbose`
* Shortcut: `-v|-vv|-vvv`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
* Default: `false`

**version:**

* Name: `--version`
* Shortcut: `-V`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this application version.
* Default: `false`

**ansi:**

* Name: `--ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Force ANSI output.
* Default: `false`

**no-ansi:**

* Name: `--no-ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Disable ANSI output.
* Default: `false`

**no-interaction:**

* Name: `--no-interaction`
* Shortcut: `-n`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not ask any interactive question.
* Default: `false`
PKD1[��$$HConsole/Symfony/Component/Console/Tests/Fixtures/application_astext2.txtnu�[���<info>Console Tool</info>

<comment>Usage:</comment>
  [options] command [arguments]

<comment>Options:</comment>
  <info>--help</info>           <info>-h</info> Display this help message.
  <info>--quiet</info>          <info>-q</info> Do not output any message.
  <info>--verbose</info>        <info>-v|vv|vvv</info> Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  <info>--version</info>        <info>-V</info> Display this application version.
  <info>--ansi</info>              Force ANSI output.
  <info>--no-ansi</info>           Disable ANSI output.
  <info>--no-interaction</info> <info>-n</info> Do not ask any interactive question.

<comment>Available commands for the "foo" namespace:</comment>
  <info>foo:bar  </info> The foo:bar command
PKD1[g��/11EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.txtnu�[��� <info>argument_name</info> argument description
PKD1[[��%��?Console/Symfony/Component/Console/Tests/Fixtures/command_1.jsonnu�[���{"name":"descriptor:command1","usage":"descriptor:command1","description":"command 1 description","help":"command 1 help","aliases":["alias1","alias2"],"definition":{"arguments":[],"options":[]}}
PKD1[�Z�o��AConsole/Symfony/Component/Console/Tests/Fixtures/application_1.mdnu�[���UNKNOWN
=======

* help
* list

help
----

* Description: Displays help for a command
* Usage: `help [--xml] [--format="..."] [--raw] [command_name]`
* Aliases: <none>

The <info>help</info> command displays help for a given command:

  <info>php app/console help list</info>

You can also output the help in other formats by using the <comment>--format</comment> option:

  <info>php app/console help --format=xml list</info>

To display the list of available commands, please use the <info>list</info> command.

### Arguments:

**command_name:**

* Name: command_name
* Is required: no
* Is array: no
* Description: The command name
* Default: `'help'`

### Options:

**xml:**

* Name: `--xml`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output help as XML
* Default: `false`

**format:**

* Name: `--format`
* Shortcut: <none>
* Accept value: yes
* Is value required: yes
* Is multiple: no
* Description: To output help in other formats
* Default: `'txt'`

**raw:**

* Name: `--raw`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output raw command help
* Default: `false`

**help:**

* Name: `--help`
* Shortcut: `-h`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this help message.
* Default: `false`

**quiet:**

* Name: `--quiet`
* Shortcut: `-q`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not output any message.
* Default: `false`

**verbose:**

* Name: `--verbose`
* Shortcut: `-v|-vv|-vvv`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
* Default: `false`

**version:**

* Name: `--version`
* Shortcut: `-V`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Display this application version.
* Default: `false`

**ansi:**

* Name: `--ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Force ANSI output.
* Default: `false`

**no-ansi:**

* Name: `--no-ansi`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Disable ANSI output.
* Default: `false`

**no-interaction:**

* Name: `--no-interaction`
* Shortcut: `-n`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: Do not ask any interactive question.
* Default: `false`

list
----

* Description: Lists commands
* Usage: `list [--xml] [--raw] [--format="..."] [namespace]`
* Aliases: <none>

The <info>list</info> command lists all commands:

  <info>php app/console list</info>

You can also display the commands for a specific namespace:

  <info>php app/console list test</info>

You can also output the information in other formats by using the <comment>--format</comment> option:

  <info>php app/console list --format=xml</info>

It's also possible to get raw list of commands (useful for embedding command runner):

  <info>php app/console list --raw</info>

### Arguments:

**namespace:**

* Name: namespace
* Is required: no
* Is array: no
* Description: The namespace name
* Default: `NULL`

### Options:

**xml:**

* Name: `--xml`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output list as XML
* Default: `false`

**raw:**

* Name: `--raw`
* Shortcut: <none>
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: To output raw command list
* Default: `false`

**format:**

* Name: `--format`
* Shortcut: <none>
* Accept value: yes
* Is value required: yes
* Is multiple: no
* Description: To output list in other formats
* Default: `'txt'`
PKD1[ia����EConsole/Symfony/Component/Console/Tests/Fixtures/definition_asxml.txtnu�[���<?xml version="1.0" encoding="UTF-8"?>
<definition>
  <arguments>
    <argument name="foo" is_required="0" is_array="0">
      <description>The foo argument</description>
      <defaults/>
    </argument>
    <argument name="baz" is_required="0" is_array="0">
      <description>The baz argument</description>
      <defaults>
        <default>true</default>
      </defaults>
    </argument>
    <argument name="bar" is_required="0" is_array="1">
      <description>The bar argument</description>
      <defaults>
        <default>bar</default>
      </defaults>
    </argument>
  </arguments>
  <options>
    <option name="--foo" shortcut="-f" accept_value="1" is_value_required="1" is_multiple="0">
      <description>The foo option</description>
      <defaults/>
    </option>
    <option name="--baz" shortcut="" accept_value="1" is_value_required="0" is_multiple="0">
      <description>The baz option</description>
      <defaults>
        <default>false</default>
      </defaults>
    </option>
    <option name="--bar" shortcut="-b" accept_value="1" is_value_required="0" is_multiple="0">
      <description>The bar option</description>
      <defaults>
        <default>bar</default>
      </defaults>
    </option>
  </options>
</definition>
PKD1[�_�n��EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<argument name="argument_name" is_required="1" is_array="0">
  <description></description>
  <defaults/>
</argument>
PKD1[�: 8��EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<argument name="argument_name" is_required="0" is_array="0">
  <description>argument description</description>
  <defaults>
    <default>default_value</default>
  </defaults>
</argument>
PKD1[��-��ZConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception3decorated.txtnu�[���

                           
  [Exception]              
  Third exception comment  
                           




                            
  [Exception]               
  Second exception comment  
                            




                                       
  [Exception]                          
  First exception <p>this is html</p>  
                                       


foo3:bar


PKD1[�@�]"]"BConsole/Symfony/Component/Console/Tests/Fixtures/application_2.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<symfony name="My Symfony application" version="v1.0">
  <commands>
    <command id="help" name="help">
      <usage>help [--xml] [--format="..."] [--raw] [command_name]</usage>
      <description>Displays help for a command</description>
      <help>The &lt;info&gt;help&lt;/info&gt; command displays help for a given command:
 
   &lt;info&gt;php app/console help list&lt;/info&gt;
 
 You can also output the help in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console help --format=xml list&lt;/info&gt;
 
 To display the list of available commands, please use the &lt;info&gt;list&lt;/info&gt; command.</help>
      <aliases/>
      <arguments>
        <argument name="command_name" is_required="0" is_array="0">
          <description>The command name</description>
          <defaults>
            <default>help</default>
          </defaults>
        </argument>
      </arguments>
      <options>
        <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output help as XML</description>
        </option>
        <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
          <description>To output help in other formats</description>
          <defaults>
            <default>txt</default>
          </defaults>
        </option>
        <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output raw command help</description>
        </option>
        <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this help message.</description>
        </option>
        <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not output any message.</description>
        </option>
        <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
        </option>
        <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this application version.</description>
        </option>
        <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Force ANSI output.</description>
        </option>
        <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Disable ANSI output.</description>
        </option>
        <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not ask any interactive question.</description>
        </option>
      </options>
    </command>
    <command id="list" name="list">
      <usage>list [--xml] [--raw] [--format="..."] [namespace]</usage>
      <description>Lists commands</description>
      <help>The &lt;info&gt;list&lt;/info&gt; command lists all commands:
 
   &lt;info&gt;php app/console list&lt;/info&gt;
 
 You can also display the commands for a specific namespace:
 
   &lt;info&gt;php app/console list test&lt;/info&gt;
 
 You can also output the information in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console list --format=xml&lt;/info&gt;
 
 It's also possible to get raw list of commands (useful for embedding command runner):
 
   &lt;info&gt;php app/console list --raw&lt;/info&gt;</help>
      <aliases/>
      <arguments>
        <argument name="namespace" is_required="0" is_array="0">
          <description>The namespace name</description>
          <defaults/>
        </argument>
      </arguments>
      <options>
        <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output list as XML</description>
        </option>
        <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output raw command list</description>
        </option>
        <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
          <description>To output list in other formats</description>
          <defaults>
            <default>txt</default>
          </defaults>
        </option>
      </options>
    </command>
    <command id="descriptor:command1" name="descriptor:command1">
      <usage>descriptor:command1</usage>
      <description>command 1 description</description>
      <help>command 1 help</help>
      <aliases>
        <alias>alias1</alias>
        <alias>alias2</alias>
      </aliases>
      <arguments/>
      <options>
        <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this help message.</description>
        </option>
        <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not output any message.</description>
        </option>
        <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
        </option>
        <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this application version.</description>
        </option>
        <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Force ANSI output.</description>
        </option>
        <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Disable ANSI output.</description>
        </option>
        <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not ask any interactive question.</description>
        </option>
      </options>
    </command>
    <command id="descriptor:command2" name="descriptor:command2">
      <usage>descriptor:command2 [-o|--option_name] argument_name</usage>
      <description>command 2 description</description>
      <help>command 2 help</help>
      <aliases/>
      <arguments>
        <argument name="argument_name" is_required="1" is_array="0">
          <description></description>
          <defaults/>
        </argument>
      </arguments>
      <options>
        <option name="--option_name" shortcut="-o" accept_value="0" is_value_required="0" is_multiple="0">
          <description></description>
        </option>
        <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this help message.</description>
        </option>
        <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not output any message.</description>
        </option>
        <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
        </option>
        <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this application version.</description>
        </option>
        <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Force ANSI output.</description>
        </option>
        <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Disable ANSI output.</description>
        </option>
        <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not ask any interactive question.</description>
        </option>
      </options>
    </command>
  </commands>
  <namespaces>
    <namespace id="_global">
      <command>alias1</command>
      <command>alias2</command>
      <command>help</command>
      <command>list</command>
    </namespace>
    <namespace id="descriptor">
      <command>descriptor:command1</command>
      <command>descriptor:command2</command>
    </namespace>
  </namespaces>
</symfony>
PKD1[�K@�bbCConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.txtnu�[��� <info>--option_name</info> (-o) option description<comment> (default: "default_value")</comment>
PKD1[p�����FConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.mdnu�[���### Options:

**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: <none>
* Default: `false`
PKD1[�A�(ff>Console/Symfony/Component/Console/Tests/Fixtures/command_2.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<command id="descriptor:command2" name="descriptor:command2">
  <usage>descriptor:command2 [-o|--option_name] argument_name</usage>
  <description>command 2 description</description>
  <help>command 2 help</help>
  <aliases/>
  <arguments>
    <argument name="argument_name" is_required="1" is_array="0">
      <description></description>
      <defaults/>
    </argument>
  </arguments>
  <options>
    <option name="--option_name" shortcut="-o" accept_value="0" is_value_required="0" is_multiple="0">
      <description></description>
    </option>
  </options>
</command>
PKD1[��,���FConsole/Symfony/Component/Console/Tests/Fixtures/definition_astext.txtnu�[���<comment>Arguments:</comment>
 <info>foo       </info> The foo argument
 <info>baz       </info> The baz argument<comment> (default: true)</comment>
 <info>bar       </info> The bar argument<comment> (default: ["http://foo.com/"])</comment>

<comment>Options:</comment>
 <info>--foo</info> (-f) The foo option
 <info>--baz</info>      The baz option<comment> (default: false)</comment>
 <info>--bar</info> (-b) The bar option<comment> (default: "bar")</comment>
 <info>--qux</info>      The qux option<comment> (default: ["http://foo.com/","bar"])</comment><comment> (multiple values allowed)</comment>
 <info>--qux2</info>     The qux2 option<comment> (default: {"foo":"bar"})</comment><comment> (multiple values allowed)</comment>
PKD1[�I���CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<option name="--option_name" shortcut="-o" accept_value="1" is_value_required="0" is_multiple="1">
  <description>option description</description>
  <defaults/>
</option>
PKD1[u$´!!CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.txtnu�[��� <info>--option_name</info> (-o)
PKD1[���$$HConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.jsonnu�[���{"arguments":{"argument_name":{"name":"argument_name","is_required":true,"is_array":false,"description":"","default":null}},"options":{"option_name":{"name":"--option_name","shortcut":"-o","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"","default":false}}}
PKD1[3�P���GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<definition>
  <arguments>
    <argument name="argument_name" is_required="1" is_array="0">
      <description></description>
      <defaults/>
    </argument>
  </arguments>
  <options/>
</definition>
PKD1[Ѹ�;;GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.txtnu�[���<comment>Arguments:</comment>
 <info>argument_name </info>
PKD1[��a66BConsole/Symfony/Component/Console/Tests/Fixtures/application_1.txtnu�[���<info>Console Tool</info>

<comment>Usage:</comment>
  [options] command [arguments]

<comment>Options:</comment>
  <info>--help</info>           <info>-h</info> Display this help message.
  <info>--quiet</info>          <info>-q</info> Do not output any message.
  <info>--verbose</info>        <info>-v|vv|vvv</info> Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  <info>--version</info>        <info>-V</info> Display this application version.
  <info>--ansi</info>              Force ANSI output.
  <info>--no-ansi</info>           Disable ANSI output.
  <info>--no-interaction</info> <info>-n</info> Do not ask any interactive question.

<comment>Available commands:</comment>
  <info>help  </info> Displays help for a command
  <info>list  </info> Lists commands
PKD1[����HConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.jsonnu�[���{"arguments":[],"options":[]}
PKD1[X� �,,EConsole/Symfony/Component/Console/Tests/Fixtures/application_run2.txtnu�[���Usage:
 help [--xml] [--format="..."] [--raw] [command_name]

Arguments:
 command               The command to execute
 command_name          The command name (default: "help")

Options:
 --xml                 To output help as XML
 --format              To output help in other formats (default: "txt")
 --raw                 To output raw command help
 --help (-h)           Display this help message.
 --quiet (-q)          Do not output any message.
 --verbose (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
 --version (-V)        Display this application version.
 --ansi                Force ANSI output.
 --no-ansi             Disable ANSI output.
 --no-interaction (-n) Do not ask any interactive question.

Help:
 The help command displays help for a given command:
 
   php app/console help list
 
 You can also output the help in other formats by using the --format option:
 
   php app/console help --format=xml list
 
 To display the list of available commands, please use the list command.
PKD1[󚲱}}FConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.jsonnu�[���{"name":"argument_name","is_required":false,"is_array":false,"description":"argument description","default":"default_value"}
PKD1[1"8MMKConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication2.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Fixtures;

use Symfony\Component\Console\Application;

class DescriptorApplication2 extends Application
{
    public function __construct()
    {
        parent::__construct('My Symfony application', 'v1.0');
        $this->add(new DescriptorCommand1());
        $this->add(new DescriptorCommand2());
    }
}
PKD1[#ɤb��HConsole/Symfony/Component/Console/Tests/Fixtures/application_gethelp.txtnu�[���<info>Console Tool</info>

<comment>Usage:</comment>
  [options] command [arguments]

<comment>Options:</comment>
  <info>--help</info>           <info>-h</info> Display this help message.
  <info>--quiet</info>          <info>-q</info> Do not output any message.
  <info>--verbose</info>        <info>-v|vv|vvv</info> Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  <info>--version</info>        <info>-V</info> Display this application version.
  <info>--ansi</info>              Force ANSI output.
  <info>--no-ansi</info>           Disable ANSI output.
  <info>--no-interaction</info> <info>-n</info> Do not ask any interactive question.PKD1[�(���BConsole/Symfony/Component/Console/Tests/Fixtures/application_2.txtnu�[���<info>My Symfony application</info> version <comment>v1.0</comment>

<comment>Usage:</comment>
  [options] command [arguments]

<comment>Options:</comment>
  <info>--help</info>           <info>-h</info> Display this help message.
  <info>--quiet</info>          <info>-q</info> Do not output any message.
  <info>--verbose</info>        <info>-v|vv|vvv</info> Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  <info>--version</info>        <info>-V</info> Display this application version.
  <info>--ansi</info>              Force ANSI output.
  <info>--no-ansi</info>           Disable ANSI output.
  <info>--no-interaction</info> <info>-n</info> Do not ask any interactive question.

<comment>Available commands:</comment>
  <info>alias1               </info> command 1 description
  <info>alias2               </info> command 1 description
  <info>help                 </info> Displays help for a command
  <info>list                 </info> Lists commands
<comment>descriptor</comment>
  <info>descriptor:command1  </info> command 1 description
  <info>descriptor:command2  </info> command 2 description
PKD1[;`�MGConsole/Symfony/Component/Console/Tests/Fixtures/application_asxml1.txtnu�[���<?xml version="1.0" encoding="UTF-8"?>
<symfony>
  <commands>
    <command id="help" name="help">
  <usage>help [--xml] [--format="..."] [--raw] [command_name]</usage>
  <description>Displays help for a command</description>
  <help>The &lt;info&gt;help&lt;/info&gt; command displays help for a given command:
 
   &lt;info&gt;php app/console help list&lt;/info&gt;
 
 You can also output the help in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console help --format=xml list&lt;/info&gt;
 
 To display the list of available commands, please use the &lt;info&gt;list&lt;/info&gt; command.</help>
  <aliases />
  <arguments>
    <argument name="command_name" is_required="0" is_array="0">
      <description>The command name</description>
      <defaults>
        <default>help</default>
      </defaults>
    </argument>
  </arguments>
  <options>
    <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>To output help as XML</description>
    </option>
    <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
      <description>To output help in other formats</description>
      <defaults>
        <default>txt</default>
      </defaults>
    </option>
    <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>To output raw command help</description>
    </option>
    <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Display this help message.</description>
    </option>
    <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Do not output any message.</description>
    </option>
    <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
    </option>
    <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Display this application version.</description>
    </option>
    <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Force ANSI output.</description>
    </option>
    <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Disable ANSI output.</description>
    </option>
    <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
      <description>Do not ask any interactive question.</description>
    </option>
  </options>
</command>
    <command id="list" name="list">
  <usage>list [--xml] [--raw] [--format="..."] [namespace]</usage>
  <description>Lists commands</description>
  <help>The &lt;info&gt;list&lt;/info&gt; command lists all commands:
 
   &lt;info&gt;php app/console list&lt;/info&gt;
 
 You can also display the commands for a specific namespace:
 
   &lt;info&gt;php app/console list test&lt;/info&gt;
 
 You can also output the information in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console list --format=xml&lt;/info&gt;
 
 It's also possible to get raw list of commands (useful for embedding command runner):
 
   &lt;info&gt;php app/console list --raw&lt;/info&gt;</help>
  <aliases/>
  <arguments>
    <argument name="namespace" is_required="0" is_array="0">
      <description>The namespace name</description>
      <defaults/>
    </argument>
  </arguments>
  <options>
    <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>To output list as XML</description>
    </option>
    <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
      <description>To output raw command list</description>
    </option>
    <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
      <description>To output list in other formats</description>
      <defaults>
        <default>txt</default>
      </defaults>
    </option>
  </options>
</command>
    <command id="foo:bar" name="foo:bar">
  <usage>foo:bar</usage>
  <description>The foo:bar command</description>
  <help/>
  <aliases>
    <alias>afoobar</alias>
  </aliases>
  <arguments/>
    <options>
      <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Display this help message.</description>
      </option>
      <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Do not output any message.</description>
      </option>
      <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
      </option>
      <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Display this application version.</description>
      </option>
      <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Force ANSI output.</description>
      </option>
      <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Disable ANSI output.</description>
      </option>
      <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
        <description>Do not ask any interactive question.</description>
      </option>
    </options>
</command>
  </commands>
  <namespaces>
    <namespace id="_global">
      <command>afoobar</command>
      <command>help</command>
      <command>list</command>
    </namespace>
    <namespace id="foo">
      <command>foo:bar</command>
    </namespace>
  </namespaces>
</symfony>
PKD1[W��،�DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.mdnu�[���**argument_name:**

* Name: argument_name
* Is required: no
* Is array: no
* Description: argument description
* Default: `'default_value'`
PKD1[��X��DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.jsonnu�[���{"name":"--option_name","shortcut":"-o","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"","default":false}
PKD1[�
c�?Console/Symfony/Component/Console/Tests/Fixtures/FooCommand.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class FooCommand extends Command
{
    public $input;
    public $output;

    protected function configure()
    {
        $this
            ->setName('foo:bar')
            ->setDescription('The foo:bar command')
            ->setAliases(array('afoobar'))
        ;
    }

    protected function interact(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('interact called');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;

        $output->writeln('called');
    }
}
PKD1[G u=��QConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception3.txtnu�[���

                           
  [Exception]              
  Third exception comment  
                           




                            
  [Exception]               
  Second exception comment  
                            




                                       
  [Exception]                          
  First exception <p>this is html</p>  
                                       


foo3:bar


PKD1[FConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.mdnu�[���PKD1[���==GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.txtnu�[���<comment>Options:</comment>
 <info>--option_name</info> (-o)
PKD1[�����CConsole/Symfony/Component/Console/Tests/Fixtures/command_astext.txtnu�[���<comment>Usage:</comment>
 namespace:name

<comment>Aliases:</comment> <info>name</info>
<comment>Arguments:</comment>
 <info>command              </info> The command to execute

<comment>Options:</comment>
 <info>--help</info> (-h)           Display this help message.
 <info>--quiet</info> (-q)          Do not output any message.
 <info>--verbose</info> (-v|vv|vvv) Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
 <info>--version</info> (-V)        Display this application version.
 <info>--ansi</info>                Force ANSI output.
 <info>--no-ansi</info>             Disable ANSI output.
 <info>--no-interaction</info> (-n) Do not ask any interactive question.

<comment>Help:</comment>
 help
PKD1[�J�2CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<option name="--option_name" shortcut="-o" accept_value="1" is_value_required="0" is_multiple="0">
  <description>option description</description>
  <defaults>
    <default>default_value</default>
  </defaults>
</option>
PKD1[l�T���BConsole/Symfony/Component/Console/Tests/Fixtures/application_1.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<symfony>
  <commands>
    <command id="help" name="help">
      <usage>help [--xml] [--format="..."] [--raw] [command_name]</usage>
      <description>Displays help for a command</description>
      <help>The &lt;info&gt;help&lt;/info&gt; command displays help for a given command:
 
   &lt;info&gt;php app/console help list&lt;/info&gt;
 
 You can also output the help in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console help --format=xml list&lt;/info&gt;
 
 To display the list of available commands, please use the &lt;info&gt;list&lt;/info&gt; command.</help>
      <aliases/>
      <arguments>
        <argument name="command_name" is_required="0" is_array="0">
          <description>The command name</description>
          <defaults>
            <default>help</default>
          </defaults>
        </argument>
      </arguments>
      <options>
        <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output help as XML</description>
        </option>
        <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
          <description>To output help in other formats</description>
          <defaults>
            <default>txt</default>
          </defaults>
        </option>
        <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output raw command help</description>
        </option>
        <option name="--help" shortcut="-h" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this help message.</description>
        </option>
        <option name="--quiet" shortcut="-q" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not output any message.</description>
        </option>
        <option name="--verbose" shortcut="-v" shortcuts="-v|-vv|-vvv" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug</description>
        </option>
        <option name="--version" shortcut="-V" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Display this application version.</description>
        </option>
        <option name="--ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Force ANSI output.</description>
        </option>
        <option name="--no-ansi" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Disable ANSI output.</description>
        </option>
        <option name="--no-interaction" shortcut="-n" accept_value="0" is_value_required="0" is_multiple="0">
          <description>Do not ask any interactive question.</description>
        </option>
      </options>
    </command>
    <command id="list" name="list">
      <usage>list [--xml] [--raw] [--format="..."] [namespace]</usage>
      <description>Lists commands</description>
      <help>The &lt;info&gt;list&lt;/info&gt; command lists all commands:
 
   &lt;info&gt;php app/console list&lt;/info&gt;
 
 You can also display the commands for a specific namespace:
 
   &lt;info&gt;php app/console list test&lt;/info&gt;
 
 You can also output the information in other formats by using the &lt;comment&gt;--format&lt;/comment&gt; option:
 
   &lt;info&gt;php app/console list --format=xml&lt;/info&gt;
 
 It's also possible to get raw list of commands (useful for embedding command runner):
 
   &lt;info&gt;php app/console list --raw&lt;/info&gt;</help>
      <aliases/>
      <arguments>
        <argument name="namespace" is_required="0" is_array="0">
          <description>The namespace name</description>
          <defaults/>
        </argument>
      </arguments>
      <options>
        <option name="--xml" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output list as XML</description>
        </option>
        <option name="--raw" shortcut="" accept_value="0" is_value_required="0" is_multiple="0">
          <description>To output raw command list</description>
        </option>
        <option name="--format" shortcut="" accept_value="1" is_value_required="1" is_multiple="0">
          <description>To output list in other formats</description>
          <defaults>
            <default>txt</default>
          </defaults>
        </option>
      </options>
    </command>
  </commands>
  <namespaces>
    <namespace id="_global">
      <command>help</command>
      <command>list</command>
    </namespace>
  </namespaces>
</symfony>
PKD1[�Y-͡�BConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.mdnu�[���**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: <none>
* Default: `false`
PKE1[(?hEConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.txtnu�[��� <info>argument_name</info>
PKE1[�e::EConsole/Symfony/Component/Console/Tests/Fixtures/application_run1.txtnu�[���Console Tool

Usage:
  [options] command [arguments]

Options:
  --help           -h Display this help message.
  --quiet          -q Do not output any message.
  --verbose        -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  --version        -V Display this application version.
  --ansi              Force ANSI output.
  --no-ansi           Disable ANSI output.
  --no-interaction -n Do not ask any interactive question.

Available commands:
  help   Displays help for a command
  list   Lists commands
PKE1[��x�44CConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.txtnu�[��� <info>--option_name</info> (-o) option description
PKE1[6 �_AA@Console/Symfony/Component/Console/Tests/Fixtures/Foo3Command.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Foo3Command extends Command
{
    protected function configure()
    {
        $this
            ->setName('foo3:bar')
            ->setDescription('The foo3:bar command')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            try {
                throw new \Exception("First exception <p>this is html</p>");
            } catch (\Exception $e) {
                throw new \Exception("Second exception <comment>comment</comment>", 0, $e);
            }
        } catch (\Exception $e) {
            throw new \Exception("Third exception <fg=blue;bg=red>comment</>", 0, $e);
        }
    }
}
PKE1[��I��DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.jsonnu�[���{"name":"--option_name","shortcut":"-o","accept_value":true,"is_value_required":true,"is_multiple":false,"description":"option description","default":null}
PKE1[Xz�??GConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand2.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Fixtures;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class DescriptorCommand2 extends Command
{
    protected function configure()
    {
        $this
            ->setName('descriptor:command2')
            ->setDescription('command 2 description')
            ->setHelp('command 2 help')
            ->addArgument('argument_name', InputArgument::REQUIRED)
            ->addOption('option_name', 'o', InputOption::VALUE_NONE)
        ;
    }
}
PKE1[*[Ǿ44FConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.mdnu�[���### Arguments:

**argument_name:**

* Name: argument_name
* Is required: yes
* Is array: no
* Description: <none>
* Default: `NULL`

### Options:

**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: <none>
* Default: `false`
PKE1[	�Ӹ�BConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.mdnu�[���**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: yes
* Is value required: no
* Is multiple: no
* Description: option description
* Default: `'default_value'`
PKE1[��U���=Console/Symfony/Component/Console/Tests/Fixtures/command_2.mdnu�[���descriptor:command2
-------------------

* Description: command 2 description
* Usage: `descriptor:command2 [-o|--option_name] argument_name`
* Aliases: <none>

command 2 help

### Arguments:

**argument_name:**

* Name: argument_name
* Is required: yes
* Is array: no
* Description: <none>
* Default: `NULL`

### Options:

**option_name:**

* Name: `--option_name`
* Shortcut: `-o`
* Accept value: no
* Is value required: no
* Is multiple: no
* Description: <none>
* Default: `false`
PKE1[8�UT

EConsole/Symfony/Component/Console/Tests/Fixtures/application_run4.txtnu�[���Console Tool
PKE1[1G~"//BConsole/Symfony/Component/Console/Tests/Fixtures/FoobarCommand.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class FoobarCommand extends Command
{
    public $input;
    public $output;

    protected function configure()
    {
        $this
            ->setName('foobar:foo')
            ->setDescription('The foobar:foo command')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
    }
}
PKE1[�/""��@Console/Symfony/Component/Console/Tests/Fixtures/Foo5Command.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;

class Foo5Command extends Command
{
    public function __construct()
    {
    }
}
PKE1[�Xl��QConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception4.txtnu�[���

                               
  [InvalidArgumentException]   
  Command "foo" is not define  
  d.                           
                               


PKE1[*�q��HConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.jsonnu�[���{"arguments":[],"options":{"option_name":{"name":"--option_name","shortcut":"-o","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"","default":false}}}
PKE1[��EOO>Console/Symfony/Component/Console/Tests/Fixtures/command_1.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<command id="descriptor:command1" name="descriptor:command1">
  <usage>descriptor:command1</usage>
  <description>command 1 description</description>
  <help>command 1 help</help>
  <aliases>
    <alias>alias1</alias>
    <alias>alias2</alias>
  </aliases>
  <arguments/>
  <options/>
</command>
PKE1[�NY__EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.txtnu�[��� <info>argument_name</info> argument description<comment> (default: "default_value")</comment>
PKE1[�����HConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.jsonnu�[���{"arguments":{"argument_name":{"name":"argument_name","is_required":true,"is_array":false,"description":"","default":null}},"options":[]}
PKE1[h����>Console/Symfony/Component/Console/Tests/Fixtures/command_2.txtnu�[���<comment>Usage:</comment>
 descriptor:command2 [-o|--option_name] argument_name

<comment>Arguments:</comment>
 <info>argument_name     </info> 

<comment>Options:</comment>
 <info>--option_name</info> (-o) 

<comment>Help:</comment>
 command 2 help
PKE1[�	���@Console/Symfony/Component/Console/Tests/Fixtures/Foo2Command.phpnu�[���<?php

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Foo2Command extends Command
{
    protected function configure()
    {
        $this
            ->setName('foo1:bar')
            ->setDescription('The foo1:bar command')
            ->setAliases(array('afoobar2'))
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    }
}
PKE1[,D���QConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception2.txtnu�[���

                                      
  [InvalidArgumentException]          
  The "--foo" option does not exist.  
                                      


list [--xml] [--raw] [--format="..."] [namespace]


PKE1[.p�~~GConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.txtnu�[���<comment>Arguments:</comment>
 <info>argument_name     </info> 

<comment>Options:</comment>
 <info>--option_name</info> (-o)
PKE1[��M��CConsole/Symfony/Component/Console/Tests/Fixtures/application_2.jsonnu�[���{"commands":[{"name":"help","usage":"help [--xml] [--format=\"...\"] [--raw] [command_name]","description":"Displays help for a command","help":"The <info>help<\/info> command displays help for a given command:\n\n  <info>php app\/console help list<\/info>\n\nYou can also output the help in other formats by using the <comment>--format<\/comment> option:\n\n  <info>php app\/console help --format=xml list<\/info>\n\nTo display the list of available commands, please use the <info>list<\/info> command.","aliases":[],"definition":{"arguments":{"command_name":{"name":"command_name","is_required":false,"is_array":false,"description":"The command name","default":"help"}},"options":{"xml":{"name":"--xml","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output help as XML","default":false},"format":{"name":"--format","shortcut":"","accept_value":true,"is_value_required":true,"is_multiple":false,"description":"To output help in other formats","default":"txt"},"raw":{"name":"--raw","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output raw command help","default":false},"help":{"name":"--help","shortcut":"-h","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this help message.","default":false},"quiet":{"name":"--quiet","shortcut":"-q","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not output any message.","default":false},"verbose":{"name":"--verbose","shortcut":"-v|-vv|-vvv","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug","default":false},"version":{"name":"--version","shortcut":"-V","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this application version.","default":false},"ansi":{"name":"--ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Force ANSI output.","default":false},"no-ansi":{"name":"--no-ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Disable ANSI output.","default":false},"no-interaction":{"name":"--no-interaction","shortcut":"-n","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not ask any interactive question.","default":false}}}},{"name":"list","usage":"list [--xml] [--raw] [--format=\"...\"] [namespace]","description":"Lists commands","help":"The <info>list<\/info> command lists all commands:\n\n  <info>php app\/console list<\/info>\n\nYou can also display the commands for a specific namespace:\n\n  <info>php app\/console list test<\/info>\n\nYou can also output the information in other formats by using the <comment>--format<\/comment> option:\n\n  <info>php app\/console list --format=xml<\/info>\n\nIt's also possible to get raw list of commands (useful for embedding command runner):\n\n  <info>php app\/console list --raw<\/info>","aliases":[],"definition":{"arguments":{"namespace":{"name":"namespace","is_required":false,"is_array":false,"description":"The namespace name","default":null}},"options":{"xml":{"name":"--xml","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output list as XML","default":false},"raw":{"name":"--raw","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"To output raw command list","default":false},"format":{"name":"--format","shortcut":"","accept_value":true,"is_value_required":true,"is_multiple":false,"description":"To output list in other formats","default":"txt"}}}},{"name":"descriptor:command1","usage":"descriptor:command1","description":"command 1 description","help":"command 1 help","aliases":["alias1","alias2"],"definition":{"arguments":[],"options":{"help":{"name":"--help","shortcut":"-h","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this help message.","default":false},"quiet":{"name":"--quiet","shortcut":"-q","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not output any message.","default":false},"verbose":{"name":"--verbose","shortcut":"-v|-vv|-vvv","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug","default":false},"version":{"name":"--version","shortcut":"-V","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this application version.","default":false},"ansi":{"name":"--ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Force ANSI output.","default":false},"no-ansi":{"name":"--no-ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Disable ANSI output.","default":false},"no-interaction":{"name":"--no-interaction","shortcut":"-n","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not ask any interactive question.","default":false}}}},{"name":"descriptor:command2","usage":"descriptor:command2 [-o|--option_name] argument_name","description":"command 2 description","help":"command 2 help","aliases":[],"definition":{"arguments":{"argument_name":{"name":"argument_name","is_required":true,"is_array":false,"description":"","default":null}},"options":{"option_name":{"name":"--option_name","shortcut":"-o","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"","default":false},"help":{"name":"--help","shortcut":"-h","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this help message.","default":false},"quiet":{"name":"--quiet","shortcut":"-q","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not output any message.","default":false},"verbose":{"name":"--verbose","shortcut":"-v|-vv|-vvv","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug","default":false},"version":{"name":"--version","shortcut":"-V","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Display this application version.","default":false},"ansi":{"name":"--ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Force ANSI output.","default":false},"no-ansi":{"name":"--no-ansi","shortcut":"","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Disable ANSI output.","default":false},"no-interaction":{"name":"--no-interaction","shortcut":"-n","accept_value":false,"is_value_required":false,"is_multiple":false,"description":"Do not ask any interactive question.","default":false}}}}],"namespaces":[{"id":"_global","commands":["alias1","alias2","help","list"]},{"id":"descriptor","commands":["descriptor:command1","descriptor:command2"]}]}
PKE1[��ttDConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.mdnu�[���**argument_name:**

* Name: argument_name
* Is required: yes
* Is array: no
* Description: <none>
* Default: `NULL`
PKE1[Q��d	d	HConsole/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Tester;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Tester\ApplicationTester;

class ApplicationTesterTest extends \PHPUnit_Framework_TestCase
{
    protected $application;
    protected $tester;

    protected function setUp()
    {
        $this->application = new Application();
        $this->application->setAutoExit(false);
        $this->application->register('foo')
            ->addArgument('foo')
            ->setCode(function ($input, $output) { $output->writeln('foo'); })
        ;

        $this->tester = new ApplicationTester($this->application);
        $this->tester->run(array('command' => 'foo', 'foo' => 'bar'), array('interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
    }

    protected function tearDown()
    {
        $this->application = null;
        $this->tester = null;
    }

    public function testRun()
    {
        $this->assertFalse($this->tester->getInput()->isInteractive(), '->execute() takes an interactive option');
        $this->assertFalse($this->tester->getOutput()->isDecorated(), '->execute() takes a decorated option');
        $this->assertEquals(Output::VERBOSITY_VERBOSE, $this->tester->getOutput()->getVerbosity(), '->execute() takes a verbosity option');
    }

    public function testGetInput()
    {
        $this->assertEquals('bar', $this->tester->getInput()->getArgument('foo'), '->getInput() returns the current input instance');
    }

    public function testGetOutput()
    {
        rewind($this->tester->getOutput()->getStream());
        $this->assertEquals('foo'.PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance');
    }

    public function testGetDisplay()
    {
        $this->assertEquals('foo'.PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution');
    }

    public function testGetStatusCode()
    {
        $this->assertSame(0, $this->tester->getStatusCode(), '->getStatusCode() returns the status code');
    }
}
PKE1[�x0mBBDConsole/Symfony/Component/Console/Tests/Tester/CommandTesterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Tester;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Tester\CommandTester;

class CommandTesterTest extends \PHPUnit_Framework_TestCase
{
    protected $command;
    protected $tester;

    protected function setUp()
    {
        $this->command = new Command('foo');
        $this->command->addArgument('command');
        $this->command->addArgument('foo');
        $this->command->setCode(function ($input, $output) { $output->writeln('foo'); });

        $this->tester = new CommandTester($this->command);
        $this->tester->execute(array('foo' => 'bar'), array('interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
    }

    protected function tearDown()
    {
        $this->command = null;
        $this->tester = null;
    }

    public function testExecute()
    {
        $this->assertFalse($this->tester->getInput()->isInteractive(), '->execute() takes an interactive option');
        $this->assertFalse($this->tester->getOutput()->isDecorated(), '->execute() takes a decorated option');
        $this->assertEquals(Output::VERBOSITY_VERBOSE, $this->tester->getOutput()->getVerbosity(), '->execute() takes a verbosity option');
    }

    public function testGetInput()
    {
        $this->assertEquals('bar', $this->tester->getInput()->getArgument('foo'), '->getInput() returns the current input instance');
    }

    public function testGetOutput()
    {
        rewind($this->tester->getOutput()->getStream());
        $this->assertEquals('foo'.PHP_EOL, stream_get_contents($this->tester->getOutput()->getStream()), '->getOutput() returns the current output instance');
    }

    public function testGetDisplay()
    {
        $this->assertEquals('foo'.PHP_EOL, $this->tester->getDisplay(), '->getDisplay() returns the display of the last execution');
    }

    public function testGetStatusCode()
    {
        $this->assertSame(0, $this->tester->getStatusCode(), '->getStatusCode() returns the status code');
    }

    public function testCommandFromApplication()
    {
        $application = new Application();
        $application->setAutoExit(false);

        $command = new Command('foo');
        $command->setCode(function ($input, $output) { $output->writeln('foo'); });

        $application->add($command);

        $tester = new CommandTester($application->find('foo'));

        // check that there is no need to pass the command name here
        $this->assertEquals(0, $tester->execute(array()));
    }
}
PKE1[�����AConsole/Symfony/Component/Console/Tests/Input/StringInputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StringInput;

class StringInputTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTokenizeData
     */
    public function testTokenize($input, $tokens, $message)
    {
        $input = new StringInput($input);
        $r = new \ReflectionClass('Symfony\Component\Console\Input\ArgvInput');
        $p = $r->getProperty('tokens');
        $p->setAccessible(true);
        $this->assertEquals($tokens, $p->getValue($input), $message);
    }

    public function testInputOptionWithGivenString()
    {
        $definition = new InputDefinition(
            array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))
        );

        // call to bind
        $input = new StringInput('--foo=bar');
        $input->bind($definition);
        $this->assertEquals('bar', $input->getOption('foo'));

        // definition in constructor
        $input = new StringInput('--foo=bar', $definition);
        $this->assertEquals('bar', $input->getOption('foo'));
    }

    public function getTokenizeData()
    {
        return array(
            array('', array(), '->tokenize() parses an empty string'),
            array('foo', array('foo'), '->tokenize() parses arguments'),
            array('  foo  bar  ', array('foo', 'bar'), '->tokenize() ignores whitespaces between arguments'),
            array('"quoted"', array('quoted'), '->tokenize() parses quoted arguments'),
            array("'quoted'", array('quoted'), '->tokenize() parses quoted arguments'),
            array("'a\rb\nc\td'", array("a\rb\nc\td"), '->tokenize() parses whitespace chars in strings'),
            array("'a'\r'b'\n'c'\t'd'", array('a','b','c','d'), '->tokenize() parses whitespace chars between args as spaces'),
            array('\"quoted\"', array('"quoted"'), '->tokenize() parses escaped-quoted arguments'),
            array("\'quoted\'", array('\'quoted\''), '->tokenize() parses escaped-quoted arguments'),
            array('-a', array('-a'), '->tokenize() parses short options'),
            array('-azc', array('-azc'), '->tokenize() parses aggregated short options'),
            array('-awithavalue', array('-awithavalue'), '->tokenize() parses short options with a value'),
            array('-a"foo bar"', array('-afoo bar'), '->tokenize() parses short options with a value'),
            array('-a"foo bar""foo bar"', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
            array('-a\'foo bar\'', array('-afoo bar'), '->tokenize() parses short options with a value'),
            array('-a\'foo bar\'\'foo bar\'', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
            array('-a\'foo bar\'"foo bar"', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
            array('--long-option', array('--long-option'), '->tokenize() parses long options'),
            array('--long-option=foo', array('--long-option=foo'), '->tokenize() parses long options with a value'),
            array('--long-option="foo bar"', array('--long-option=foo bar'), '->tokenize() parses long options with a value'),
            array('--long-option="foo bar""another"', array('--long-option=foo baranother'), '->tokenize() parses long options with a value'),
            array('--long-option=\'foo bar\'', array('--long-option=foo bar'), '->tokenize() parses long options with a value'),
            array("--long-option='foo bar''another'", array("--long-option=foo baranother"), '->tokenize() parses long options with a value'),
            array("--long-option='foo bar'\"another\"", array("--long-option=foo baranother"), '->tokenize() parses long options with a value'),
            array('foo -a -ffoo --long bar', array('foo', '-a', '-ffoo', '--long', 'bar'), '->tokenize() parses when several arguments and options'),
        );
    }

    public function testToString()
    {
        $input = new StringInput('-f foo');
        $this->assertEquals('-f foo', (string) $input);

        $input = new StringInput('-f --bar=foo "a b c d"');
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d'), (string) $input);

        $input = new StringInput('-f --bar=foo \'a b c d\' '."'A\nB\\'C'");
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d').' '.escapeshellarg("A\nB'C"), (string) $input);
    }
}
PKE1[��p���;Console/Symfony/Component/Console/Tests/Input/InputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class InputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals('foo', $input->getArgument('name'), '->__construct() takes a InputDefinition as an argument');
    }

    public function testOptions()
    {
        $input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'))));
        $this->assertEquals('foo', $input->getOption('name'), '->getOption() returns the value for the given option');

        $input->setOption('name', 'bar');
        $this->assertEquals('bar', $input->getOption('name'), '->setOption() sets the value for a given option');
        $this->assertEquals(array('name' => 'bar'), $input->getOptions(), '->getOptions() returns all option values');

        $input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
        $this->assertEquals('default', $input->getOption('bar'), '->getOption() returns the default value for optional options');
        $this->assertEquals(array('name' => 'foo', 'bar' => 'default'), $input->getOptions(), '->getOptions() returns all option values, even optional ones');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "foo" option does not exist.
     */
    public function testSetInvalidOption()
    {
        $input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
        $input->setOption('foo', 'bar');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "foo" option does not exist.
     */
    public function testGetInvalidOption()
    {
        $input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
        $input->getOption('foo');
    }

    public function testArguments()
    {
        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals('foo', $input->getArgument('name'), '->getArgument() returns the value for the given argument');

        $input->setArgument('name', 'bar');
        $this->assertEquals('bar', $input->getArgument('name'), '->setArgument() sets the value for a given argument');
        $this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->getArguments() returns all argument values');

        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
        $this->assertEquals('default', $input->getArgument('bar'), '->getArgument() returns the default value for optional arguments');
        $this->assertEquals(array('name' => 'foo', 'bar' => 'default'), $input->getArguments(), '->getArguments() returns all argument values, even optional ones');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "foo" argument does not exist.
     */
    public function testSetInvalidArgument()
    {
        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
        $input->setArgument('foo', 'bar');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "foo" argument does not exist.
     */
    public function testGetInvalidArgument()
    {
        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
        $input->getArgument('foo');
    }

    /**
     * @expectedException        \RuntimeException
     * @expectedExceptionMessage Not enough arguments.
     */
    public function testValidateWithMissingArguments()
    {
        $input = new ArrayInput(array());
        $input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::REQUIRED))));
        $input->validate();
    }

    public function testValidate()
    {
        $input = new ArrayInput(array('name' => 'foo'));
        $input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::REQUIRED))));

        $this->assertNull($input->validate());
    }

    public function testSetGetInteractive()
    {
        $input = new ArrayInput(array());
        $this->assertTrue($input->isInteractive(), '->isInteractive() returns whether the input should be interactive or not');
        $input->setInteractive(false);
        $this->assertFalse($input->isInteractive(), '->setInteractive() changes the interactive flag');
    }
}
PKE1[�9I;;?Console/Symfony/Component/Console/Tests/Input/ArgvInputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class ArgvInputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $_SERVER['argv'] = array('cli.php', 'foo');
        $input = new ArgvInput();
        $r = new \ReflectionObject($input);
        $p = $r->getProperty('tokens');
        $p->setAccessible(true);

        $this->assertEquals(array('foo'), $p->getValue($input), '__construct() automatically get its input from the argv server variable');
    }

    public function testParseArguments()
    {
        $input = new ArgvInput(array('cli.php', 'foo'));
        $input->bind(new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments');

        $input->bind(new InputDefinition(array(new InputArgument('name'))));
        $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() is stateless');
    }

    /**
     * @dataProvider provideOptions
     */
    public function testParseOptions($input, $options, $expectedOptions, $message)
    {
        $input = new ArgvInput($input);
        $input->bind(new InputDefinition($options));

        $this->assertEquals($expectedOptions, $input->getOptions(), $message);
    }

    public function provideOptions()
    {
        return array(
            array(
                array('cli.php', '--foo'),
                array(new InputOption('foo')),
                array('foo' => true),
                '->parse() parses long options without a value'
            ),
            array(
                array('cli.php', '--foo=bar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
                array('foo' => 'bar'),
                '->parse() parses long options with a required value (with a = separator)'
            ),
            array(
                array('cli.php', '--foo', 'bar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
                array('foo' => 'bar'),
                '->parse() parses long options with a required value (with a space separator)'
            ),
            array(
                array('cli.php', '-f'),
                array(new InputOption('foo', 'f')),
                array('foo' => true),
                '->parse() parses short options without a value'
            ),
            array(
                array('cli.php', '-fbar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
                array('foo' => 'bar'),
                '->parse() parses short options with a required value (with no separator)'
            ),
            array(
                array('cli.php', '-f', 'bar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
                array('foo' => 'bar'),
                '->parse() parses short options with a required value (with a space separator)'
            ),
            array(
                array('cli.php', '-f', ''),
                array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
                array('foo' => ''),
                '->parse() parses short options with an optional empty value'
            ),
            array(
                array('cli.php', '-f', '', 'foo'),
                array(new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
                array('foo' => ''),
                '->parse() parses short options with an optional empty value followed by an argument'
            ),
            array(
                array('cli.php', '-f', '', '-b'),
                array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')),
                array('foo' => '', 'bar' => true),
                '->parse() parses short options with an optional empty value followed by an option'
            ),
            array(
                array('cli.php', '-f', '-b', 'foo'),
                array(new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')),
                array('foo' => null, 'bar' => true),
                '->parse() parses short options with an optional value which is not present'
            ),
            array(
                array('cli.php', '-fb'),
                array(new InputOption('foo', 'f'), new InputOption('bar', 'b')),
                array('foo' => true, 'bar' => true),
                '->parse() parses short options when they are aggregated as a single one'
            ),
            array(
                array('cli.php', '-fb', 'bar'),
                array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_REQUIRED)),
                array('foo' => true, 'bar' => 'bar'),
                '->parse() parses short options when they are aggregated as a single one and the last one has a required value'
            ),
            array(
                array('cli.php', '-fb', 'bar'),
                array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
                array('foo' => true, 'bar' => 'bar'),
                '->parse() parses short options when they are aggregated as a single one and the last one has an optional value'
            ),
            array(
                array('cli.php', '-fbbar'),
                array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
                array('foo' => true, 'bar' => 'bar'),
                '->parse() parses short options when they are aggregated as a single one and the last one has an optional value with no separator'
            ),
            array(
                array('cli.php', '-fbbar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
                array('foo' => 'bbar', 'bar' => null),
                '->parse() parses short options when they are aggregated as a single one and one of them takes a value'
            )
        );
    }

    /**
     * @dataProvider provideInvalidInput
     */
    public function testInvalidInput($argv, $definition, $expectedExceptionMessage)
    {
        $this->setExpectedException('RuntimeException', $expectedExceptionMessage);

        $input = new ArgvInput($argv);
        $input->bind($definition);
    }

    public function provideInvalidInput()
    {
        return array(
            array(
                array('cli.php', '--foo'),
                new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
                'The "--foo" option requires a value.'
            ),
            array(
                array('cli.php', '-f'),
                new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
                'The "--foo" option requires a value.'
            ),
            array(
                array('cli.php', '-ffoo'),
                new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))),
                'The "-o" option does not exist.'
            ),
            array(
                array('cli.php', '--foo=bar'),
                new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))),
                'The "--foo" option does not accept a value.'
            ),
            array(
                array('cli.php', 'foo', 'bar'),
                new InputDefinition(),
                'Too many arguments.'
            ),
            array(
                array('cli.php', '--foo'),
                new InputDefinition(),
                'The "--foo" option does not exist.'
            ),
            array(
                array('cli.php', '-f'),
                new InputDefinition(),
                'The "-f" option does not exist.'
            ),
            array(
                array('cli.php', '-1'),
                new InputDefinition(array(new InputArgument('number'))),
                'The "-1" option does not exist.'
            )
        );
    }

    public function testParseArrayArgument()
    {
        $input = new ArgvInput(array('cli.php', 'foo', 'bar', 'baz', 'bat'));
        $input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::IS_ARRAY))));

        $this->assertEquals(array('name' => array('foo', 'bar', 'baz', 'bat')), $input->getArguments(), '->parse() parses array arguments');
    }

    public function testParseArrayOption()
    {
        $input = new ArgvInput(array('cli.php', '--name=foo', '--name=bar', '--name=baz'));
        $input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));

        $this->assertEquals(array('name' => array('foo', 'bar', 'baz')), $input->getOptions(), '->parse() parses array options ("--option=value" syntax)');

        $input = new ArgvInput(array('cli.php', '--name', 'foo', '--name', 'bar', '--name', 'baz'));
        $input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));
        $this->assertEquals(array('name' => array('foo', 'bar', 'baz')), $input->getOptions(), '->parse() parses array options ("--option value" syntax)');

        $input = new ArgvInput(array('cli.php', '--name=foo', '--name=bar', '--name='));
        $input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));
        $this->assertSame(array('name' => array('foo', 'bar', null)), $input->getOptions(), '->parse() parses empty array options as null ("--option=value" syntax)');

        $input = new ArgvInput(array('cli.php', '--name', 'foo', '--name', 'bar', '--name', '--anotherOption'));
        $input->bind(new InputDefinition(array(
            new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY),
            new InputOption('anotherOption', null, InputOption::VALUE_NONE),
        )));
        $this->assertSame(array('name' => array('foo', 'bar', null), 'anotherOption' => true), $input->getOptions(), '->parse() parses empty array options as null ("--option value" syntax)');
    }

    public function testParseNegativeNumberAfterDoubleDash()
    {
        $input = new ArgvInput(array('cli.php', '--', '-1'));
        $input->bind(new InputDefinition(array(new InputArgument('number'))));
        $this->assertEquals(array('number' => '-1'), $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');

        $input = new ArgvInput(array('cli.php', '-f', 'bar', '--', '-1'));
        $input->bind(new InputDefinition(array(new InputArgument('number'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL))));
        $this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses arguments with leading dashes as options before having encountered a double-dash sequence');
        $this->assertEquals(array('number' => '-1'), $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');
    }

    public function testParseEmptyStringArgument()
    {
        $input = new ArgvInput(array('cli.php', '-f', 'bar', ''));
        $input->bind(new InputDefinition(array(new InputArgument('empty'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL))));

        $this->assertEquals(array('empty' => ''), $input->getArguments(), '->parse() parses empty string arguments');
    }

    public function testGetFirstArgument()
    {
        $input = new ArgvInput(array('cli.php', '-fbbar'));
        $this->assertEquals('', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input');

        $input = new ArgvInput(array('cli.php', '-fbbar', 'foo'));
        $this->assertEquals('foo', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input');
    }

    public function testHasParameterOption()
    {
        $input = new ArgvInput(array('cli.php', '-f', 'foo'));
        $this->assertTrue($input->hasParameterOption('-f'), '->hasParameterOption() returns true if the given short option is in the raw input');

        $input = new ArgvInput(array('cli.php', '--foo', 'foo'));
        $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if the given short option is in the raw input');

        $input = new ArgvInput(array('cli.php', 'foo'));
        $this->assertFalse($input->hasParameterOption('--foo'), '->hasParameterOption() returns false if the given short option is not in the raw input');

        $input = new ArgvInput(array('cli.php', '--foo=bar'));
        $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if the given option with provided value is in the raw input');
    }

    public function testToString()
    {
        $input = new ArgvInput(array('cli.php', '-f', 'foo'));
        $this->assertEquals('-f foo', (string) $input);

        $input = new ArgvInput(array('cli.php', '-f', '--bar=foo', 'a b c d', "A\nB'C"));
        $this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d').' '.escapeshellarg("A\nB'C"), (string) $input);
    }

    /**
     * @dataProvider provideGetParameterOptionValues
     */
    public function testGetParameterOptionEqualSign($argv, $key, $expected)
    {
        $input = new ArgvInput($argv);
        $this->assertEquals($expected, $input->getParameterOption($key), '->getParameterOption() returns the expected value');
    }

    public function provideGetParameterOptionValues()
    {
        return array(
            array(array('app/console', 'foo:bar', '-e', 'dev'), '-e', 'dev'),
            array(array('app/console', 'foo:bar', '--env=dev'), '--env', 'dev'),
            array(array('app/console', 'foo:bar', '-e', 'dev'), array('-e', '--env'), 'dev'),
            array(array('app/console', 'foo:bar', '--env=dev'), array('-e', '--env'), 'dev'),
            array(array('app/console', 'foo:bar', '--env=dev', '--en=1'), array('--en'), '1'),
        );
    }

    public function testParseSingleDashAsArgument()
    {
        $input = new ArgvInput(array('cli.php', '-'));
        $input->bind(new InputDefinition(array(new InputArgument('file'))));
        $this->assertEquals(array('file' => '-'), $input->getArguments(), '->parse() parses single dash as an argument');
    }
}
PKE1[��@�H�HEConsole/Symfony/Component/Console/Tests/Input/InputDefinitionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class InputDefinitionTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixtures;

    protected $foo, $bar, $foo1, $foo2;

    public static function setUpBeforeClass()
    {
        self::$fixtures = __DIR__.'/../Fixtures/';
    }

    public function testConstructorArguments()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $this->assertEquals(array(), $definition->getArguments(), '__construct() creates a new InputDefinition object');

        $definition = new InputDefinition(array($this->foo, $this->bar));
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '__construct() takes an array of InputArgument objects as its first argument');
    }

    public function testConstructorOptions()
    {
        $this->initializeOptions();

        $definition = new InputDefinition();
        $this->assertEquals(array(), $definition->getOptions(), '__construct() creates a new InputDefinition object');

        $definition = new InputDefinition(array($this->foo, $this->bar));
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '__construct() takes an array of InputOption objects as its first argument');
    }

    public function testSetArguments()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->setArguments(array($this->foo));
        $this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->setArguments() sets the array of InputArgument objects');
        $definition->setArguments(array($this->bar));

        $this->assertEquals(array('bar' => $this->bar), $definition->getArguments(), '->setArguments() clears all InputArgument objects');
    }

    public function testAddArguments()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArguments(array($this->foo));
        $this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->addArguments() adds an array of InputArgument objects');
        $definition->addArguments(array($this->bar));
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '->addArguments() does not clear existing InputArgument objects');
    }

    public function testAddArgument()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument($this->foo);
        $this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->addArgument() adds a InputArgument object');
        $definition->addArgument($this->bar);
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '->addArgument() adds a InputArgument object');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage An argument with name "foo" already exists.
     */
    public function testArgumentsMustHaveDifferentNames()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument($this->foo);
        $definition->addArgument($this->foo1);
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage Cannot add an argument after an array argument.
     */
    public function testArrayArgumentHasToBeLast()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument(new InputArgument('fooarray', InputArgument::IS_ARRAY));
        $definition->addArgument(new InputArgument('anotherbar'));
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage Cannot add a required argument after an optional one.
     */
    public function testRequiredArgumentCannotFollowAnOptionalOne()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument($this->foo);
        $definition->addArgument($this->foo2);
    }

    public function testGetArgument()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArguments(array($this->foo));
        $this->assertEquals($this->foo, $definition->getArgument('foo'), '->getArgument() returns a InputArgument by its name');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "bar" argument does not exist.
     */
    public function testGetInvalidArgument()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArguments(array($this->foo));
        $definition->getArgument('bar');
    }

    public function testHasArgument()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArguments(array($this->foo));

        $this->assertTrue($definition->hasArgument('foo'), '->hasArgument() returns true if a InputArgument exists for the given name');
        $this->assertFalse($definition->hasArgument('bar'), '->hasArgument() returns false if a InputArgument exists for the given name');
    }

    public function testGetArgumentRequiredCount()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument($this->foo2);
        $this->assertEquals(1, $definition->getArgumentRequiredCount(), '->getArgumentRequiredCount() returns the number of required arguments');
        $definition->addArgument($this->foo);
        $this->assertEquals(1, $definition->getArgumentRequiredCount(), '->getArgumentRequiredCount() returns the number of required arguments');
    }

    public function testGetArgumentCount()
    {
        $this->initializeArguments();

        $definition = new InputDefinition();
        $definition->addArgument($this->foo2);
        $this->assertEquals(1, $definition->getArgumentCount(), '->getArgumentCount() returns the number of arguments');
        $definition->addArgument($this->foo);
        $this->assertEquals(2, $definition->getArgumentCount(), '->getArgumentCount() returns the number of arguments');
    }

    public function testGetArgumentDefaults()
    {
        $definition = new InputDefinition(array(
            new InputArgument('foo1', InputArgument::OPTIONAL),
            new InputArgument('foo2', InputArgument::OPTIONAL, '', 'default'),
            new InputArgument('foo3', InputArgument::OPTIONAL | InputArgument::IS_ARRAY),
        //  new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', array(1, 2)),
        ));
        $this->assertEquals(array('foo1' => null, 'foo2' => 'default', 'foo3' => array()), $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');

        $definition = new InputDefinition(array(
            new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', array(1, 2)),
        ));
        $this->assertEquals(array('foo4' => array(1, 2)), $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');
    }

    public function testSetOptions()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->setOptions() sets the array of InputOption objects');
        $definition->setOptions(array($this->bar));
        $this->assertEquals(array('bar' => $this->bar), $definition->getOptions(), '->setOptions() clears all InputOption objects');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "-f" option does not exist.
     */
    public function testSetOptionsClearsOptions()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $definition->setOptions(array($this->bar));
        $definition->getOptionForShortcut('f');
    }

    public function testAddOptions()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->addOptions() adds an array of InputOption objects');
        $definition->addOptions(array($this->bar));
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '->addOptions() does not clear existing InputOption objects');
    }

    public function testAddOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition();
        $definition->addOption($this->foo);
        $this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->addOption() adds a InputOption object');
        $definition->addOption($this->bar);
        $this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '->addOption() adds a InputOption object');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage An option named "foo" already exists.
     */
    public function testAddDuplicateOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition();
        $definition->addOption($this->foo);
        $definition->addOption($this->foo2);
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage An option with shortcut "f" already exists.
     */
    public function testAddDuplicateShortcutOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition();
        $definition->addOption($this->foo);
        $definition->addOption($this->foo1);
    }

    public function testGetOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertEquals($this->foo, $definition->getOption('foo'), '->getOption() returns a InputOption by its name');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "--bar" option does not exist.
     */
    public function testGetInvalidOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $definition->getOption('bar');
    }

    public function testHasOption()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertTrue($definition->hasOption('foo'), '->hasOption() returns true if a InputOption exists for the given name');
        $this->assertFalse($definition->hasOption('bar'), '->hasOption() returns false if a InputOption exists for the given name');
    }

    public function testHasShortcut()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertTrue($definition->hasShortcut('f'), '->hasShortcut() returns true if a InputOption exists for the given shortcut');
        $this->assertFalse($definition->hasShortcut('b'), '->hasShortcut() returns false if a InputOption exists for the given shortcut');
    }

    public function testGetOptionForShortcut()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $this->assertEquals($this->foo, $definition->getOptionForShortcut('f'), '->getOptionForShortcut() returns a InputOption by its shortcut');
    }

    public function testGetOptionForMultiShortcut()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->multi));
        $this->assertEquals($this->multi, $definition->getOptionForShortcut('m'), '->getOptionForShortcut() returns a InputOption by its shortcut');
        $this->assertEquals($this->multi, $definition->getOptionForShortcut('mmm'), '->getOptionForShortcut() returns a InputOption by its shortcut');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "-l" option does not exist.
     */
    public function testGetOptionForInvalidShortcut()
    {
        $this->initializeOptions();

        $definition = new InputDefinition(array($this->foo));
        $definition->getOptionForShortcut('l');
    }

    public function testGetOptionDefaults()
    {
        $definition = new InputDefinition(array(
            new InputOption('foo1', null, InputOption::VALUE_NONE),
            new InputOption('foo2', null, InputOption::VALUE_REQUIRED),
            new InputOption('foo3', null, InputOption::VALUE_REQUIRED, '', 'default'),
            new InputOption('foo4', null, InputOption::VALUE_OPTIONAL),
            new InputOption('foo5', null, InputOption::VALUE_OPTIONAL, '', 'default'),
            new InputOption('foo6', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY),
            new InputOption('foo7', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, '', array(1, 2)),
        ));
        $defaults = array(
            'foo1' => null,
            'foo2' => null,
            'foo3' => 'default',
            'foo4' => null,
            'foo5' => 'default',
            'foo6' => array(),
            'foo7' => array(1, 2),
        );
        $this->assertEquals($defaults, $definition->getOptionDefaults(), '->getOptionDefaults() returns the default values for all options');
    }

    public function testGetSynopsis()
    {
        $definition = new InputDefinition(array(new InputOption('foo')));
        $this->assertEquals('[--foo]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputOption('foo', 'f')));
        $this->assertEquals('[-f|--foo]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)));
        $this->assertEquals('[-f|--foo="..."]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)));
        $this->assertEquals('[-f|--foo[="..."]]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');

        $definition = new InputDefinition(array(new InputArgument('foo')));
        $this->assertEquals('[foo]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputArgument('foo', InputArgument::REQUIRED)));
        $this->assertEquals('foo', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputArgument('foo', InputArgument::IS_ARRAY)));
        $this->assertEquals('[foo1] ... [fooN]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
        $definition = new InputDefinition(array(new InputArgument('foo', InputArgument::REQUIRED | InputArgument::IS_ARRAY)));
        $this->assertEquals('foo1 ... [fooN]', $definition->getSynopsis(), '->getSynopsis() returns a synopsis of arguments and options');
    }

    public function testAsText()
    {
        $definition = new InputDefinition(array(
            new InputArgument('foo', InputArgument::OPTIONAL, 'The foo argument'),
            new InputArgument('baz', InputArgument::OPTIONAL, 'The baz argument', true),
            new InputArgument('bar', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'The bar argument', array('http://foo.com/')),
            new InputOption('foo', 'f', InputOption::VALUE_REQUIRED, 'The foo option'),
            new InputOption('baz', null, InputOption::VALUE_OPTIONAL, 'The baz option', false),
            new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL, 'The bar option', 'bar'),
            new InputOption('qux', '', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The qux option', array('http://foo.com/', 'bar')),
            new InputOption('qux2', '', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'The qux2 option', array('foo' => 'bar')),
        ));
        $this->assertStringEqualsFile(self::$fixtures.'/definition_astext.txt', $definition->asText(), '->asText() returns a textual representation of the InputDefinition');
    }

    public function testAsXml()
    {
        $definition = new InputDefinition(array(
            new InputArgument('foo', InputArgument::OPTIONAL, 'The foo argument'),
            new InputArgument('baz', InputArgument::OPTIONAL, 'The baz argument', true),
            new InputArgument('bar', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'The bar argument', array('bar')),
            new InputOption('foo', 'f', InputOption::VALUE_REQUIRED, 'The foo option'),
            new InputOption('baz', null, InputOption::VALUE_OPTIONAL, 'The baz option', false),
            new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL, 'The bar option', 'bar'),
        ));
        $this->assertXmlStringEqualsXmlFile(self::$fixtures.'/definition_asxml.txt', $definition->asXml(), '->asText() returns a textual representation of the InputDefinition');
    }

    protected function initializeArguments()
    {
        $this->foo = new InputArgument('foo');
        $this->bar = new InputArgument('bar');
        $this->foo1 = new InputArgument('foo');
        $this->foo2 = new InputArgument('foo2', InputArgument::REQUIRED);
    }

    protected function initializeOptions()
    {
        $this->foo = new InputOption('foo', 'f');
        $this->bar = new InputOption('bar', 'b');
        $this->foo1 = new InputOption('fooBis', 'f');
        $this->foo2 = new InputOption('foo', 'p');
        $this->multi = new InputOption('multi', 'm|mm|mmm');
    }
}
PKE1[1E��<<@Console/Symfony/Component/Console/Tests/Input/ArrayInputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

class ArrayInputTest extends \PHPUnit_Framework_TestCase
{
    public function testGetFirstArgument()
    {
        $input = new ArrayInput(array());
        $this->assertNull($input->getFirstArgument(), '->getFirstArgument() returns null if no argument were passed');
        $input = new ArrayInput(array('name' => 'Fabien'));
        $this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument');
        $input = new ArrayInput(array('--foo' => 'bar', 'name' => 'Fabien'));
        $this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument');
    }

    public function testHasParameterOption()
    {
        $input = new ArrayInput(array('name' => 'Fabien', '--foo' => 'bar'));
        $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters');
        $this->assertFalse($input->hasParameterOption('--bar'), '->hasParameterOption() returns false if an option is not present in the passed parameters');

        $input = new ArrayInput(array('--foo'));
        $this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters');
    }

    public function testParseArguments()
    {
        $input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));

        $this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments');
    }

    /**
     * @dataProvider provideOptions
     */
    public function testParseOptions($input, $options, $expectedOptions, $message)
    {
        $input = new ArrayInput($input, new InputDefinition($options));

        $this->assertEquals($expectedOptions, $input->getOptions(), $message);
    }

    public function provideOptions()
    {
        return array(
            array(
                array('--foo' => 'bar'),
                array(new InputOption('foo')),
                array('foo' => 'bar'),
                '->parse() parses long options'
            ),
            array(
                array('--foo' => 'bar'),
                array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
                array('foo' => 'bar'),
                '->parse() parses long options with a default value'
            ),
            array(
                array('--foo' => null),
                array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
                array('foo' => 'default'),
                '->parse() parses long options with a default value'
            ),
            array(
                array('-f' => 'bar'),
                array(new InputOption('foo', 'f')),
                array('foo' => 'bar'),
                '->parse() parses short options'
            )
        );
    }

    /**
     * @dataProvider provideInvalidInput
     */
    public function testParseInvalidInput($parameters, $definition, $expectedExceptionMessage)
    {
        $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage);

        new ArrayInput($parameters, $definition);
    }

    public function provideInvalidInput()
    {
        return array(
            array(
                array('foo' => 'foo'),
                new InputDefinition(array(new InputArgument('name'))),
                'The "foo" argument does not exist.'
            ),
            array(
                array('--foo' => null),
                new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
                'The "--foo" option requires a value.'
            ),
            array(
                array('--foo' => 'foo'),
                new InputDefinition(),
                'The "--foo" option does not exist.'
            ),
            array(
                array('-o' => 'foo'),
                new InputDefinition(),
                'The "-o" option does not exist.'
            )
        );
    }

    public function testToString()
    {
        $input = new ArrayInput(array('-f' => null, '-b' => 'bar', '--foo' => 'b a z', '--lala' => null, 'test' => 'Foo', 'test2' => "A\nB'C"));
        $this->assertEquals('-f -b=bar --foo='.escapeshellarg('b a z').' --lala Foo '.escapeshellarg("A\nB'C"), (string) $input);
    }
}
PKE1[KU�#�#AConsole/Symfony/Component/Console/Tests/Input/InputOptionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\InputOption;

class InputOptionTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $option = new InputOption('foo');
        $this->assertEquals('foo', $option->getName(), '__construct() takes a name as its first argument');
        $option = new InputOption('--foo');
        $this->assertEquals('foo', $option->getName(), '__construct() removes the leading -- of the option name');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.
     */
    public function testArrayModeWithoutValue()
    {
        new InputOption('foo', 'f', InputOption::VALUE_IS_ARRAY);
    }

    public function testShortcut()
    {
        $option = new InputOption('foo', 'f');
        $this->assertEquals('f', $option->getShortcut(), '__construct() can take a shortcut as its second argument');
        $option = new InputOption('foo', '-f|-ff|fff');
        $this->assertEquals('f|ff|fff', $option->getShortcut(), '__construct() removes the leading - of the shortcuts');
        $option = new InputOption('foo', array('f', 'ff', '-fff'));
        $this->assertEquals('f|ff|fff', $option->getShortcut(), '__construct() removes the leading - of the shortcuts');
        $option = new InputOption('foo');
        $this->assertNull($option->getShortcut(), '__construct() makes the shortcut null by default');
    }

    public function testModes()
    {
        $option = new InputOption('foo', 'f');
        $this->assertFalse($option->acceptValue(), '__construct() gives a "InputOption::VALUE_NONE" mode by default');
        $this->assertFalse($option->isValueRequired(), '__construct() gives a "InputOption::VALUE_NONE" mode by default');
        $this->assertFalse($option->isValueOptional(), '__construct() gives a "InputOption::VALUE_NONE" mode by default');

        $option = new InputOption('foo', 'f', null);
        $this->assertFalse($option->acceptValue(), '__construct() can take "InputOption::VALUE_NONE" as its mode');
        $this->assertFalse($option->isValueRequired(), '__construct() can take "InputOption::VALUE_NONE" as its mode');
        $this->assertFalse($option->isValueOptional(), '__construct() can take "InputOption::VALUE_NONE" as its mode');

        $option = new InputOption('foo', 'f', InputOption::VALUE_NONE);
        $this->assertFalse($option->acceptValue(), '__construct() can take "InputOption::VALUE_NONE" as its mode');
        $this->assertFalse($option->isValueRequired(), '__construct() can take "InputOption::VALUE_NONE" as its mode');
        $this->assertFalse($option->isValueOptional(), '__construct() can take "InputOption::VALUE_NONE" as its mode');

        $option = new InputOption('foo', 'f', InputOption::VALUE_REQUIRED);
        $this->assertTrue($option->acceptValue(), '__construct() can take "InputOption::VALUE_REQUIRED" as its mode');
        $this->assertTrue($option->isValueRequired(), '__construct() can take "InputOption::VALUE_REQUIRED" as its mode');
        $this->assertFalse($option->isValueOptional(), '__construct() can take "InputOption::VALUE_REQUIRED" as its mode');

        $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL);
        $this->assertTrue($option->acceptValue(), '__construct() can take "InputOption::VALUE_OPTIONAL" as its mode');
        $this->assertFalse($option->isValueRequired(), '__construct() can take "InputOption::VALUE_OPTIONAL" as its mode');
        $this->assertTrue($option->isValueOptional(), '__construct() can take "InputOption::VALUE_OPTIONAL" as its mode');
    }

    /**
     * @dataProvider provideInvalidModes
     */
    public function testInvalidModes($mode)
    {
        $this->setExpectedException('InvalidArgumentException', sprintf('Option mode "%s" is not valid.', $mode));

        new InputOption('foo', 'f', $mode);
    }

    public function provideInvalidModes()
    {
        return array(
            array('ANOTHER_ONE'),
            array(-1)
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testEmptyNameIsInvalid()
    {
        new InputOption('');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testDoubleDashNameIsInvalid()
    {
        new InputOption('--');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSingleDashOptionIsInvalid()
    {
        new InputOption('foo', '-');
    }

    public function testIsArray()
    {
        $option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY);
        $this->assertTrue($option->isArray(), '->isArray() returns true if the option can be an array');
        $option = new InputOption('foo', null, InputOption::VALUE_NONE);
        $this->assertFalse($option->isArray(), '->isArray() returns false if the option can not be an array');
    }

    public function testGetDescription()
    {
        $option = new InputOption('foo', 'f', null, 'Some description');
        $this->assertEquals('Some description', $option->getDescription(), '->getDescription() returns the description message');
    }

    public function testGetDefault()
    {
        $option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL, '', 'default');
        $this->assertEquals('default', $option->getDefault(), '->getDefault() returns the default value');

        $option = new InputOption('foo', null, InputOption::VALUE_REQUIRED, '', 'default');
        $this->assertEquals('default', $option->getDefault(), '->getDefault() returns the default value');

        $option = new InputOption('foo', null, InputOption::VALUE_REQUIRED);
        $this->assertNull($option->getDefault(), '->getDefault() returns null if no default value is configured');

        $option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY);
        $this->assertEquals(array(), $option->getDefault(), '->getDefault() returns an empty array if option is an array');

        $option = new InputOption('foo', null, InputOption::VALUE_NONE);
        $this->assertFalse($option->getDefault(), '->getDefault() returns false if the option does not take a value');
    }

    public function testSetDefault()
    {
        $option = new InputOption('foo', null, InputOption::VALUE_REQUIRED, '', 'default');
        $option->setDefault(null);
        $this->assertNull($option->getDefault(), '->setDefault() can reset the default value by passing null');
        $option->setDefault('another');
        $this->assertEquals('another', $option->getDefault(), '->setDefault() changes the default value');

        $option = new InputOption('foo', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY);
        $option->setDefault(array(1, 2));
        $this->assertEquals(array(1, 2), $option->getDefault(), '->setDefault() changes the default value');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage Cannot set a default value when using InputOption::VALUE_NONE mode.
     */
    public function testDefaultValueWithValueNoneMode()
    {
        $option = new InputOption('foo', 'f', InputOption::VALUE_NONE);
        $option->setDefault('default');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage A default value for an array option must be an array.
     */
    public function testDefaultValueWithIsArrayMode()
    {
        $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY);
        $option->setDefault('default');
    }

    public function testEquals()
    {
        $option = new InputOption('foo', 'f', null, 'Some description');
        $option2 = new InputOption('foo', 'f', null, 'Alternative description');
        $this->assertTrue($option->equals($option2));

        $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, 'Some description');
        $option2 = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, 'Some description', true);
        $this->assertFalse($option->equals($option2));

        $option = new InputOption('foo', 'f', null, 'Some description');
        $option2 = new InputOption('bar', 'f', null, 'Some description');
        $this->assertFalse($option->equals($option2));

        $option = new InputOption('foo', 'f', null, 'Some description');
        $option2 = new InputOption('foo', '', null, 'Some description');
        $this->assertFalse($option->equals($option2));

        $option = new InputOption('foo', 'f', null, 'Some description');
        $option2 = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, 'Some description');
        $this->assertFalse($option->equals($option2));
    }
}
PKE1[F�5��CConsole/Symfony/Component/Console/Tests/Input/InputArgumentTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Input;

use Symfony\Component\Console\Input\InputArgument;

class InputArgumentTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $argument = new InputArgument('foo');
        $this->assertEquals('foo', $argument->getName(), '__construct() takes a name as its first argument');
    }

    public function testModes()
    {
        $argument = new InputArgument('foo');
        $this->assertFalse($argument->isRequired(), '__construct() gives a "InputArgument::OPTIONAL" mode by default');

        $argument = new InputArgument('foo', null);
        $this->assertFalse($argument->isRequired(), '__construct() can take "InputArgument::OPTIONAL" as its mode');

        $argument = new InputArgument('foo', InputArgument::OPTIONAL);
        $this->assertFalse($argument->isRequired(), '__construct() can take "InputArgument::OPTIONAL" as its mode');

        $argument = new InputArgument('foo', InputArgument::REQUIRED);
        $this->assertTrue($argument->isRequired(), '__construct() can take "InputArgument::REQUIRED" as its mode');
    }

    /**
     * @dataProvider provideInvalidModes
     */
    public function testInvalidModes($mode)
    {
        $this->setExpectedException('InvalidArgumentException', sprintf('Argument mode "%s" is not valid.', $mode));

        new InputArgument('foo', $mode);
    }

    public function provideInvalidModes()
    {
        return array(
            array('ANOTHER_ONE'),
            array(-1)
        );
    }

    public function testIsArray()
    {
        $argument = new InputArgument('foo', InputArgument::IS_ARRAY);
        $this->assertTrue($argument->isArray(), '->isArray() returns true if the argument can be an array');
        $argument = new InputArgument('foo', InputArgument::OPTIONAL | InputArgument::IS_ARRAY);
        $this->assertTrue($argument->isArray(), '->isArray() returns true if the argument can be an array');
        $argument = new InputArgument('foo', InputArgument::OPTIONAL);
        $this->assertFalse($argument->isArray(), '->isArray() returns false if the argument can not be an array');
    }

    public function testGetDescription()
    {
        $argument = new InputArgument('foo', null, 'Some description');
        $this->assertEquals('Some description', $argument->getDescription(), '->getDescription() return the message description');
    }

    public function testGetDefault()
    {
        $argument = new InputArgument('foo', InputArgument::OPTIONAL, '', 'default');
        $this->assertEquals('default', $argument->getDefault(), '->getDefault() return the default value');
    }

    public function testSetDefault()
    {
        $argument = new InputArgument('foo', InputArgument::OPTIONAL, '', 'default');
        $argument->setDefault(null);
        $this->assertNull($argument->getDefault(), '->setDefault() can reset the default value by passing null');
        $argument->setDefault('another');
        $this->assertEquals('another', $argument->getDefault(), '->setDefault() changes the default value');

        $argument = new InputArgument('foo', InputArgument::OPTIONAL | InputArgument::IS_ARRAY);
        $argument->setDefault(array(1, 2));
        $this->assertEquals(array(1, 2), $argument->getDefault(), '->setDefault() changes the default value');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage Cannot set a default value except for InputArgument::OPTIONAL mode.
     */
    public function testSetDefaultWithRequiredArgument()
    {
        $argument = new InputArgument('foo', InputArgument::REQUIRED);
        $argument->setDefault('default');
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage A default value for an array argument must be an array.
     */
    public function testSetDefaultWithArrayArgument()
    {
        $argument = new InputArgument('foo', InputArgument::IS_ARRAY);
        $argument->setDefault('default');
    }
}
PKE1[��Ĕ���;Console/Symfony/Component/Console/Tests/ApplicationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ApplicationTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
        require_once self::$fixturesPath.'/FooCommand.php';
        require_once self::$fixturesPath.'/Foo1Command.php';
        require_once self::$fixturesPath.'/Foo2Command.php';
        require_once self::$fixturesPath.'/Foo3Command.php';
        require_once self::$fixturesPath.'/Foo4Command.php';
        require_once self::$fixturesPath.'/Foo5Command.php';
        require_once self::$fixturesPath.'/FoobarCommand.php';
        require_once self::$fixturesPath.'/BarBucCommand.php';
    }

    protected function normalizeLineBreaks($text)
    {
        return str_replace(PHP_EOL, "\n", $text);
    }

    /**
     * Replaces the dynamic placeholders of the command help text with a static version.
     * The placeholder %command.full_name% includes the script path that is not predictable
     * and can not be tested against.
     */
    protected function ensureStaticCommandHelp(Application $application)
    {
        foreach ($application->all() as $command) {
            $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp()));
        }
    }

    public function testConstructor()
    {
        $application = new Application('foo', 'bar');
        $this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
        $this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument');
        $this->assertEquals(array('help', 'list'), array_keys($application->all()), '__construct() registered the help and list commands by default');
    }

    public function testSetGetName()
    {
        $application = new Application();
        $application->setName('foo');
        $this->assertEquals('foo', $application->getName(), '->setName() sets the name of the application');
    }

    public function testSetGetVersion()
    {
        $application = new Application();
        $application->setVersion('bar');
        $this->assertEquals('bar', $application->getVersion(), '->setVersion() sets the version of the application');
    }

    public function testGetLongVersion()
    {
        $application = new Application('foo', 'bar');
        $this->assertEquals('<info>foo</info> version <comment>bar</comment>', $application->getLongVersion(), '->getLongVersion() returns the long version of the application');
    }

    public function testHelp()
    {
        $application = new Application();
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_gethelp.txt', $this->normalizeLineBreaks($application->getHelp()), '->setHelp() returns a help message');
    }

    public function testAll()
    {
        $application = new Application();
        $commands = $application->all();
        $this->assertInstanceOf('Symfony\\Component\\Console\\Command\\HelpCommand', $commands['help'], '->all() returns the registered commands');

        $application->add(new \FooCommand());
        $commands = $application->all('foo');
        $this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
    }

    public function testRegister()
    {
        $application = new Application();
        $command = $application->register('foo');
        $this->assertEquals('foo', $command->getName(), '->register() registers a new command');
    }

    public function testAdd()
    {
        $application = new Application();
        $application->add($foo = new \FooCommand());
        $commands = $application->all();
        $this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command');

        $application = new Application();
        $application->addCommands(array($foo = new \FooCommand(), $foo1 = new \Foo1Command()));
        $commands = $application->all();
        $this->assertEquals(array($foo, $foo1), array($commands['foo:bar'], $commands['foo:bar1']), '->addCommands() registers an array of commands');
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.
     */
    public function testAddCommandWithEmptyConstructor()
    {
        $application = new Application();
        $application->add(new \Foo5Command());
    }

    public function testHasGet()
    {
        $application = new Application();
        $this->assertTrue($application->has('list'), '->has() returns true if a named command is registered');
        $this->assertFalse($application->has('afoobar'), '->has() returns false if a named command is not registered');

        $application->add($foo = new \FooCommand());
        $this->assertTrue($application->has('afoobar'), '->has() returns true if an alias is registered');
        $this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
        $this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');

        $application = new Application();
        $application->add($foo = new \FooCommand());
        // simulate --help
        $r = new \ReflectionObject($application);
        $p = $r->getProperty('wantHelps');
        $p->setAccessible(true);
        $p->setValue($application, true);
        $command = $application->get('foo:bar');
        $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $command, '->get() returns the help command if --help is provided as the input');
    }

    public function testSilentHelp()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $tester = new ApplicationTester($application);
        $tester->run(array('-h' => true, '-q' => true), array('decorated' => false));

        $this->assertEmpty($tester->getDisplay(true));
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The command "foofoo" does not exist.
     */
    public function testGetInvalidCommand()
    {
        $application = new Application();
        $application->get('foofoo');
    }

    public function testGetNamespaces()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $this->assertEquals(array('foo'), $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
    }

    public function testFindNamespace()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
        $this->assertEquals('foo', $application->findNamespace('f'), '->findNamespace() finds a namespace given an abbreviation');
        $application->add(new \Foo2Command());
        $this->assertEquals('foo', $application->findNamespace('foo'), '->findNamespace() returns the given namespace if it exists');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The namespace "f" is ambiguous (foo, foo1).
     */
    public function testFindAmbiguousNamespace()
    {
        $application = new Application();
        $application->add(new \BarBucCommand());
        $application->add(new \FooCommand());
        $application->add(new \Foo2Command());
        $application->findNamespace('f');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage There are no commands defined in the "bar" namespace.
     */
    public function testFindInvalidNamespace()
    {
        $application = new Application();
        $application->findNamespace('bar');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage Command "foo1" is not defined
     */
    public function testFindUniqueNameButNamespaceName()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $application->add(new \Foo2Command());

        $application->find($commandName = 'foo1');
    }

    public function testFind()
    {
        $application = new Application();
        $application->add(new \FooCommand());

        $this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists');
        $this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists');
        $this->assertInstanceOf('FooCommand', $application->find('f:bar'), '->find() returns a command if the abbreviation for the namespace exists');
        $this->assertInstanceOf('FooCommand', $application->find('f:b'), '->find() returns a command if the abbreviation for the namespace and the command name exist');
        $this->assertInstanceOf('FooCommand', $application->find('a'), '->find() returns a command if the abbreviation exists for an alias');
    }

    /**
     * @dataProvider provideAmbiguousAbbreviations
     */
    public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
    {
        $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage);

        $application = new Application();
        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $application->add(new \Foo2Command());

        $application->find($abbreviation);
    }

    public function provideAmbiguousAbbreviations()
    {
        return array(
            array('f', 'Command "f" is not defined.'),
            array('a', 'Command "a" is ambiguous (afoobar, afoobar1 and 1 more).'),
            array('foo:b', 'Command "foo:b" is ambiguous (foo:bar, foo:bar1 and 1 more).')
        );
    }

    public function testFindCommandEqualNamespace()
    {
        $application = new Application();
        $application->add(new \Foo3Command());
        $application->add(new \Foo4Command());

        $this->assertInstanceOf('Foo3Command', $application->find('foo3:bar'), '->find() returns the good command even if a namespace has same name');
        $this->assertInstanceOf('Foo4Command', $application->find('foo3:bar:toh'), '->find() returns a command even if its namespace equals another command name');
    }

    public function testFindCommandWithAmbiguousNamespacesButUniqueName()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $application->add(new \FoobarCommand());

        $this->assertInstanceOf('FoobarCommand', $application->find('f:f'));
    }

    public function testFindCommandWithMissingNamespace()
    {
        $application = new Application();
        $application->add(new \Foo4Command());

        $this->assertInstanceOf('Foo4Command', $application->find('f::t'));
    }

    /**
     * @dataProvider             provideInvalidCommandNamesSingle
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage Did you mean this
     */
    public function testFindAlternativeExceptionMessageSingle($name)
    {
        $application = new Application();
        $application->add(new \Foo3Command());
        $application->find($name);
    }

    public function provideInvalidCommandNamesSingle()
    {
        return array(
            array('foo3:baR'),
            array('foO3:bar')
        );
    }

    public function testFindAlternativeExceptionMessageMultiple()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $application->add(new \Foo2Command());

        // Command + plural
        try {
            $application->find('foo:baR');
            $this->fail('->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
            $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
            $this->assertRegExp('/foo1:bar/', $e->getMessage());
            $this->assertRegExp('/foo:bar/', $e->getMessage());
        }

        // Namespace + plural
        try {
            $application->find('foo2:bar');
            $this->fail('->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
            $this->assertRegExp('/Did you mean one of these/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
            $this->assertRegExp('/foo1/', $e->getMessage());
        }

        $application->add(new \Foo3Command());
        $application->add(new \Foo4Command());

        // Subnamespace + plural
        try {
            $a = $application->find('foo3:');
            $this->fail('->find() should throw an \InvalidArgumentException if a command is ambiguous because of a subnamespace, with alternatives');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e);
            $this->assertRegExp('/foo3:bar/', $e->getMessage());
            $this->assertRegExp('/foo3:bar:toh/', $e->getMessage());
        }
    }

    public function testFindAlternativeCommands()
    {
        $application = new Application();

        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $application->add(new \Foo2Command());

        try {
            $application->find($commandName = 'Unknown command');
            $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
            $this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, without alternatives');
        }

        // Test if "bar1" command throw an "\InvalidArgumentException" and does not contain
        // "foo:bar" as alternative because "bar1" is too far from "foo:bar"
        try {
            $application->find($commandName = 'bar1');
            $this->fail('->find() throws an \InvalidArgumentException if command does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if command does not exist');
            $this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternatives');
            $this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "afoobar1"');
            $this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, with alternative : "foo:bar1"');
            $this->assertNotRegExp('/foo:bar(?>!1)/', $e->getMessage(), '->find() throws an \InvalidArgumentException if command does not exist, without "foo:bar" alternative');
        }
    }

    public function testFindAlternativeCommandsWithAnAlias()
    {
        $fooCommand = new \FooCommand();
        $fooCommand->setAliases(array('foo2'));

        $application = new Application();
        $application->add($fooCommand);

        $result = $application->find('foo');

        $this->assertSame($fooCommand, $result);
    }

    public function testFindAlternativeNamespace()
    {
        $application = new Application();

        $application->add(new \FooCommand());
        $application->add(new \Foo1Command());
        $application->add(new \Foo2Command());
        $application->add(new \foo3Command());

        try {
            $application->find('Unknown-namespace:Unknown-command');
            $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
            $this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, without alternatives');
        }

        try {
            $application->find('foo2:command');
            $this->fail('->find() throws an \InvalidArgumentException if namespace does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->find() throws an \InvalidArgumentException if namespace does not exist');
            $this->assertRegExp('/There are no commands defined in the "foo2" namespace./', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative');
            $this->assertRegExp('/foo/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo"');
            $this->assertRegExp('/foo1/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo1"');
            $this->assertRegExp('/foo3/', $e->getMessage(), '->find() throws an \InvalidArgumentException if namespace does not exist, with alternative : "foo3"');
        }
    }

    public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
    {
        $application = $this->getMock('Symfony\Component\Console\Application', array('getNamespaces'));
        $application->expects($this->once())
            ->method('getNamespaces')
            ->will($this->returnValue(array('foo:sublong', 'bar:sub')));

        $this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
    }

    public function testSetCatchExceptions()
    {
        $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
        $application->setAutoExit(false);
        $application->expects($this->any())
            ->method('getTerminalWidth')
            ->will($this->returnValue(120));
        $tester = new ApplicationTester($application);

        $application->setCatchExceptions(true);
        $tester->run(array('command' => 'foo'), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');

        $application->setCatchExceptions(false);
        try {
            $tester->run(array('command' => 'foo'), array('decorated' => false));
            $this->fail('->setCatchExceptions() sets the catch exception flag');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag');
            $this->assertEquals('Command "foo" is not defined.', $e->getMessage(), '->setCatchExceptions() sets the catch exception flag');
        }
    }

    public function testAsText()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $this->ensureStaticCommandHelp($application);
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext1.txt', $this->normalizeLineBreaks($application->asText()), '->asText() returns a text representation of the application');
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_astext2.txt', $this->normalizeLineBreaks($application->asText('foo')), '->asText() returns a text representation of the application');
    }

    public function testAsXml()
    {
        $application = new Application();
        $application->add(new \FooCommand());
        $this->ensureStaticCommandHelp($application);
        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml1.txt', $application->asXml(), '->asXml() returns an XML representation of the application');
        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/application_asxml2.txt', $application->asXml('foo'), '->asXml() returns an XML representation of the application');
    }

    public function testRenderException()
    {
        $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
        $application->setAutoExit(false);
        $application->expects($this->any())
            ->method('getTerminalWidth')
            ->will($this->returnValue(120));
        $tester = new ApplicationTester($application);

        $tester->run(array('command' => 'foo'), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->renderException() renders a pretty exception');

        $tester->run(array('command' => 'foo'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
        $this->assertContains('Exception trace', $tester->getDisplay(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');

        $tester->run(array('command' => 'list', '--foo' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getDisplay(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command');

        $application->add(new \Foo3Command());
        $tester = new ApplicationTester($application);
        $tester->run(array('command' => 'foo3:bar'), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');

        $tester->run(array('command' => 'foo3:bar'), array('decorated' => true));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');

        $application = $this->getMock('Symfony\Component\Console\Application', array('getTerminalWidth'));
        $application->setAutoExit(false);
        $application->expects($this->any())
            ->method('getTerminalWidth')
            ->will($this->returnValue(32));
        $tester = new ApplicationTester($application);

        $tester->run(array('command' => 'foo'), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getDisplay(true), '->renderException() wraps messages when they are bigger than the terminal');
    }

    public function testRun()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);
        $application->add($command = new \Foo1Command());
        $_SERVER['argv'] = array('cli.php', 'foo:bar1');

        ob_start();
        $application->run();
        ob_end_clean();

        $this->assertInstanceOf('Symfony\Component\Console\Input\ArgvInput', $command->input, '->run() creates an ArgvInput by default if none is given');
        $this->assertInstanceOf('Symfony\Component\Console\Output\ConsoleOutput', $command->output, '->run() creates a ConsoleOutput by default if none is given');

        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $this->ensureStaticCommandHelp($application);
        $tester = new ApplicationTester($application);

        $tester->run(array(), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');

        $tester->run(array('--help' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');

        $tester->run(array('-h' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');

        $tester->run(array('command' => 'list', '--help' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');

        $tester->run(array('command' => 'list', '-h' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');

        $tester->run(array('--ansi' => true));
        $this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');

        $tester->run(array('--no-ansi' => true));
        $this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');

        $tester->run(array('--version' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');

        $tester->run(array('-V' => true), array('decorated' => false));
        $this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');

        $tester->run(array('command' => 'list', '--quiet' => true));
        $this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');

        $tester->run(array('command' => 'list', '-q' => true));
        $this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');

        $tester->run(array('command' => 'list', '--verbose' => true));
        $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');

        $tester->run(array('command' => 'list', '--verbose' => 1));
        $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');

        $tester->run(array('command' => 'list', '--verbose' => 2));
        $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');

        $tester->run(array('command' => 'list', '--verbose' => 3));
        $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');

        $tester->run(array('command' => 'list', '--verbose' => 4));
        $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');

        $tester->run(array('command' => 'list', '-v' => true));
        $this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');

        $tester->run(array('command' => 'list', '-vv' => true));
        $this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');

        $tester->run(array('command' => 'list', '-vvv' => true));
        $this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');

        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);
        $application->add(new \FooCommand());
        $tester = new ApplicationTester($application);

        $tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false));
        $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');

        $tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false));
        $this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
    }

    /**
     * Issue #9285
     *
     * If the "verbose" option is just before an argument in ArgvInput,
     * an argument value should not be treated as verbosity value.
     * This test will fail with "Not enough arguments." if broken
     */
    public function testVerboseValueNotBreakArguments()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);
        $application->add(new \FooCommand());

        $output = new StreamOutput(fopen('php://memory', 'w', false));

        $input = new ArgvInput(array('cli.php', '-v', 'foo:bar'));
        $application->run($input, $output);

        $input = new ArgvInput(array('cli.php', '--verbose', 'foo:bar'));
        $application->run($input, $output);
    }

    public function testRunReturnsIntegerExitCode()
    {
        $exception = new \Exception('', 4);

        $application = $this->getMock('Symfony\Component\Console\Application', array('doRun'));
        $application->setAutoExit(false);
        $application->expects($this->once())
             ->method('doRun')
             ->will($this->throwException($exception));

        $exitCode = $application->run(new ArrayInput(array()), new NullOutput());

        $this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
    }

    public function testRunReturnsExitCodeOneForExceptionCodeZero()
    {
        $exception = new \Exception('', 0);

        $application = $this->getMock('Symfony\Component\Console\Application', array('doRun'));
        $application->setAutoExit(false);
        $application->expects($this->once())
             ->method('doRun')
             ->will($this->throwException($exception));

        $exitCode = $application->run(new ArrayInput(array()), new NullOutput());

        $this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
    }

    /**
     * @expectedException \LogicException
     * @dataProvider getAddingAlreadySetDefinitionElementData
     */
    public function testAddingAlreadySetDefinitionElementData($def)
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);
        $application
            ->register('foo')
            ->setDefinition(array($def))
            ->setCode(function (InputInterface $input, OutputInterface $output) {})
        ;

        $input = new ArrayInput(array('command' => 'foo'));
        $output = new NullOutput();
        $application->run($input, $output);
    }

    public function getAddingAlreadySetDefinitionElementData()
    {
        return array(
            array(new InputArgument('command', InputArgument::REQUIRED)),
            array(new InputOption('quiet', '', InputOption::VALUE_NONE)),
            array(new InputOption('query', 'q', InputOption::VALUE_NONE)),
        );
    }

    public function testGetDefaultHelperSetReturnsDefaultValues()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $helperSet = $application->getHelperSet();

        $this->assertTrue($helperSet->has('formatter'));
        $this->assertTrue($helperSet->has('dialog'));
        $this->assertTrue($helperSet->has('progress'));
    }

    public function testAddingSingleHelperSetOverwritesDefaultValues()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $application->setHelperSet(new HelperSet(array(new FormatterHelper())));

        $helperSet = $application->getHelperSet();

        $this->assertTrue($helperSet->has('formatter'));

        // no other default helper set should be returned
        $this->assertFalse($helperSet->has('dialog'));
        $this->assertFalse($helperSet->has('progress'));
    }

    public function testOverwritingDefaultHelperSetOverwritesDefaultValues()
    {
        $application = new CustomApplication();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $application->setHelperSet(new HelperSet(array(new FormatterHelper())));

        $helperSet = $application->getHelperSet();

        $this->assertTrue($helperSet->has('formatter'));

        // no other default helper set should be returned
        $this->assertFalse($helperSet->has('dialog'));
        $this->assertFalse($helperSet->has('progress'));
    }

    public function testGetDefaultInputDefinitionReturnsDefaultValues()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $inputDefinition = $application->getDefinition();

        $this->assertTrue($inputDefinition->hasArgument('command'));

        $this->assertTrue($inputDefinition->hasOption('help'));
        $this->assertTrue($inputDefinition->hasOption('quiet'));
        $this->assertTrue($inputDefinition->hasOption('verbose'));
        $this->assertTrue($inputDefinition->hasOption('version'));
        $this->assertTrue($inputDefinition->hasOption('ansi'));
        $this->assertTrue($inputDefinition->hasOption('no-ansi'));
        $this->assertTrue($inputDefinition->hasOption('no-interaction'));
    }

    public function testOverwritingDefaultInputDefinitionOverwritesDefaultValues()
    {
        $application = new CustomApplication();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $inputDefinition = $application->getDefinition();

        // check whether the default arguments and options are not returned any more
        $this->assertFalse($inputDefinition->hasArgument('command'));

        $this->assertFalse($inputDefinition->hasOption('help'));
        $this->assertFalse($inputDefinition->hasOption('quiet'));
        $this->assertFalse($inputDefinition->hasOption('verbose'));
        $this->assertFalse($inputDefinition->hasOption('version'));
        $this->assertFalse($inputDefinition->hasOption('ansi'));
        $this->assertFalse($inputDefinition->hasOption('no-ansi'));
        $this->assertFalse($inputDefinition->hasOption('no-interaction'));

        $this->assertTrue($inputDefinition->hasOption('custom'));
    }

    public function testSettingCustomInputDefinitionOverwritesDefaultValues()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))));

        $inputDefinition = $application->getDefinition();

        // check whether the default arguments and options are not returned any more
        $this->assertFalse($inputDefinition->hasArgument('command'));

        $this->assertFalse($inputDefinition->hasOption('help'));
        $this->assertFalse($inputDefinition->hasOption('quiet'));
        $this->assertFalse($inputDefinition->hasOption('verbose'));
        $this->assertFalse($inputDefinition->hasOption('version'));
        $this->assertFalse($inputDefinition->hasOption('ansi'));
        $this->assertFalse($inputDefinition->hasOption('no-ansi'));
        $this->assertFalse($inputDefinition->hasOption('no-interaction'));

        $this->assertTrue($inputDefinition->hasOption('custom'));
    }

    public function testRunWithDispatcher()
    {
        $application = new Application();
        $application->setAutoExit(false);
        $application->setDispatcher($this->getDispatcher());

        $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
            $output->write('foo.');
        });

        $tester = new ApplicationTester($application);
        $tester->run(array('command' => 'foo'));
        $this->assertEquals('before.foo.after.', $tester->getDisplay());
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage caught
     */
    public function testRunWithExceptionAndDispatcher()
    {
        $application = new Application();
        $application->setDispatcher($this->getDispatcher());
        $application->setAutoExit(false);
        $application->setCatchExceptions(false);

        $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
            throw new \RuntimeException('foo');
        });

        $tester = new ApplicationTester($application);
        $tester->run(array('command' => 'foo'));
    }

    public function testRunDispatchesAllEventsWithException()
    {
        $application = new Application();
        $application->setDispatcher($this->getDispatcher());
        $application->setAutoExit(false);

        $application->register('foo')->setCode(function (InputInterface $input, OutputInterface $output) {
            $output->write('foo.');

            throw new \RuntimeException('foo');
        });

        $tester = new ApplicationTester($application);
        $tester->run(array('command' => 'foo'));
        $this->assertContains('before.foo.after.caught.', $tester->getDisplay());
    }

    public function testTerminalDimensions()
    {
        $application = new Application();
        $originalDimensions = $application->getTerminalDimensions();
        $this->assertCount(2, $originalDimensions);

        $width = 80;
        if ($originalDimensions[0] == $width) {
            $width = 100;
        }

        $application->setTerminalDimensions($width, 80);
        $this->assertSame(array($width, 80), $application->getTerminalDimensions());
    }

    protected function getDispatcher()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener('console.command', function (ConsoleCommandEvent $event) {
            $event->getOutput()->write('before.');
        });
        $dispatcher->addListener('console.terminate', function (ConsoleTerminateEvent $event) {
            $event->getOutput()->write('after.');

            $event->setExitCode(128);
        });
        $dispatcher->addListener('console.exception', function (ConsoleExceptionEvent $event) {
            $event->getOutput()->writeln('caught.');

            $event->setException(new \LogicException('caught.', $event->getExitCode(), $event->getException()));
        });

        return $dispatcher;
    }
}

class CustomApplication extends Application
{
    /**
     * Overwrites the default input definition.
     *
     * @return InputDefinition An InputDefinition instance
     */
    protected function getDefaultInputDefinition()
    {
        return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')));
    }

    /**
     * Gets the default helper set with the helpers that should always be available.
     *
     * @return HelperSet A HelperSet instance
     */
    protected function getDefaultHelperSet()
    {
        return new HelperSet(array(new FormatterHelper()));
    }
}
PKE1[�r�HwwNConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Formatter;

use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class OutputFormatterStyleTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $style = new OutputFormatterStyle('green', 'black', array('bold', 'underscore'));
        $this->assertEquals("\033[32;40;1;4mfoo\033[0m", $style->apply('foo'));

        $style = new OutputFormatterStyle('red', null, array('blink'));
        $this->assertEquals("\033[31;5mfoo\033[0m", $style->apply('foo'));

        $style = new OutputFormatterStyle(null, 'white');
        $this->assertEquals("\033[47mfoo\033[0m", $style->apply('foo'));
    }

    public function testForeground()
    {
        $style = new OutputFormatterStyle();

        $style->setForeground('black');
        $this->assertEquals("\033[30mfoo\033[0m", $style->apply('foo'));

        $style->setForeground('blue');
        $this->assertEquals("\033[34mfoo\033[0m", $style->apply('foo'));

        $this->setExpectedException('InvalidArgumentException');
        $style->setForeground('undefined-color');
    }

    public function testBackground()
    {
        $style = new OutputFormatterStyle();

        $style->setBackground('black');
        $this->assertEquals("\033[40mfoo\033[0m", $style->apply('foo'));

        $style->setBackground('yellow');
        $this->assertEquals("\033[43mfoo\033[0m", $style->apply('foo'));

        $this->setExpectedException('InvalidArgumentException');
        $style->setBackground('undefined-color');
    }

    public function testOptions()
    {
        $style = new OutputFormatterStyle();

        $style->setOptions(array('reverse', 'conceal'));
        $this->assertEquals("\033[7;8mfoo\033[0m", $style->apply('foo'));

        $style->setOption('bold');
        $this->assertEquals("\033[7;8;1mfoo\033[0m", $style->apply('foo'));

        $style->unsetOption('reverse');
        $this->assertEquals("\033[8;1mfoo\033[0m", $style->apply('foo'));

        $style->setOption('bold');
        $this->assertEquals("\033[8;1mfoo\033[0m", $style->apply('foo'));

        $style->setOptions(array('bold'));
        $this->assertEquals("\033[1mfoo\033[0m", $style->apply('foo'));

        try {
            $style->setOption('foo');
            $this->fail('->setOption() throws an \InvalidArgumentException when the option does not exist in the available options');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->setOption() throws an \InvalidArgumentException when the option does not exist in the available options');
            $this->assertContains('Invalid option specified: "foo"', $e->getMessage(), '->setOption() throws an \InvalidArgumentException when the option does not exist in the available options');
        }

        try {
            $style->unsetOption('foo');
            $this->fail('->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options');
            $this->assertContains('Invalid option specified: "foo"', $e->getMessage(), '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options');
        }
    }
}
PKE1[� R�wwSConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Formatter;

use Symfony\Component\Console\Formatter\OutputFormatterStyleStack;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class OutputFormatterStyleStackTest extends \PHPUnit_Framework_TestCase
{
    public function testPush()
    {
        $stack = new OutputFormatterStyleStack();
        $stack->push($s1 = new OutputFormatterStyle('white', 'black'));
        $stack->push($s2 = new OutputFormatterStyle('yellow', 'blue'));

        $this->assertEquals($s2, $stack->getCurrent());

        $stack->push($s3 = new OutputFormatterStyle('green', 'red'));

        $this->assertEquals($s3, $stack->getCurrent());
    }

    public function testPop()
    {
        $stack = new OutputFormatterStyleStack();
        $stack->push($s1 = new OutputFormatterStyle('white', 'black'));
        $stack->push($s2 = new OutputFormatterStyle('yellow', 'blue'));

        $this->assertEquals($s2, $stack->pop());
        $this->assertEquals($s1, $stack->pop());
    }

    public function testPopEmpty()
    {
        $stack = new OutputFormatterStyleStack();
        $style = new OutputFormatterStyle();

        $this->assertEquals($style, $stack->pop());
    }

    public function testPopNotLast()
    {
        $stack = new OutputFormatterStyleStack();
        $stack->push($s1 = new OutputFormatterStyle('white', 'black'));
        $stack->push($s2 = new OutputFormatterStyle('yellow', 'blue'));
        $stack->push($s3 = new OutputFormatterStyle('green', 'red'));

        $this->assertEquals($s2, $stack->pop($s2));
        $this->assertEquals($s1, $stack->pop());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidPop()
    {
        $stack = new OutputFormatterStyleStack();
        $stack->push(new OutputFormatterStyle('white', 'black'));
        $stack->pop(new OutputFormatterStyle('yellow', 'blue'));
    }
}
PKE1[]6\���IConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Formatter;

use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class OutputFormatterTest extends \PHPUnit_Framework_TestCase
{
    public function testEmptyTag()
    {
        $formatter = new OutputFormatter(true);
        $this->assertEquals("foo<>bar", $formatter->format('foo<>bar'));
    }

    public function testLGCharEscaping()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("foo<bar", $formatter->format('foo\\<bar'));
        $this->assertEquals("<info>some info</info>", $formatter->format('\\<info>some info\\</info>'));
        $this->assertEquals("\\<info>some info\\</info>", OutputFormatter::escape('<info>some info</info>'));

        $this->assertEquals(
            "\033[33mSymfony\\Component\\Console does work very well!\033[0m",
            $formatter->format('<comment>Symfony\Component\Console does work very well!</comment>')
        );
    }

    public function testBundledStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertTrue($formatter->hasStyle('error'));
        $this->assertTrue($formatter->hasStyle('info'));
        $this->assertTrue($formatter->hasStyle('comment'));
        $this->assertTrue($formatter->hasStyle('question'));

        $this->assertEquals(
            "\033[37;41msome error\033[0m",
            $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "\033[32msome info\033[0m",
            $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "\033[33msome comment\033[0m",
            $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "\033[30;46msome question\033[0m",
            $formatter->format('<question>some question</question>')
        );
    }

    public function testNestedStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41msome \033[0m\033[32msome info\033[0m\033[37;41m error\033[0m",
            $formatter->format('<error>some <info>some info</info> error</error>')
        );
    }

    public function testAdjacentStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41msome error\033[0m\033[32msome info\033[0m",
            $formatter->format('<error>some error</error><info>some info</info>')
        );
    }

    public function testStyleMatchingNotGreedy()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "(\033[32m>=2.0,<2.3\033[0m)",
            $formatter->format('(<info>>=2.0,<2.3</info>)')
        );
    }

    public function testStyleEscaping()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "(\033[32mz>=2.0,<a2.3\033[0m)",
            $formatter->format('(<info>'.$formatter->escape('z>=2.0,<a2.3').'</info>)')
        );
    }

    public function testDeepNestedStyles()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(
            "\033[37;41merror\033[0m\033[32minfo\033[0m\033[33mcomment\033[0m\033[37;41merror\033[0m",
            $formatter->format('<error>error<info>info<comment>comment</info>error</error>')
        );
    }

    public function testNewStyle()
    {
        $formatter = new OutputFormatter(true);

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('test', $style);

        $this->assertEquals($style, $formatter->getStyle('test'));
        $this->assertNotEquals($style, $formatter->getStyle('info'));

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('b', $style);

        $this->assertEquals("\033[34;47msome \033[0m\033[34;47mcustom\033[0m\033[34;47m msg\033[0m", $formatter->format('<test>some <b>custom</b> msg</test>'));
    }

    public function testRedefineStyle()
    {
        $formatter = new OutputFormatter(true);

        $style = new OutputFormatterStyle('blue', 'white');
        $formatter->setStyle('info', $style);

        $this->assertEquals("\033[34;47msome custom msg\033[0m", $formatter->format('<info>some custom msg</info>'));
    }

    public function testInlineStyle()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("\033[34;41msome text\033[0m", $formatter->format('<fg=blue;bg=red>some text</>'));
        $this->assertEquals("\033[34;41msome text\033[0m", $formatter->format('<fg=blue;bg=red>some text</fg=blue;bg=red>'));
    }

    public function testNonStyleTag()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals("\033[32msome \033[0m\033[32m<tag>\033[0m\033[32m styled \033[0m\033[32m<p>\033[0m\033[32msingle-char tag\033[0m\033[32m</p>\033[0m", $formatter->format('<info>some <tag> styled <p>single-char tag</p></info>'));
    }

    public function testFormatLongString()
    {
        $formatter = new OutputFormatter(true);
        $long = str_repeat("\\", 14000);
        $this->assertEquals("\033[37;41msome error\033[0m".$long, $formatter->format('<error>some error</error>'.$long));
    }

    public function testNotDecoratedFormatter()
    {
        $formatter = new OutputFormatter(false);

        $this->assertTrue($formatter->hasStyle('error'));
        $this->assertTrue($formatter->hasStyle('info'));
        $this->assertTrue($formatter->hasStyle('comment'));
        $this->assertTrue($formatter->hasStyle('question'));

        $this->assertEquals(
            "some error", $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "some info", $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "some comment", $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "some question", $formatter->format('<question>some question</question>')
        );

        $formatter->setDecorated(true);

        $this->assertEquals(
            "\033[37;41msome error\033[0m", $formatter->format('<error>some error</error>')
        );
        $this->assertEquals(
            "\033[32msome info\033[0m", $formatter->format('<info>some info</info>')
        );
        $this->assertEquals(
            "\033[33msome comment\033[0m", $formatter->format('<comment>some comment</comment>')
        );
        $this->assertEquals(
            "\033[30;46msome question\033[0m", $formatter->format('<question>some question</question>')
        );
    }

    public function testContentWithLineBreaks()
    {
        $formatter = new OutputFormatter(true);

        $this->assertEquals(<<<EOF
\033[32m
some text\033[0m
EOF
            , $formatter->format(<<<EOF
<info>
some text</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32msome text
\033[0m
EOF
            , $formatter->format(<<<EOF
<info>some text
</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32m
some text
\033[0m
EOF
            , $formatter->format(<<<EOF
<info>
some text
</info>
EOF
        ));

        $this->assertEquals(<<<EOF
\033[32m
some text
more text
\033[0m
EOF
            , $formatter->format(<<<EOF
<info>
some text
more text
</info>
EOF
        ));
    }
}
PKE1[����CConsole/Symfony/Component/Console/Tests/Output/StreamOutputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Output;

use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Output\StreamOutput;

class StreamOutputTest extends \PHPUnit_Framework_TestCase
{
    protected $stream;

    protected function setUp()
    {
        $this->stream = fopen('php://memory', 'a', false);
    }

    protected function tearDown()
    {
        $this->stream = null;
    }

    public function testConstructor()
    {
        $output = new StreamOutput($this->stream, Output::VERBOSITY_QUIET, true);
        $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '__construct() takes the verbosity as its first argument');
        $this->assertTrue($output->isDecorated(), '__construct() takes the decorated flag as its second argument');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The StreamOutput class needs a stream as its first argument.
     */
    public function testStreamIsRequired()
    {
        new StreamOutput('foo');
    }

    public function testGetStream()
    {
        $output = new StreamOutput($this->stream);
        $this->assertEquals($this->stream, $output->getStream(), '->getStream() returns the current stream');
    }

    public function testDoWrite()
    {
        $output = new StreamOutput($this->stream);
        $output->writeln('foo');
        rewind($output->getStream());
        $this->assertEquals('foo'.PHP_EOL, stream_get_contents($output->getStream()), '->doWrite() writes to the stream');
    }
}
PKE1[;�!��AConsole/Symfony/Component/Console/Tests/Output/NullOutputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Output;

use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;

class NullOutputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $output = new NullOutput();

        ob_start();
        $output->write('foo');
        $buffer = ob_get_clean();

        $this->assertSame('', $buffer, '->write() does nothing (at least nothing is printed)');
        $this->assertFalse($output->isDecorated(), '->isDecorated() returns false');
    }

    public function testVerbosity()
    {
        $output = new NullOutput();
        $this->assertSame(OutputInterface::VERBOSITY_QUIET, $output->getVerbosity(), '->getVerbosity() returns VERBOSITY_QUIET for NullOutput by default');

        $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
        $this->assertSame(OutputInterface::VERBOSITY_QUIET, $output->getVerbosity(), '->getVerbosity() always returns VERBOSITY_QUIET for NullOutput');
    }
}
PKE1[}�R��DConsole/Symfony/Component/Console/Tests/Output/ConsoleOutputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Output;

use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\Output;

class ConsoleOutputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $output = new ConsoleOutput(Output::VERBOSITY_QUIET, true);
        $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '__construct() takes the verbosity as its first argument');
    }
}
PKF1[�����=Console/Symfony/Component/Console/Tests/Output/OutputTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Output;

use Symfony\Component\Console\Output\Output;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;

class OutputTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $output = new TestOutput(Output::VERBOSITY_QUIET, true);
        $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '__construct() takes the verbosity as its first argument');
        $this->assertTrue($output->isDecorated(), '__construct() takes the decorated flag as its second argument');
    }

    public function testSetIsDecorated()
    {
        $output = new TestOutput();
        $output->setDecorated(true);
        $this->assertTrue($output->isDecorated(), 'setDecorated() sets the decorated flag');
    }

    public function testSetGetVerbosity()
    {
        $output = new TestOutput();
        $output->setVerbosity(Output::VERBOSITY_QUIET);
        $this->assertEquals(Output::VERBOSITY_QUIET, $output->getVerbosity(), '->setVerbosity() sets the verbosity');

        $this->assertTrue($output->isQuiet());
        $this->assertFalse($output->isVerbose());
        $this->assertFalse($output->isVeryVerbose());
        $this->assertFalse($output->isDebug());

        $output->setVerbosity(Output::VERBOSITY_NORMAL);
        $this->assertFalse($output->isQuiet());
        $this->assertFalse($output->isVerbose());
        $this->assertFalse($output->isVeryVerbose());
        $this->assertFalse($output->isDebug());

        $output->setVerbosity(Output::VERBOSITY_VERBOSE);
        $this->assertFalse($output->isQuiet());
        $this->assertTrue($output->isVerbose());
        $this->assertFalse($output->isVeryVerbose());
        $this->assertFalse($output->isDebug());

        $output->setVerbosity(Output::VERBOSITY_VERY_VERBOSE);
        $this->assertFalse($output->isQuiet());
        $this->assertTrue($output->isVerbose());
        $this->assertTrue($output->isVeryVerbose());
        $this->assertFalse($output->isDebug());

        $output->setVerbosity(Output::VERBOSITY_DEBUG);
        $this->assertFalse($output->isQuiet());
        $this->assertTrue($output->isVerbose());
        $this->assertTrue($output->isVeryVerbose());
        $this->assertTrue($output->isDebug());
    }

    public function testWriteWithVerbosityQuiet()
    {
        $output = new TestOutput(Output::VERBOSITY_QUIET);
        $output->writeln('foo');
        $this->assertEquals('', $output->output, '->writeln() outputs nothing if verbosity is set to VERBOSITY_QUIET');
    }

    public function testWriteAnArrayOfMessages()
    {
        $output = new TestOutput();
        $output->writeln(array('foo', 'bar'));
        $this->assertEquals("foo\nbar\n", $output->output, '->writeln() can take an array of messages to output');
    }

    /**
     * @dataProvider provideWriteArguments
     */
    public function testWriteRawMessage($message, $type, $expectedOutput)
    {
        $output = new TestOutput();
        $output->writeln($message, $type);
        $this->assertEquals($expectedOutput, $output->output);
    }

    public function provideWriteArguments()
    {
        return array(
            array('<info>foo</info>', Output::OUTPUT_RAW, "<info>foo</info>\n"),
            array('<info>foo</info>', Output::OUTPUT_PLAIN, "foo\n"),
        );
    }

    public function testWriteWithDecorationTurnedOff()
    {
        $output = new TestOutput();
        $output->setDecorated(false);
        $output->writeln('<info>foo</info>');
        $this->assertEquals("foo\n", $output->output, '->writeln() strips decoration tags if decoration is set to false');
    }

    public function testWriteDecoratedMessage()
    {
        $fooStyle = new OutputFormatterStyle('yellow', 'red', array('blink'));
        $output = new TestOutput();
        $output->getFormatter()->setStyle('FOO', $fooStyle);
        $output->setDecorated(true);
        $output->writeln('<foo>foo</foo>');
        $this->assertEquals("\033[33;41;5mfoo\033[0m\n", $output->output, '->writeln() decorates the output');
    }

    /**
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage Unknown output type given (24)
     */
    public function testWriteWithInvalidOutputType()
    {
        $output = new TestOutput();
        $output->writeln('<foo>foo</foo>', 24);
    }

    public function testWriteWithInvalidStyle()
    {
        $output = new TestOutput();

        $output->clear();
        $output->write('<bar>foo</bar>');
        $this->assertEquals('<bar>foo</bar>', $output->output, '->write() do nothing when a style does not exist');

        $output->clear();
        $output->writeln('<bar>foo</bar>');
        $this->assertEquals("<bar>foo</bar>\n", $output->output, '->writeln() do nothing when a style does not exist');
    }
}

class TestOutput extends Output
{
    public $output = '';

    public function clear()
    {
        $this->output = '';
    }

    protected function doWrite($message, $newline)
    {
        $this->output .= $message.($newline ? "\n" : '');
    }
}
PKF1[gO��
�
FConsole/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Helper;

use Symfony\Component\Console\Helper\FormatterHelper;

class FormatterHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testFormatSection()
    {
        $formatter = new FormatterHelper();

        $this->assertEquals(
            '<info>[cli]</info> Some text to display',
            $formatter->formatSection('cli', 'Some text to display'),
            '::formatSection() formats a message in a section'
        );
    }

    public function testFormatBlock()
    {
        $formatter = new FormatterHelper();

        $this->assertEquals(
            '<error> Some text to display </error>',
            $formatter->formatBlock('Some text to display', 'error'),
            '::formatBlock() formats a message in a block'
        );

        $this->assertEquals(
            '<error> Some text to display </error>'."\n" .
            '<error> foo bar              </error>',
            $formatter->formatBlock(array('Some text to display', 'foo bar'), 'error'),
            '::formatBlock() formats a message in a block'
        );

        $this->assertEquals(
            '<error>                        </error>'."\n" .
            '<error>  Some text to display  </error>'."\n" .
            '<error>                        </error>',
            $formatter->formatBlock('Some text to display', 'error', true),
            '::formatBlock() formats a message in a block'
        );
    }

    public function testFormatBlockWithDiacriticLetters()
    {
        if (!extension_loaded('mbstring')) {
            $this->markTestSkipped('This test requires mbstring to work.');
        }

        $formatter = new FormatterHelper();

        $this->assertEquals(
            '<error>                       </error>'."\n" .
            '<error>  Du texte à afficher  </error>'."\n" .
            '<error>                       </error>',
            $formatter->formatBlock('Du texte à afficher', 'error', true),
            '::formatBlock() formats a message in a block'
        );
    }

    public function testFormatBlockLGEscaping()
    {
        $formatter = new FormatterHelper();

        $this->assertEquals(
            '<error>                            </error>'."\n" .
            '<error>  \<info>some info\</info>  </error>'."\n" .
            '<error>                            </error>',
            $formatter->formatBlock('<info>some info</info>', 'error', true),
            '::formatBlock() escapes \'<\' chars'
        );
    }
}
PKF1[�L��"�"CConsole/Symfony/Component/Console/Tests/Helper/DialogHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Helper;

use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Output\StreamOutput;

class DialogHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testSelect()
    {
        $dialog = new DialogHelper();

        $helperSet = new HelperSet(array(new FormatterHelper()));
        $dialog->setHelperSet($helperSet);

        $heroes = array('Superman', 'Batman', 'Spiderman');

        $dialog->setInputStream($this->getInputStream("\n1\n  1  \nFabien\n1\nFabien\n1\n0,2\n 0 , 2  \n\n\n"));
        $this->assertEquals('2', $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, '2'));
        $this->assertEquals('1', $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes));
        $this->assertEquals('1', $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes));
        $this->assertEquals('1', $dialog->select($output = $this->getOutputStream(), 'What is your favorite superhero?', $heroes, null, false, 'Input "%s" is not a superhero!', false));

        rewind($output->getStream());
        $this->assertContains('Input "Fabien" is not a superhero!', stream_get_contents($output->getStream()));

        try {
            $this->assertEquals('1', $dialog->select($output = $this->getOutputStream(), 'What is your favorite superhero?', $heroes, null, 1));
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals('Value "Fabien" is invalid', $e->getMessage());
        }

        $this->assertEquals(array('1'), $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, null, false, 'Input "%s" is not a superhero!', true));
        $this->assertEquals(array('0', '2'), $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, null, false, 'Input "%s" is not a superhero!', true));
        $this->assertEquals(array('0', '2'), $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, null, false, 'Input "%s" is not a superhero!', true));
        $this->assertEquals(array('0', '1'), $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, '0,1', false, 'Input "%s" is not a superhero!', true));
        $this->assertEquals(array('0', '1'), $dialog->select($this->getOutputStream(), 'What is your favorite superhero?', $heroes, ' 0 , 1 ', false, 'Input "%s" is not a superhero!', true));
    }

    public function testAsk()
    {
        $dialog = new DialogHelper();

        $dialog->setInputStream($this->getInputStream("\n8AM\n"));

        $this->assertEquals('2PM', $dialog->ask($this->getOutputStream(), 'What time is it?', '2PM'));
        $this->assertEquals('8AM', $dialog->ask($output = $this->getOutputStream(), 'What time is it?', '2PM'));

        rewind($output->getStream());
        $this->assertEquals('What time is it?', stream_get_contents($output->getStream()));
    }

    public function testAskWithAutocomplete()
    {
        if (!$this->hasSttyAvailable()) {
            $this->markTestSkipped('`stty` is required to test autocomplete functionality');
        }

        // Acm<NEWLINE>
        // Ac<BACKSPACE><BACKSPACE>s<TAB>Test<NEWLINE>
        // <NEWLINE>
        // <UP ARROW><UP ARROW><NEWLINE>
        // <UP ARROW><UP ARROW><UP ARROW><UP ARROW><UP ARROW><TAB>Test<NEWLINE>
        // <DOWN ARROW><NEWLINE>
        // S<BACKSPACE><BACKSPACE><DOWN ARROW><DOWN ARROW><NEWLINE>
        // F00<BACKSPACE><BACKSPACE>oo<TAB><NEWLINE>
        $inputStream = $this->getInputStream("Acm\nAc\177\177s\tTest\n\n\033[A\033[A\n\033[A\033[A\033[A\033[A\033[A\tTest\n\033[B\nS\177\177\033[B\033[B\nF00\177\177oo\t\n");

        $dialog = new DialogHelper();
        $dialog->setInputStream($inputStream);

        $bundles = array('AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle');

        $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('AsseticBundleTest', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('FrameworkBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('SecurityBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('FooBundleTest', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('AcmeDemoBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('AsseticBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
        $this->assertEquals('FooBundle', $dialog->ask($this->getOutputStream(), 'Please select a bundle', 'FrameworkBundle', $bundles));
    }

    /**
     * @group tty
     */
    public function testAskHiddenResponse()
    {
        if (defined('PHP_WINDOWS_VERSION_BUILD')) {
            $this->markTestSkipped('This test is not supported on Windows');
        }

        $dialog = new DialogHelper();

        $dialog->setInputStream($this->getInputStream("8AM\n"));

        $this->assertEquals('8AM', $dialog->askHiddenResponse($this->getOutputStream(), 'What time is it?'));
    }

    public function testAskConfirmation()
    {
        $dialog = new DialogHelper();

        $dialog->setInputStream($this->getInputStream("\n\n"));
        $this->assertTrue($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?'));
        $this->assertFalse($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?', false));

        $dialog->setInputStream($this->getInputStream("y\nyes\n"));
        $this->assertTrue($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?', false));
        $this->assertTrue($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?', false));

        $dialog->setInputStream($this->getInputStream("n\nno\n"));
        $this->assertFalse($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?', true));
        $this->assertFalse($dialog->askConfirmation($this->getOutputStream(), 'Do you like French fries?', true));
    }

    public function testAskAndValidate()
    {
        $dialog = new DialogHelper();
        $helperSet = new HelperSet(array(new FormatterHelper()));
        $dialog->setHelperSet($helperSet);

        $question ='What color was the white horse of Henry IV?';
        $error = 'This is not a color!';
        $validator = function ($color) use ($error) {
            if (!in_array($color, array('white', 'black'))) {
                throw new \InvalidArgumentException($error);
            }

            return $color;
        };

        $dialog->setInputStream($this->getInputStream("\nblack\n"));
        $this->assertEquals('white', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white'));
        $this->assertEquals('black', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white'));

        $dialog->setInputStream($this->getInputStream("green\nyellow\norange\n"));
        try {
            $this->assertEquals('white', $dialog->askAndValidate($this->getOutputStream(), $question, $validator, 2, 'white'));
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals($error, $e->getMessage());
        }
    }

    public function testNoInteraction()
    {
        $dialog = new DialogHelper();

        $input = new ArrayInput(array());
        $input->setInteractive(false);

        $dialog->setInput($input);

        $this->assertEquals('not yet', $dialog->ask($this->getOutputStream(), 'Do you have a job?', 'not yet'));
    }

    protected function getInputStream($input)
    {
        $stream = fopen('php://memory', 'r+', false);
        fputs($stream, $input);
        rewind($stream);

        return $stream;
    }

    protected function getOutputStream()
    {
        return new StreamOutput(fopen('php://memory', 'r+', false));
    }

    private function hasSttyAvailable()
    {
        exec('stty 2>&1', $output, $exitcode);

        return $exitcode === 0;
    }
}
PKF1[+��vv@Console/Symfony/Component/Console/Tests/Helper/HelperSetTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Helper;

use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Command\Command;

class HelperSetTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::__construct
     */
    public function testConstructor()
    {
        $mock_helper = $this->getGenericMockHelper('fake_helper');
        $helperset = new HelperSet(array('fake_helper_alias' => $mock_helper));

        $this->assertEquals($mock_helper, $helperset->get('fake_helper_alias'), '__construct sets given helper to helpers');
        $this->assertTrue($helperset->has('fake_helper_alias'), '__construct sets helper alias for given helper');
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::set
     */
    public function testSet()
    {
        $helperset = new HelperSet();
        $helperset->set($this->getGenericMockHelper('fake_helper', $helperset));
        $this->assertTrue($helperset->has('fake_helper'), '->set() adds helper to helpers');

        $helperset = new HelperSet();
        $helperset->set($this->getGenericMockHelper('fake_helper_01', $helperset));
        $helperset->set($this->getGenericMockHelper('fake_helper_02', $helperset));
        $this->assertTrue($helperset->has('fake_helper_01'), '->set() will set multiple helpers on consecutive calls');
        $this->assertTrue($helperset->has('fake_helper_02'), '->set() will set multiple helpers on consecutive calls');

        $helperset = new HelperSet();
        $helperset->set($this->getGenericMockHelper('fake_helper', $helperset), 'fake_helper_alias');
        $this->assertTrue($helperset->has('fake_helper'), '->set() adds helper alias when set');
        $this->assertTrue($helperset->has('fake_helper_alias'), '->set() adds helper alias when set');
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::has
     */
    public function testHas()
    {
        $helperset = new HelperSet(array('fake_helper_alias' => $this->getGenericMockHelper('fake_helper')));
        $this->assertTrue($helperset->has('fake_helper'), '->has() finds set helper');
        $this->assertTrue($helperset->has('fake_helper_alias'), '->has() finds set helper by alias');
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::get
     */
    public function testGet()
    {
        $helper_01 = $this->getGenericMockHelper('fake_helper_01');
        $helper_02 = $this->getGenericMockHelper('fake_helper_02');
        $helperset = new HelperSet(array('fake_helper_01_alias' => $helper_01, 'fake_helper_02_alias' => $helper_02));
        $this->assertEquals($helper_01, $helperset->get('fake_helper_01'), '->get() returns correct helper by name');
        $this->assertEquals($helper_01, $helperset->get('fake_helper_01_alias'), '->get() returns correct helper by alias');
        $this->assertEquals($helper_02, $helperset->get('fake_helper_02'), '->get() returns correct helper by name');
        $this->assertEquals($helper_02, $helperset->get('fake_helper_02_alias'), '->get() returns correct helper by alias');

        $helperset = new HelperSet();
        try {
            $helperset->get('foo');
            $this->fail('->get() throws \InvalidArgumentException when helper not found');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws \InvalidArgumentException when helper not found');
            $this->assertContains('The helper "foo" is not defined.', $e->getMessage(), '->get() throws \InvalidArgumentException when helper not found');
        }
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::setCommand
     */
    public function testSetCommand()
    {
        $cmd_01 = new Command('foo');
        $cmd_02 = new Command('bar');

        $helperset = new HelperSet();
        $helperset->setCommand($cmd_01);
        $this->assertEquals($cmd_01, $helperset->getCommand(), '->setCommand() stores given command');

        $helperset = new HelperSet();
        $helperset->setCommand($cmd_01);
        $helperset->setCommand($cmd_02);
        $this->assertEquals($cmd_02, $helperset->getCommand(), '->setCommand() overwrites stored command with consecutive calls');
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::getCommand
     */
    public function testGetCommand()
    {
        $cmd = new Command('foo');
        $helperset = new HelperSet();
        $helperset->setCommand($cmd);
        $this->assertEquals($cmd, $helperset->getCommand(), '->getCommand() retrieves stored command');
    }

    /**
     * @covers \Symfony\Component\Console\Helper\HelperSet::getIterator
     */
    public function testIteration()
    {
        $helperset = new HelperSet();
        $helperset->set($this->getGenericMockHelper('fake_helper_01', $helperset));
        $helperset->set($this->getGenericMockHelper('fake_helper_02', $helperset));

        $helpers = array('fake_helper_01', 'fake_helper_02');
        $i = 0;

        foreach ($helperset as $helper) {
            $this->assertEquals($helpers[$i++], $helper->getName());
        }
    }

   /**
     * Create a generic mock for the helper interface. Optionally check for a call to setHelperSet with a specific
     * helperset instance.
     *
     * @param string    $name
     * @param HelperSet $helperset allows a mock to verify a particular helperset set is being added to the Helper
     */
    private function getGenericMockHelper($name, HelperSet $helperset = null)
    {
        $mock_helper = $this->getMock('\Symfony\Component\Console\Helper\HelperInterface');
        $mock_helper->expects($this->any())
            ->method('getName')
            ->will($this->returnValue($name));

        if ($helperset) {
            $mock_helper->expects($this->any())
                ->method('setHelperSet')
                ->with($this->equalTo($helperset));
        }

        return $mock_helper;
    }
}
PKF1[]_Դ3)3)BConsole/Symfony/Component/Console/Tests/Helper/TableHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Helper;

use Symfony\Component\Console\Helper\TableHelper;
use Symfony\Component\Console\Output\StreamOutput;

class TableHelperTest extends \PHPUnit_Framework_TestCase
{
    protected $stream;

    protected function setUp()
    {
        $this->stream = fopen('php://memory', 'r+');
    }

    protected function tearDown()
    {
        fclose($this->stream);
        $this->stream = null;
    }

    /**
     * @dataProvider testRenderProvider
     */
    public function testRender($headers, $rows, $layout, $expected)
    {
        $table = new TableHelper();
        $table
            ->setHeaders($headers)
            ->setRows($rows)
            ->setLayout($layout)
        ;
        $table->render($output = $this->getOutputStream());

        $this->assertEquals($expected, $this->getOutputContent($output));
    }

    /**
     * @dataProvider testRenderProvider
     */
    public function testRenderAddRows($headers, $rows, $layout, $expected)
    {
        $table = new TableHelper();
        $table
            ->setHeaders($headers)
            ->addRows($rows)
            ->setLayout($layout)
        ;
        $table->render($output = $this->getOutputStream());

        $this->assertEquals($expected, $this->getOutputContent($output));
    }

    /**
     * @dataProvider testRenderProvider
     */
    public function testRenderAddRowsOneByOne($headers, $rows, $layout, $expected)
    {
        $table = new TableHelper();
        $table
            ->setHeaders($headers)
            ->setLayout($layout)
        ;
        foreach ($rows as $row) {
            $table->addRow($row);
        }
        $table->render($output = $this->getOutputStream());

        $this->assertEquals($expected, $this->getOutputContent($output));
    }

    public function testRenderProvider()
    {
        $books = array(
            array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
            array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
            array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
            array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
        );

        return array(
            array(
                array('ISBN', 'Title', 'Author'),
                $books,
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+---------------+--------------------------+------------------+
| ISBN          | Title                    | Author           |
+---------------+--------------------------+------------------+
| 99921-58-10-7 | Divine Comedy            | Dante Alighieri  |
| 9971-5-0210-0 | A Tale of Two Cities     | Charles Dickens  |
| 960-425-059-0 | The Lord of the Rings    | J. R. R. Tolkien |
| 80-902734-1-6 | And Then There Were None | Agatha Christie  |
+---------------+--------------------------+------------------+

TABLE
            ),
            array(
                array('ISBN', 'Title', 'Author'),
                $books,
                TableHelper::LAYOUT_COMPACT,
<<<TABLE
 ISBN          Title                    Author           
 99921-58-10-7 Divine Comedy            Dante Alighieri  
 9971-5-0210-0 A Tale of Two Cities     Charles Dickens  
 960-425-059-0 The Lord of the Rings    J. R. R. Tolkien 
 80-902734-1-6 And Then There Were None Agatha Christie  

TABLE
            ),
            array(
                array('ISBN', 'Title', 'Author'),
                $books,
                TableHelper::LAYOUT_BORDERLESS,
<<<TABLE
 =============== ========================== ================== 
  ISBN            Title                      Author            
 =============== ========================== ================== 
  99921-58-10-7   Divine Comedy              Dante Alighieri   
  9971-5-0210-0   A Tale of Two Cities       Charles Dickens   
  960-425-059-0   The Lord of the Rings      J. R. R. Tolkien  
  80-902734-1-6   And Then There Were None   Agatha Christie   
 =============== ========================== ================== 

TABLE
            ),
            array(
                array('ISBN', 'Title'),
                array(
                    array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
                    array('9971-5-0210-0'),
                    array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
                    array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
                ),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+---------------+--------------------------+------------------+
| ISBN          | Title                    |                  |
+---------------+--------------------------+------------------+
| 99921-58-10-7 | Divine Comedy            | Dante Alighieri  |
| 9971-5-0210-0 |                          |                  |
| 960-425-059-0 | The Lord of the Rings    | J. R. R. Tolkien |
| 80-902734-1-6 | And Then There Were None | Agatha Christie  |
+---------------+--------------------------+------------------+

TABLE
            ),
            array(
                array(),
                array(
                    array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
                    array('9971-5-0210-0'),
                    array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
                    array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
                ),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+---------------+--------------------------+------------------+
| 99921-58-10-7 | Divine Comedy            | Dante Alighieri  |
| 9971-5-0210-0 |                          |                  |
| 960-425-059-0 | The Lord of the Rings    | J. R. R. Tolkien |
| 80-902734-1-6 | And Then There Were None | Agatha Christie  |
+---------------+--------------------------+------------------+

TABLE
            ),
            array(
                array('ISBN', 'Title', 'Author'),
                array(
                    array("99921-58-10-7", "Divine\nComedy", "Dante Alighieri"),
                    array("9971-5-0210-2", "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."),
                    array("9971-5-0210-2", "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."),
                    array("960-425-059-0", "The Lord of the Rings", "J. R. R.\nTolkien"),
                ),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+---------------+----------------------------+-----------------+
| ISBN          | Title                      | Author          |
+---------------+----------------------------+-----------------+
| 99921-58-10-7 | Divine                     | Dante Alighieri |
|               | Comedy                     |                 |
| 9971-5-0210-2 | Harry Potter               | Rowling         |
|               | and the Chamber of Secrets | Joanne K.       |
| 9971-5-0210-2 | Harry Potter               | Rowling         |
|               | and the Chamber of Secrets | Joanne K.       |
| 960-425-059-0 | The Lord of the Rings      | J. R. R.        |
|               |                            | Tolkien         |
+---------------+----------------------------+-----------------+

TABLE
            ),
            array(
                array('ISBN', 'Title'),
                array(),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+------+-------+
| ISBN | Title |
+------+-------+

TABLE
            ),
            array(
                array(),
                array(),
                TableHelper::LAYOUT_DEFAULT,
                '',
            ),
            'Cell text with tags used for Output styling' => array(
                array('ISBN', 'Title', 'Author'),
                array(
                    array('<info>99921-58-10-7</info>', '<error>Divine Comedy</error>', '<fg=blue;bg=white>Dante Alighieri</fg=blue;bg=white>'),
                    array('9971-5-0210-0', 'A Tale of Two Cities', '<info>Charles Dickens</>'),
                ),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+---------------+----------------------+-----------------+
| ISBN          | Title                | Author          |
+---------------+----------------------+-----------------+
| 99921-58-10-7 | Divine Comedy        | Dante Alighieri |
| 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens |
+---------------+----------------------+-----------------+

TABLE
            ),
            'Cell text with tags not used for Output styling' => array(
                array('ISBN', 'Title', 'Author'),
                array(
                    array('<strong>99921-58-10-700</strong>', '<f>Divine Com</f>', 'Dante Alighieri'),
                    array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
                ),
                TableHelper::LAYOUT_DEFAULT,
<<<TABLE
+----------------------------------+----------------------+-----------------+
| ISBN                             | Title                | Author          |
+----------------------------------+----------------------+-----------------+
| <strong>99921-58-10-700</strong> | <f>Divine Com</f>    | Dante Alighieri |
| 9971-5-0210-0                    | A Tale of Two Cities | Charles Dickens |
+----------------------------------+----------------------+-----------------+

TABLE
            ),
        );
    }

    public function testRenderMultiByte()
    {
        if (!function_exists('mb_strlen')) {
            $this->markTestSkipped('The "mbstring" extension is not available');
        }

        $table = new TableHelper();
        $table
            ->setHeaders(array('■■'))
            ->setRows(array(array(1234)))
            ->setLayout(TableHelper::LAYOUT_DEFAULT)
        ;
        $table->render($output = $this->getOutputStream());

        $expected =
<<<TABLE
+------+
| ■■   |
+------+
| 1234 |
+------+

TABLE;

        $this->assertEquals($expected, $this->getOutputContent($output));
    }

    protected function getOutputStream()
    {
        return new StreamOutput($this->stream, StreamOutput::VERBOSITY_NORMAL, false);
    }

    protected function getOutputContent(StreamOutput $output)
    {
        rewind($output->getStream());

        return str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream()));
    }
}
PKF1["
U���EConsole/Symfony/Component/Console/Tests/Helper/ProgressHelperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Helper;

use Symfony\Component\Console\Helper\ProgressHelper;
use Symfony\Component\Console\Output\StreamOutput;

class ProgressHelperTest extends \PHPUnit_Framework_TestCase
{
    public function testAdvance()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream());
        $progress->advance();

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('    1 [->--------------------------]'), stream_get_contents($output->getStream()));
    }

    public function testAdvanceWithStep()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream());
        $progress->advance(5);

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('    5 [----->----------------------]'), stream_get_contents($output->getStream()));
    }

    public function testAdvanceMultipleTimes()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream());
        $progress->advance(3);
        $progress->advance(2);

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('    3 [--->------------------------]').$this->generateOutput('    5 [----->----------------------]'), stream_get_contents($output->getStream()));
    }

    public function testCustomizations()
    {
        $progress = new ProgressHelper();
        $progress->setBarWidth(10);
        $progress->setBarCharacter('_');
        $progress->setEmptyBarCharacter(' ');
        $progress->setProgressCharacter('/');
        $progress->setFormat(' %current%/%max% [%bar%] %percent%%');
        $progress->start($output = $this->getOutputStream(), 10);
        $progress->advance();

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('  1/10 [_/        ]  10%'), stream_get_contents($output->getStream()));
    }

    public function testPercent()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream(), 50);
        $progress->display();
        $progress->advance();
        $progress->advance();

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('  0/50 [>---------------------------]   0%').$this->generateOutput('  1/50 [>---------------------------]   2%').$this->generateOutput('  2/50 [=>--------------------------]   4%'), stream_get_contents($output->getStream()));
    }

    public function testOverwriteWithShorterLine()
    {
        $progress = new ProgressHelper();
        $progress->setFormat(' %current%/%max% [%bar%] %percent%%');
        $progress->start($output = $this->getOutputStream(), 50);
        $progress->display();
        $progress->advance();

        // set shorter format
        $progress->setFormat(' %current%/%max% [%bar%]');
        $progress->advance();

        rewind($output->getStream());
        $this->assertEquals(
            $this->generateOutput('  0/50 [>---------------------------]   0%') .
            $this->generateOutput('  1/50 [>---------------------------]   2%') .
            $this->generateOutput('  2/50 [=>--------------------------]     '),
            stream_get_contents($output->getStream())
        );
    }

    public function testSetCurrentProgress()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream(), 50);
        $progress->display();
        $progress->advance();
        $progress->setCurrent(15);
        $progress->setCurrent(25);

        rewind($output->getStream());
        $this->assertEquals(
            $this->generateOutput('  0/50 [>---------------------------]   0%') .
            $this->generateOutput('  1/50 [>---------------------------]   2%') .
            $this->generateOutput(' 15/50 [========>-------------------]  30%') .
            $this->generateOutput(' 25/50 [==============>-------------]  50%'),
            stream_get_contents($output->getStream())
        );
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage You must start the progress bar
     */
    public function testSetCurrentBeforeStarting()
    {
        $progress = new ProgressHelper();
        $progress->setCurrent(15);
    }

    /**
     * @expectedException        \LogicException
     * @expectedExceptionMessage You can't regress the progress bar
     */
    public function testRegressProgress()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream(), 50);
        $progress->setCurrent(15);
        $progress->setCurrent(10);
    }

    public function testRedrawFrequency()
    {
        $progress = $this->getMock('Symfony\Component\Console\Helper\ProgressHelper', array('display'));
        $progress->expects($this->exactly(4))
                 ->method('display');

        $progress->setRedrawFrequency(2);

        $progress->start($output = $this->getOutputStream(), 6);
        $progress->setCurrent(1);
        $progress->advance(2);
        $progress->advance(2);
        $progress->advance(1);
    }

    public function testMultiByteSupport()
    {
        if (!function_exists('mb_strlen') || (false === $encoding = mb_detect_encoding('■'))) {
            $this->markTestSkipped('The mbstring extension is needed for multi-byte support');
        }

        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream());
        $progress->setBarCharacter('■');
        $progress->advance(3);

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('    3 [■■■>------------------------]'), stream_get_contents($output->getStream()));
    }

    public function testClear()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream(), 50);
        $progress->setCurrent(25);
        $progress->clear();

        rewind($output->getStream());
        $this->assertEquals(
            $this->generateOutput(' 25/50 [==============>-------------]  50%') . $this->generateOutput(''),
            stream_get_contents($output->getStream())
        );
    }

    public function testPercentNotHundredBeforeComplete()
    {
        $progress = new ProgressHelper();
        $progress->start($output = $this->getOutputStream(), 200);
        $progress->display();
        $progress->advance(199);
        $progress->advance();

        rewind($output->getStream());
        $this->assertEquals($this->generateOutput('   0/200 [>---------------------------]   0%').$this->generateOutput(' 199/200 [===========================>]  99%').$this->generateOutput(' 200/200 [============================] 100%'), stream_get_contents($output->getStream()));
    }

    protected function getOutputStream()
    {
        return new StreamOutput(fopen('php://memory', 'r+', false));
    }

    protected $lastMessagesLength;

    protected function generateOutput($expected)
    {
        $expectedout = $expected;

        if ($this->lastMessagesLength !== null) {
            $expectedout = str_pad($expected, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
        }

        $this->lastMessagesLength = strlen($expectedout);

        return "\x0D".$expectedout;
    }
}
PKF1[K� 99IConsole/Symfony/Component/Console/Tests/Descriptor/TextDescriptorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Descriptor\TextDescriptor;

class TextDescriptorTest extends AbstractDescriptorTest
{
    protected function getDescriptor()
    {
        return new TextDescriptor();
    }

    protected function getFormat()
    {
        return 'txt';
    }
}
PKF1[1H�DDDMConsole/Symfony/Component/Console/Tests/Descriptor/MarkdownDescriptorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Descriptor\MarkdownDescriptor;

class MarkdownDescriptorTest extends AbstractDescriptorTest
{
    protected function getDescriptor()
    {
        return new MarkdownDescriptor();
    }

    protected function getFormat()
    {
        return 'md';
    }
}
PKF1[oW��::IConsole/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Descriptor\JsonDescriptor;

class JsonDescriptorTest extends AbstractDescriptorTest
{
    protected function getDescriptor()
    {
        return new JsonDescriptor();
    }

    protected function getFormat()
    {
        return 'json';
    }
}
PKF1[���66HConsole/Symfony/Component/Console/Tests/Descriptor/XmlDescriptorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Descriptor\XmlDescriptor;

class XmlDescriptorTest extends AbstractDescriptorTest
{
    protected function getDescriptor()
    {
        return new XmlDescriptor();
    }

    protected function getFormat()
    {
        return 'xml';
    }
}
PKF1[�ž_JJFConsole/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Tests\Fixtures\DescriptorApplication1;
use Symfony\Component\Console\Tests\Fixtures\DescriptorApplication2;
use Symfony\Component\Console\Tests\Fixtures\DescriptorCommand1;
use Symfony\Component\Console\Tests\Fixtures\DescriptorCommand2;

/**
 * @author Jean-François Simon <contact@jfsimon.fr>
 */
class ObjectsProvider
{
    public static function getInputArguments()
    {
        return array(
            'input_argument_1' => new InputArgument('argument_name', InputArgument::REQUIRED),
            'input_argument_2' => new InputArgument('argument_name', InputArgument::IS_ARRAY, 'argument description'),
            'input_argument_3' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'default_value'),
        );
    }

    public static function getInputOptions()
    {
        return array(
            'input_option_1' => new InputOption('option_name', 'o', InputOption::VALUE_NONE),
            'input_option_2' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', 'default_value'),
            'input_option_3' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, 'option description'),
            'input_option_4' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 'option description', array()),
        );
    }

    public static function getInputDefinitions()
    {
        return array(
            'input_definition_1' => new InputDefinition(),
            'input_definition_2' => new InputDefinition(array(new InputArgument('argument_name', InputArgument::REQUIRED))),
            'input_definition_3' => new InputDefinition(array(new InputOption('option_name', 'o', InputOption::VALUE_NONE))),
            'input_definition_4' => new InputDefinition(array(
                new InputArgument('argument_name', InputArgument::REQUIRED),
                new InputOption('option_name', 'o', InputOption::VALUE_NONE),
            )),
        );
    }

    public static function getCommands()
    {
        return array(
            'command_1' => new DescriptorCommand1(),
            'command_2' => new DescriptorCommand2(),
        );
    }

    public static function getApplications()
    {
        return array(
            'application_1' => new DescriptorApplication1(),
            'application_2' => new DescriptorApplication2(),
        );
    }
}
PKF1[}�
��MConsole/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Console\Tests\Descriptor;

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\BufferedOutput;

abstract class AbstractDescriptorTest extends \PHPUnit_Framework_TestCase
{
    /** @dataProvider getDescribeInputArgumentTestData */
    public function testDescribeInputArgument(InputArgument $argument, $expectedDescription)
    {
        $this->assertDescription($expectedDescription, $argument);
    }

    /** @dataProvider getDescribeInputOptionTestData */
    public function testDescribeInputOption(InputOption $option, $expectedDescription)
    {
        $this->assertDescription($expectedDescription, $option);
    }

    /** @dataProvider getDescribeInputDefinitionTestData */
    public function testDescribeInputDefinition(InputDefinition $definition, $expectedDescription)
    {
        $this->assertDescription($expectedDescription, $definition);
    }

    /** @dataProvider getDescribeCommandTestData */
    public function testDescribeCommand(Command $command, $expectedDescription)
    {
        $this->assertDescription($expectedDescription, $command);
    }

    /** @dataProvider getDescribeApplicationTestData */
    public function testDescribeApplication(Application $application, $expectedDescription)
    {
        // Replaces the dynamic placeholders of the command help text with a static version.
        // The placeholder %command.full_name% includes the script path that is not predictable
        // and can not be tested against.
        foreach ($application->all() as $command) {
            $command->setHelp(str_replace('%command.full_name%', 'app/console %command.name%', $command->getHelp()));
        }

        $this->assertDescription($expectedDescription, $application);
    }

    public function getDescribeInputArgumentTestData()
    {
        return $this->getDescriptionTestData(ObjectsProvider::getInputArguments());
    }

    public function getDescribeInputOptionTestData()
    {
        return $this->getDescriptionTestData(ObjectsProvider::getInputOptions());
    }

    public function getDescribeInputDefinitionTestData()
    {
        return $this->getDescriptionTestData(ObjectsProvider::getInputDefinitions());
    }

    public function getDescribeCommandTestData()
    {
        return $this->getDescriptionTestData(ObjectsProvider::getCommands());
    }

    public function getDescribeApplicationTestData()
    {
        return $this->getDescriptionTestData(ObjectsProvider::getApplications());
    }

    abstract protected function getDescriptor();
    abstract protected function getFormat();

    private function getDescriptionTestData(array $objects)
    {
        $data = array();
        foreach ($objects as $name => $object) {
            $description = file_get_contents(sprintf('%s/../Fixtures/%s.%s', __DIR__, $name, $this->getFormat()));
            $data[] = array($object, $description);
        }

        return $data;
    }

    private function assertDescription($expectedDescription, $describedObject)
    {
        $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
        $this->getDescriptor()->describe($output, $describedObject, array('raw_output' => true));
        $this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch())));
    }
}
PKF1[?�UHii2Console/Symfony/Component/Console/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Console Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKF1[e�>��4�4*XML_Util/tests/CreateTagFromArrayTests.phpnu�[���<?php

class CreateTagFromArrayTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQname()
    {
        $original = array(
            "qname" => "foo:bar",
        );
        $expected = "<foo:bar />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespace()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
        );
        $expected = "<foo:bar xmlns:foo=\"http://foo.com\" />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributes()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
        );
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\" xmlns:foo=\"http://foo.com\" />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContent()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\" xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndAttributesAndContent()
    {
        $original = array(
            "qname" => "foo:bar",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndContent()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "content"      => "I'm inside the tag",
        );
        $expected = "<foo:bar xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithEntitiesNone()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\" xmlns:foo=\"http://foo.com\">I'm inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_ENTITIES_NONE));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntities()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\" xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineFalse()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = false;
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\" key=\"value\" xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrue()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = true;
        $expected =
<<< EOF
<foo:bar argh="fruit&amp;vegetable"
         key="value"
         xmlns:foo="http://foo.com">I&apos;m inside the tag</foo:bar>
EOF;
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndent()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = true;
        $indent = "  ";
        $expected =
<<< EOF
<foo:bar argh="fruit&amp;vegetable"
  key="value"
  xmlns:foo="http://foo.com">I&apos;m inside the tag</foo:bar>
EOF;
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\"^  key=\"value\"^  xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = true;
        $expected = "<foo:bar argh=\"fruit&amp;vegetable\"^  key=\"value\"^  xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameAndNamespaceAndAttributesAndContentWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse()
    {
        $original = array(
            "qname" => "foo:bar",
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = false;
        $expected = "<foo:bar key=\"value\"^  argh=\"fruit&amp;vegetable\"^  xmlns:foo=\"http://foo.com\">I&apos;m inside the tag</foo:bar>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithInvalidArray()
    {
        $badArray = array(
            "foo" => "bar",
        );
        $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart).";
        $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithNamespaceAndAttributesAndContentButWithoutQname()
    {
        $original = array(
            "namespaceUri" => "http://foo.com",
            "attributes"   => array( "key" => "value", "argh" => "fruit&vegetable" ),
            "content"      => "I'm inside the tag",
        );
        $expectedError = "You must either supply a qualified name (qname) or local tag name (localPart).";
        $this->assertEquals($expectedError, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithNonScalarContent()
    {
        $badArray = array(
            'content' => array('foo', 'bar'),
        );
        $expectedError = "Supplied non-scalar value as tag content";
        $this->assertEquals($expectedError, XML_Util::createTagFromArray($badArray));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithArrayOfNamespaces()
    {
        $original = array(
            'qname'        => 'foo:bar',
            'namespaces'   => array('ns1' => 'uri1', 'ns2' => 'uri2'),
        );
        $expected = "<foo:bar xmlns:ns1=\"uri1\" xmlns:ns2=\"uri2\" />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameDerivedFromNamespaceUriAndLocalPart()
    {
        $original = array(
            'namespaceUri' => 'http://bar.org',
            'localPart'    => 'foo'
        );
        $expected = "<foo xmlns=\"http://bar.org\" />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameDerivedFromNamespaceAndLocalPart()
    {
        $original = array(
            'namespace'    => 'http://foo.org',
            'localPart'    => 'bar'
        );
        $expected = "<http://foo.org:bar />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithQnameDerivedFromLocalPart()
    {
        $original = array(
            'namespace'    => '',
            'localPart'    => 'bar'
        );
        $expected = "<bar />";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original));
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayWithImplicitlyEmptyContentAndCollapseNoneDoesNotCollapseTag()
    {
        $original = array('qname' => 'tag1');
        $expected = "<tag1></tag1>";
        $actual = XML_Util::createTagFromArray(
            $original,
            XML_UTIL_REPLACE_ENTITIES,  // default $replaceEntities
            false,                      // default $multiline
            '_auto',                    // default $indent
            "\n",                       // default $linebreak
            true,                       // default $sortAttributes
            XML_UTIL_COLLAPSE_NONE
        );
        $this->assertEquals($expected, $actual);
    }

    /**
     * @covers XML_Util::createTagFromArray()
     */
    public function testCreateTagFromArrayForCdataWithExplicitlyEmptyContentDoesNotCollapseTag()
    {
        $original = array('qname' => 'tag1', 'content' => '');
        $expected = "<tag1><![CDATA[]]></tag1>";
        $this->assertEquals($expected, XML_Util::createTagFromArray($original, XML_UTIL_CDATA_SECTION));
    }
}
PKF1[�C���'XML_Util/tests/ReplaceEntitiesTests.phpnu�[���<?php

class ReplaceEntitiesTests extends AbstractUnitTests
{
    protected function getSimpleData()
    {
        return 'This string contains < & >.';
    }

    protected function getUtf8Data()
    {
        return 'This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê';
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleData()
    {
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData()));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData()
    {
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), 'INVALID_OPTION'));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesXml()
    {
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesXmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML, $encoding));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForUtf8DataWithEntitiesXmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like &lt;, &gt;, &amp; and &quot; as well as ä, ö, ß, à and ê";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML, $encoding));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequired()
    {
        $expected = "This string contains &lt; &amp; >.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains &lt; &amp; >.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like &lt;, >, &amp; and &quot; as well as ä, ö, ß, à and ê";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesHtml()
    {
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForSimpleDataWithEntitiesHtmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding));
    }

    /**
     * @covers XML_Util::replaceEntities()
     */
    public function testReplaceEntitiesForUtf8DataWithEntitiesHtmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like &lt;, &gt;, &amp; and &quot; as well as &auml;, &ouml;, &szlig;, &agrave; and &ecirc;";
        $this->assertEquals($expected, XML_Util::replaceEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding));
    }
}
PKF1[یu���"XML_Util/tests/ApiVersionTests.phpnu�[���<?php

class ApiVersionTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::apiVersion()
     */
    public function testApiVersion()
    {
        $this->assertEquals('1.4', XML_Util::apiVersion());
    }
}PKF1[�Gs���XML_Util/tests/Bug5392Tests.phpnu�[���<?php

/**
 * Bug #5392 "encoding of ISO-8859-1 is the only supported encoding"
 *
 * Original characters of the given encoding that are "replaced"
 * should then "reverse" back to perfectly match the original.
 *
 * @link https://pear.php.net/bugs/bug.php?id=5392
 */
class Bug5392Tests extends AbstractUnitTests
{
    public function testReplaceEntitiesForBug5392()
    {
        $original = 'This data contains special chars like <, >, & and " as well as ä, ö, ß, à and ê';
        $replacedResult = XML_Util::replaceEntities($original, XML_UTIL_ENTITIES_HTML, "UTF-8");
        $reversedResult = XML_Util::reverseEntities($replacedResult, XML_UTIL_ENTITIES_HTML, "UTF-8");
        $this->assertEquals($original, $reversedResult, "Failed bugcheck.");
    }
}
PKF1[4e��jj*XML_Util/tests/CreateCDataSectionTests.phpnu�[���<?php

class CreateCDataSectionTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createCDataSection()
     */
    public function testCreateCDataSectionBasicUsage()
    {
        $original = "I am content.";
        $expected ="<![CDATA[I am content.]]>";
        $this->assertEquals($expected, XML_Util::createCDataSection($original));
    }
}
PKF1[|�\5)XML_Util/tests/CollapseEmptyTagsTests.phpnu�[���<?php

class CollapseEmptyTagsTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsBasicUsage()
    {
        $emptyTag = "<foo></foo>";
        $expected = "<foo />";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsBasicUsageAlongsideNonemptyTag()
    {
        $emptyTag = "<foo></foo>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<foo /><bar>baz</bar>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseAll()
    {
        $emptyTag = "<foo></foo>";
        $expected = "<foo />";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_ALL));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseAll()
    {
        $emptyTag = "<foo></foo>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<foo /><bar>baz</bar>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_ALL));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagAlongsideEmptyTagWithCollapseAll()
    {
        $emptyTag = "<foo></foo>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<foo /><bar>baz</bar><foo />";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyPrefixedTagAlongsideNonemptyTagAlongsideEmptyPrefixedTagWithCollapseAll()
    {
        $emptyTag = "<foo:foo2></foo:foo2>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<foo:foo2 /><bar>baz</bar><foo:foo2 />";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyNsPrefixedTagAlongsideNonemptyTagAlongsideEmptyNsPrefixedTagWithCollapseAll()
    {
        $emptyTag = "<http://foo.com:foo2></http://foo.com:foo2>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<http://foo.com:foo2 /><bar>baz</bar><http://foo.com:foo2 />";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag . $emptyTag, XML_UTIL_COLLAPSE_ALL));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseXhtml()
    {
        $emptyTag = "<foo></foo>";
        $expected = "<foo></foo>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_XHTML_ONLY));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseXhtml()
    {
        $emptyTag = "<foo></foo>";
        $otherTag = "<bar>baz</bar>";
        $xhtmlTag = "<br></br>";
        $expected = "<foo></foo><br /><bar>baz</bar>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $xhtmlTag . $otherTag, XML_UTIL_COLLAPSE_XHTML_ONLY));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagWithCollapseNone()
    {
        $emptyTag = "<foo></foo>";
        $expected = "<foo></foo>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag, XML_UTIL_COLLAPSE_NONE));
    }

    /**
     * @covers XML_Util::collapseEmptyTags()
     */
    public function testCollapseEmptyTagsOnOneEmptyTagAlongsideNonemptyTagWithCollapseNone()
    {
        $emptyTag = "<foo></foo>";
        $otherTag = "<bar>baz</bar>";
        $expected = "<foo></foo><bar>baz</bar>";
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($emptyTag . $otherTag, XML_UTIL_COLLAPSE_NONE));
    }
}
PKF1[��GG*XML_Util/tests/SplitQualifiedNameTests.phpnu�[���<?php

class SplitQualifiedNameTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::splitQualifiedName()
     */
    public function testSplitQualifiedNameWithoutNamespace()
    {
        $original = "xslt:stylesheet";
        $expected = array(
            'namespace' => 'xslt',
            'localPart' => 'stylesheet',
        );
        $this->assertEquals($expected, XML_Util::splitQualifiedName($original));
    }

    /**
     * @covers XML_Util::splitQualifiedName()
     */
    public function testSplitQualifiedNameWithNamespace()
    {
        $original = "stylesheet";
        $namespace = "myNs";
        $expected = array(
            'namespace' => 'myNs',
            'localPart' => 'stylesheet',
        );
        $this->assertEquals($expected, XML_Util::splitQualifiedName($original, $namespace));
    }
}
PKF1[Yq��� XML_Util/tests/Bug21184Tests.phpnu�[���<?php

/**
 * Bug #21184
 *
 * PREG returns NULL when it encounters an error.
 * In this case, it was encountering PREG_BACKTRACK_LIMIT_ERROR.
 *
 * @link https://pear.php.net/bugs/bug.php?id=21177
 */
class Bug21184 extends AbstractUnitTests
{
    public function testBug21184()
    {
        $xml = '<XML_Serializer_Tag>one</XML_Serializer_Tag>';
        $this->assertEquals($xml, XML_Util::collapseEmptyTags($xml, XML_UTIL_COLLAPSE_ALL));
    }
}
PKF1[>�M���XML_Util/tests/Bug4950Tests.phpnu�[���<?php

/**
 * Bug #4950 "Incorrect CDATA serializing"
 *
 * Content that looks like CDATA end characters and tags
 * should still be recognized solely as content text.
 *
 * @link https://pear.php.net/bugs/bug.php?id=4950
 */
class Bug4950Tests extends AbstractUnitTests
{
    public function testCreateTagForBug4950()
    {
        $qname = "test";
        $attributes = array();
        $content = "Content ]]></test> here!";
        $namespaceUrl = null;
        $expected = "<test><![CDATA[Content ]]]]><![CDATA[></test> here!]]></test>";
        $result = XML_Util::createTag($qname, $attributes, $content, $namespaceUrl, XML_UTIL_CDATA_SECTION);
        $this->assertEquals($expected, $result, "Failed bugcheck.");
    }
}
PKF1[�YR�""*XML_Util/tests/CreateStartElementTests.phpnu�[���<?php

class CreateStartElementTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagOnly()
    {
        $original = "myNs:myTag";
        $expected = "<myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createStartElement($original));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributes()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $expected = "<myNs:myTag foo=\"bar\">";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithEmptyAttributes()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = "";
        $expected = "<myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespace()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\" xmlns:myNs=\"http://www.w3c.org/myNs#\">";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithEmptyAttributesAndNonUriNamespace()
    {
        $originalTag = "myTag";
        $originalAttributes = "";
        $originalNamespace = "foo";
        $expected = "<myTag xmlns=\"foo\">";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultiline()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected =
<<< EOF
<myNs:myTag foo="bar"
            xmlns:myNs="http://www.w3c.org/myNs#">
EOF;
        $multiline = true;
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndent()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected =
<<< EOF
<myNs:myTag foo="bar"
  xmlns:myNs="http://www.w3c.org/myNs#">
EOF;
        $multiline = true;
        $indent = "  ";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreak()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsTrue()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar", "boo" => "baz");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag boo=\"baz\"^  foo=\"bar\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = true;
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes));
    }

    /**
     * @covers XML_Util::createStartElement()
     */
    public function testCreateStartElementForTagWithAttributesAndNamespaceWithMultilineAndIndentAndLinebreakAndSortAttributesIsFalse()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar", "boo" => "baz");
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\"^  boo=\"baz\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = false;
        $this->assertEquals($expected, XML_Util::createStartElement($originalTag, $originalAttributes, $originalNamespace, $multiline, $indent, $linebreak, $sortAttributes));
    }
}
PKF1[ܬ$���-XML_Util/tests/GetDocTypeDeclarationTests.phpnu�[���<?php

class GetDocTypeDeclarationTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::getDocTypeDeclaration()
     */
    public function testGetDocTypeDeclarationUsingRoot()
    {
        $expected = "<!DOCTYPE rootTag>";
        $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag"));
    }

    /**
     * @covers XML_Util::getDocTypeDeclaration()
     */
    public function testGetDocTypeDeclarationUsingRootAndStringUri()
    {
        $expected = "<!DOCTYPE rootTag SYSTEM \"myDocType.dtd\">";
        $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", "myDocType.dtd"));
    }

    /**
     * @covers XML_Util::getDocTypeDeclaration()
     */
    public function testGetDocTypeDeclarationUsingRootAndArrayUri()
    {
        $uri = array(
            'uri' => 'http://pear.php.net/dtd/package-1.0',
            'id' => '-//PHP//PEAR/DTD PACKAGE 0.1'
        );
        $expected = "<!DOCTYPE rootTag PUBLIC \"-//PHP//PEAR/DTD PACKAGE 0.1\" \"http://pear.php.net/dtd/package-1.0\">";
        $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri));
    }

    /**
     * @covers XML_Util::getDocTypeDeclaration()
     */
    public function testGetDocTypeDeclarationUsingRootAndArrayUriAndInternalDtd()
    {
        $uri = array(
            'uri' => 'http://pear.php.net/dtd/package-1.0',
            'id' => '-//PHP//PEAR/DTD PACKAGE 0.1'
        );
        $dtdEntry = '<!ELEMENT additionalInfo (#PCDATA)>';
        $expected =
<<< EOF
<!DOCTYPE rootTag PUBLIC "-//PHP//PEAR/DTD PACKAGE 0.1" "http://pear.php.net/dtd/package-1.0" [
<!ELEMENT additionalInfo (#PCDATA)>
]>
EOF;
        $this->assertEquals($expected, XML_Util::getDocTypeDeclaration("rootTag", $uri, $dtdEntry));
    }
}
PKF1[��G XML_Util/tests/Bug21177Tests.phpnu�[���<?php

/**
 * Bug #21177 "XML_Util::collapseEmptyTags() can return NULL"
 *
 * PREG returns NULL when it encounters an error.
 * In this case, it was encountering PREG_BACKTRACK_LIMIT_ERROR.
 *
 * @link https://pear.php.net/bugs/bug.php?id=21177
 */
class Bug21177Tests extends AbstractUnitTests
{
    public function getTestCandidate()
    {
        $expected = '<id_mytest_yesorno />';

        return array(
            array('<idmytestyesorno></idmytestyesorno>',        '<idmytestyesorno />'),
            array('<idmytestyesorno />',                        '<idmytestyesorno />'),

            array('<id_mytest_yesorno></id_mytest_yesorno>',    '<id_mytest_yesorno />'),
            array('<id_mytest_yesorno />',                      '<id_mytest_yesorno />'),
        );
    }

    /**
     * @dataProvider getTestCandidate()
     */
    public function testCollapseEmptyTagsForBug21177($original, $expected)
    {
        $this->assertEquals($expected, XML_Util::collapseEmptyTags($original, XML_UTIL_COLLAPSE_ALL), "Failed bugcheck.");
    }
}
PKF1[��۩�� XML_Util/tests/Bug18343Tests.phpnu�[���<?php

/**
 * Bug #18343 "Entities in file names decoded during packaging"
 *
 * No matter what flags are given to createTagFromArray(),
 * an attribute must *always* be at least ENTITIES_XML encoded.
 *
 * @link https://pear.php.net/bugs/bug.php?id=18343
 */
class Bug18343Tests extends AbstractUnitTests
{
    private $tagArray = array(
        "qname"      => "install",
        "attributes" => array(
            "as"    => "Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek",
            "name"  => "test/Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&s=Newsweek",
        )
    );

    public function getFlagsToTest()
    {
        new XML_Util(); // for constants to be declared

        return array(
            array('no flag', null),
            array('false', false),
            array('ENTITIES_NONE', XML_UTIL_ENTITIES_NONE),
            array('ENTITIES_XML', XML_UTIL_ENTITIES_XML),
            array('ENTITIES_XML_REQUIRED', XML_UTIL_ENTITIES_XML_REQUIRED),
            array('ENTITIES_HTML', XML_UTIL_ENTITIES_HTML),
            array('REPLACE_ENTITIES', XML_UTIL_REPLACE_ENTITIES),
        );
    }

    /**
     * @dataProvider getFlagsToTest()
     */
    public function testCreateTagFromArrayForBug18343($key, $flag)
    {
        // all flags for the candidate input should return the same result
        $expected =
<<< EOF
<install as="Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&amp;s=Newsweek" name="test/Horde/Feed/fixtures/lexicon/http-p.moreover.com-cgi-local-page%2Fo=rss&amp;s=Newsweek" />
EOF;
        $this->assertEquals($expected, XML_Util::createTagFromArray($this->tagArray, $flag), "Failed bugcheck for $key.");
    }
}
PKF1[z��t��'XML_Util/tests/ReverseEntitiesTests.phpnu�[���<?php

class ReverseEntitiesTests extends AbstractUnitTests
{
    protected function getSimpleData()
    {
        return 'This string contains &lt; &amp; &gt;.';
    }

    protected function getUtf8Data()
    {
        return 'This data contains special chars like &lt;, &gt;, &amp; and &quot; as well as &auml;, &ouml;, &szlig;, &agrave; and &ecirc;';
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleData()
    {
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData()));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithInvalidOptionReturnsOriginalData()
    {
        $expected = "This string contains &lt; &amp; &gt;.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), 'INVALID_OPTION'));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesXml()
    {
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesXmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML), $encoding);
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForUtf8DataWithEntitiesXmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like <, >, & and \" as well as &auml;, &ouml;, &szlig;, &agrave; and &ecirc;";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML), $encoding);
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequired()
    {
        $expected = "This string contains < & &gt;.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesXmlRequiredAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains < & &gt;.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForUtf8DataWithEntitiesXmlRequiredAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like <, &gt;, & and \" as well as &auml;, &ouml;, &szlig;, &agrave; and &ecirc;";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_XML_REQUIRED, $encoding));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesHtml()
    {
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForSimpleDataWithEntitiesHtmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This string contains < & >.";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getSimpleData(), XML_UTIL_ENTITIES_HTML, $encoding));
    }

    /**
     * @covers XML_Util::reverseEntities()
     */
    public function testReverseEntitiesForUtf8DataWithEntitiesHtmlAndEncoding()
    {
        $encoding = "UTF-8";
        $expected = "This data contains special chars like <, >, & and \" as well as ä, ö, ß, à and ê";
        $this->assertEquals($expected, XML_Util::reverseEntities($this->getUtf8Data(), XML_UTIL_ENTITIES_HTML, $encoding));
    }
}
PKF1[~�$[ee(XML_Util/tests/CreateEndElementTests.phpnu�[���<?php

class CreateEndElementTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createEndElement()
     */
    public function testCreateEndElementBasicUsage()
    {
        $original = "myTag";
        $expected = "</myTag>";
        $this->assertEquals($expected, XML_Util::createEndElement($original));
    }

    /**
     * @covers XML_Util::createEndElement()
     */
    public function testCreateEndElementWithNamespacedTag()
    {
        $original = "myNs:myTag";
        $expected = "</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createEndElement($original));
    }
}
PKF1[���!��$XML_Util/tests/AbstractUnitTests.phpnu�[���<?php

/*
 * Allow for PHPUnit 4.* while XML_Util is still usable on PHP 5.4
 */
if (!class_exists('PHPUnit_Framework_TestCase')) {
    class PHPUnit_Framework_TestCase extends \PHPUnit\Framework\TestCase {}
}

abstract class AbstractUnitTests extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        // ensure the class is defined, and thus its constants are declared
        new XML_Util();
    }
}
PKF1[�m4�**!XML_Util/tests/CreateTagTests.phpnu�[���<?php

class CreateTagTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributes()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $expected = "<myNs:myTag foo=\"bar\" />";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContent()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag";
        $expected = "<myNs:myTag foo=\"bar\">This is inside the tag</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespace()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\" xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace));
    }


    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithCDataSection()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\" xmlns:myNs=\"http://www.w3c.org/myNs#\"><![CDATA[This is inside the tag and has < & @ > in it]]></myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_CDATA_SECTION));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntities()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $expected = "<myNs:myTag foo=\"bar\" xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineFalse()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = false;
        $expected = "<myNs:myTag foo=\"bar\" xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrue()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = true;
        $expected =
<<< EOF
<myNs:myTag foo="bar"
            xmlns:myNs="http://www.w3c.org/myNs#">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>
EOF;
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndent()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = true;
        $indent = "  ";
        $expected =
<<< EOF
<myNs:myTag foo="bar"
  xmlns:myNs="http://www.w3c.org/myNs#">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>
EOF;

        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreak()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $expected = "<myNs:myTag foo=\"bar\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesTrue()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar", "boo" => "baz");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = true;
        $expected = "<myNs:myTag boo=\"baz\"^  foo=\"bar\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes));
    }

    /**
     * @covers XML_Util::createTag()
     */
    public function testCreateTagForTagWithAttributesAndContentAndNamespaceWithReplaceEntitiesAndMultilineTrueAndIndentAndLinebreakAndSortAttributesFalse()
    {
        $originalTag = "myNs:myTag";
        $originalAttributes = array("foo" => "bar", "boo" => "baz");
        $originalContent = "This is inside the tag and has < & @ > in it";
        $originalNamespace = "http://www.w3c.org/myNs#";
        $multiline = true;
        $indent = "  ";
        $linebreak = "^";
        $sortAttributes = false;
        $expected = "<myNs:myTag foo=\"bar\"^  boo=\"baz\"^  xmlns:myNs=\"http://www.w3c.org/myNs#\">This is inside the tag and has &lt; &amp; @ &gt; in it</myNs:myTag>";
        $this->assertEquals($expected, XML_Util::createTag($originalTag, $originalAttributes, $originalContent, $originalNamespace, XML_UTIL_REPLACE_ENTITIES, $multiline, $indent, $linebreak, $sortAttributes));
    }
}
PKF1[Df:��)XML_Util/tests/GetXmlDeclarationTests.phpnu�[���<?php

class GetXMLDeclarationTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::getXMLDeclaration()
     */
    public function testGetXMLDeclarationUsingVersion()
    {
        $version = "1.0";
        $expected = "<?xml version=\"1.0\"?>";
        $this->assertEquals($expected, XML_Util::getXMLDeclaration($version));
    }

    /**
     * @covers XML_Util::getXMLDeclaration()
     */
    public function testGetXMLDeclarationUsingVersionAndEncodingAndStandalone()
    {
        $version = "1.0";
        $encoding = "UTF-8";
        $standalone = true;
        $expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
        $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone));
    }

    /**
     * @covers XML_Util::getXMLDeclaration()
     */
    public function testGetXMLDeclarationUsingVersionAndStandalone()
    {
        $version = "1.0";
        $encoding = null;
        $standalone = true;
        $expected = "<?xml version=\"1.0\" standalone=\"yes\"?>";
        $this->assertEquals($expected, XML_Util::getXMLDeclaration($version, $encoding, $standalone));
    }
}
PKF1[Z�t�*XML_Util/tests/AttributesToStringTests.phpnu�[���<?php

class AttributesToStringTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringBasicUsage()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " boo=\"baz\" foo=\"bar\"";
        $this->assertEquals($expected, XML_Util::attributesToString($original));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithExplicitSortTrue()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " boo=\"baz\" foo=\"bar\"";
        $sort = true;
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithExplicitSortFalse()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " foo=\"bar\" boo=\"baz\"";
        $sort = false;
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithMultilineFalse()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " boo=\"baz\" foo=\"bar\"";
        $sort = true;
        $multiline = false;
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithMultilineTrue()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected =
<<< EOF
 boo="baz"
    foo="bar"
EOF;
        $sort = true;
        $multiline = true;
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithExplicitIndent()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " boo=\"baz\"\n        foo=\"bar\"";
        $sort = true;
        $multiline = true;
        $indent = '        '; // 8 spaces
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $indent));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithExplicitLinebreak()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $expected = " boo=\"baz\"\n^foo=\"bar\"";
        $sort = true;
        $multiline = true;
        $linebreak = '^'; // some dummy character
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithOptionsThatIncludesSort()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $options = array(
            'multiline' => true,
            'indent'    => '----',
            'linebreak' => "^",
            'entities'  => XML_UTIL_ENTITIES_XML,
            'sort'      => true,
        );

        $expected = " boo=\"baz\"\n----foo=\"bar\"";
        $this->assertEquals($expected, XML_Util::attributesToString($original, $options));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithOptionsThatExcludesSort()
    {
        $original = array('foo' => 'bar','boo' => 'baz',);
        $options = array(
            'multiline' => true,
            'indent'    => '----',
            'linebreak' => "^",
            'entities'  => XML_UTIL_ENTITIES_XML,
        );

        $expected = " boo=\"baz\"\n----foo=\"bar\"";
        $this->assertEquals($expected, XML_Util::attributesToString($original, $options));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithEntitiesNone()
    {
        $original = array("foo" => "b@&r", "boo" => "b><z");
        $expected = " boo=\"b><z\" foo=\"b@&r\"";
        $sort = true;
        $multiline = false;
        $linebreak = '    ';
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_NONE));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithEntitiesXml()
    {
        $original = array("foo" => "b@&r", "boo" => "b><z");
        $expected = " boo=\"b&gt;&lt;z\" foo=\"b@&amp;r\"";
        $sort = true;
        $multiline = false;
        $linebreak = '    ';
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithEntitiesXmlRequired()
    {
        $original = array("foo" => "b@&r", "boo" => "b><z");
        $expected = " boo=\"b>&lt;z\" foo=\"b@&amp;r\"";
        $sort = true;
        $multiline = false;
        $linebreak = '    ';
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_XML_REQUIRED));
    }

    /**
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithEntitiesHtml()
    {
        $original = array("foo" => "b@&r", "boo" => "b><z");
        $expected = " boo=\"b&gt;&lt;z\" foo=\"b@&amp;r\"";
        $sort = true;
        $multiline = false;
        $linebreak = '    ';
        $this->assertEquals($expected, XML_Util::attributesToString($original, $sort, $multiline, $linebreak, PHP_EOL, XML_UTIL_ENTITIES_HTML));
    }

    /**
     * Tag attributes should not be treated as CDATA,
     * so the operation will instead quietly use XML_UTIL_ENTITIES_XML.
     *
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithCDataSectionForSingleAttribute()
    {
        $original = array('foo' => 'bar'); // need exactly one attribute here
        $options = array(
            'sort'      => true,   // doesn't matter for this testcase
            'multiline' => false,  // doesn't matter for this testcase
            'indent'    => null,   // doesn't matter for this testcase
            'linebreak' => null,   // doesn't matter for this testcase
            'entities'  => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase
        );
        $expected = " foo=\"bar\"";
        $this->assertEquals($expected, XML_Util::attributesToString($original, $options));
    }

    /**
     * Tag attributes should not be treated as CDATA,
     * so the operation will instead quietly use XML_UTIL_ENTITIES_XML.
     *
     * @covers XML_Util::attributesToString()
     */
    public function testAttributesToStringWithCDataSectionForMultipleAttributesAndMultilineFalse()
    {
        $original = array('foo' => 'bar', 'boo' => 'baz'); // need more than one attribute here
        $options = array(
            'sort'      => true,   // doesn't matter for this testcase
            'multiline' => false,  // DOES matter for this testcase, must be false
            'indent'    => null,   // doesn't matter for this testcase
            'linebreak' => null,   // doesn't matter for this testcase
            'entities'  => XML_UTIL_CDATA_SECTION, // DOES matter for this testcase
        );
        $expected = " boo=\"baz\" foo=\"bar\"";
        $this->assertEquals($expected, XML_Util::attributesToString($original, $options));
    }
}
PKF1[ݑh���#XML_Util/tests/IsValidNameTests.phpnu�[���<?php

class IsValidNameTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::isValidName()
     */
    public function testIsValidNameForTagNameThatIsValid()
    {
        $tagName = "alpha-x_y_z.123";
        $result = XML_Util::isValidName($tagName);
        $this->assertTrue($result);
    }

    /**
     * @covers XML_Util::isValidName()
     */
    public function testIsValidNameForTagNameWithInvalidCharacter()
    {
        $tagName = "invalidTag?";
        $result = XML_Util::isValidName($tagName);
        $this->assertInstanceOf('PEAR_Error', $result);
        $expectedError = "XML names may only contain alphanumeric chars, period, hyphen, colon and underscores";
        $this->assertEquals($expectedError, $result->getMessage());
    }

    /**
     * @covers XML_Util::isValidName()
     */
    public function testIsValidNameForTagNameWithInvalidStartingCharacter()
    {
        $tagName = "1234five";
        $result = XML_Util::isValidName($tagName);
        $this->assertInstanceOf('PEAR_Error', $result);
        $expectedError = "XML names may only start with letter or underscore";
        $this->assertEquals($expectedError, $result->getMessage());
    }

    /**
     * @covers XML_Util::isValidName()
     */
    public function testIsValidNameForInt()
    {
        $tagName = 1;
        $result = XML_Util::isValidName($tagName);
        $this->assertInstanceOf('PEAR_Error', $result);
        $expectedError = "XML names may only start with letter or underscore";
        $this->assertEquals($expectedError, $result->getMessage());
    }

    /**
     * @covers XML_Util::isValidName()
     */
    public function testIsValidNameForEmptyString()
    {
        $tagName = '';
        $result = XML_Util::isValidName($tagName);
        $this->assertInstanceOf('PEAR_Error', $result);
        $expectedError = "XML names may only start with letter or underscore";
        $this->assertEquals($expectedError, $result->getMessage());
    }
}
PKF1[���TT%XML_Util/tests/CreateCommentTests.phpnu�[���<?php

class CreateCommentTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::createComment()
     */
    public function testCreateCommentBasicUsage()
    {
        $original = "I am comment.";
        $expected = "<!-- I am comment. -->";
        $this->assertEquals($expected, XML_Util::createComment($original));
    }
}
PKF1[�rv��"XML_Util/tests/RaiseErrorTests.phpnu�[���<?php

class RaiseErrorTests extends AbstractUnitTests
{
    /**
     * @covers XML_Util::raiseError()
     */
    public function testRaiseError()
    {
        $code = 12345;
        $message = "I am an error";
        $error = XML_Util::raiseError($message, $code);
        $this->assertInstanceOf('PEAR_Error', $error);
        $this->assertEquals($message, $error->getMessage());
        $this->assertEquals($code, $error->getCode());
    }
}
PKG1[F1y��A�AOOptionsResolver/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\OptionsResolver\Tests;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\Options;

class OptionsResolverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var OptionsResolver
     */
    private $resolver;

    protected function setUp()
    {
        $this->resolver = new OptionsResolver();
    }

    public function testResolve()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => '2',
        ));

        $options = array(
            'two' => '20',
        );

        $this->assertEquals(array(
            'one' => '1',
            'two' => '20',
        ), $this->resolver->resolve($options));
    }

    public function testResolveLazy()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => function (Options $options) {
                return '20';
            },
        ));

        $this->assertEquals(array(
            'one' => '1',
            'two' => '20',
        ), $this->resolver->resolve(array()));
    }

    public function testResolveLazyDependencyOnOptional()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => function (Options $options) {
                return $options['one'].'2';
            },
        ));

        $options = array(
            'one' => '10',
        );

        $this->assertEquals(array(
            'one' => '10',
            'two' => '102',
        ), $this->resolver->resolve($options));
    }

    public function testResolveLazyDependencyOnMissingOptionalWithoutDefault()
    {
        $test = $this;

        $this->resolver->setOptional(array(
            'one',
        ));

        $this->resolver->setDefaults(array(
            'two' => function (Options $options) use ($test) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertFalse(isset($options['one']));

                return '2';
            },
        ));

        $options = array(
        );

        $this->assertEquals(array(
            'two' => '2',
        ), $this->resolver->resolve($options));
    }

    public function testResolveLazyDependencyOnOptionalWithoutDefault()
    {
        $test = $this;

        $this->resolver->setOptional(array(
            'one',
        ));

        $this->resolver->setDefaults(array(
            'two' => function (Options $options) use ($test) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->assertTrue(isset($options['one']));

                return $options['one'].'2';
            },
        ));

        $options = array(
            'one' => '10',
        );

        $this->assertEquals(array(
            'one' => '10',
            'two' => '102',
        ), $this->resolver->resolve($options));
    }

    public function testResolveLazyDependencyOnRequired()
    {
        $this->resolver->setRequired(array(
            'one',
        ));
        $this->resolver->setDefaults(array(
            'two' => function (Options $options) {
                return $options['one'].'2';
            },
        ));

        $options = array(
            'one' => '10',
        );

        $this->assertEquals(array(
            'one' => '10',
            'two' => '102',
        ), $this->resolver->resolve($options));
    }

    public function testResolveLazyReplaceDefaults()
    {
        $test = $this;

        $this->resolver->setDefaults(array(
            'one' => function (Options $options) use ($test) {
                /* @var \PHPUnit_Framework_TestCase $test */
                $test->fail('Previous closure should not be executed');
            },
        ));

        $this->resolver->replaceDefaults(array(
            'one' => function (Options $options, $previousValue) {
                return '1';
            },
        ));

        $this->assertEquals(array(
            'one' => '1',
        ), $this->resolver->resolve(array()));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testResolveFailsIfNonExistingOption()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setRequired(array(
            'two',
        ));

        $this->resolver->setOptional(array(
            'three',
        ));

        $this->resolver->resolve(array(
            'foo' => 'bar',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\MissingOptionsException
     */
    public function testResolveFailsIfMissingRequiredOption()
    {
        $this->resolver->setRequired(array(
            'one',
        ));

        $this->resolver->setDefaults(array(
            'two' => '2',
        ));

        $this->resolver->resolve(array(
            'two' => '20',
        ));
    }

    public function testResolveSucceedsIfOptionValueAllowed()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedValues(array(
            'one' => array('1', 'one'),
        ));

        $options = array(
            'one' => 'one',
        );

        $this->assertEquals(array(
            'one' => 'one',
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionValueAllowed2()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => '2',
        ));

        $this->resolver->setAllowedValues(array(
            'one' => '1',
            'two' => '2',
        ));
        $this->resolver->addAllowedValues(array(
            'one' => 'one',
            'two' => 'two',
        ));

        $options = array(
            'one' => '1',
            'two' => 'two',
        );

        $this->assertEquals(array(
            'one' => '1',
            'two' => 'two',
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionalWithAllowedValuesNotSet()
    {
        $this->resolver->setRequired(array(
            'one',
        ));

        $this->resolver->setOptional(array(
            'two',
        ));

        $this->resolver->setAllowedValues(array(
            'one' => array('1', 'one'),
            'two' => array('2', 'two'),
        ));

        $options = array(
            'one' => '1',
        );

        $this->assertEquals(array(
            'one' => '1',
        ), $this->resolver->resolve($options));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testResolveFailsIfOptionValueNotAllowed()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedValues(array(
            'one' => array('1', 'one'),
        ));

        $this->resolver->resolve(array(
            'one' => '2',
        ));
    }

    public function testResolveSucceedsIfOptionTypeAllowed()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'string',
        ));

        $options = array(
            'one' => 'one',
        );

        $this->assertEquals(array(
            'one' => 'one',
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionTypeAllowedPassArray()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => array('string', 'bool'),
        ));

        $options = array(
            'one' => true,
        );

        $this->assertEquals(array(
            'one' => true,
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionTypeAllowedPassObject()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'object',
        ));

        $object = new \stdClass();
        $options = array(
            'one' => $object,
        );

        $this->assertEquals(array(
            'one' => $object,
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionTypeAllowedPassClass()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => '\stdClass',
        ));

        $object = new \stdClass();
        $options = array(
            'one' => $object,
        );

        $this->assertEquals(array(
            'one' => $object,
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionTypeAllowedAddTypes()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => '2',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'string',
            'two' => 'bool',
        ));
        $this->resolver->addAllowedTypes(array(
            'one' => 'float',
            'two' => 'integer',
        ));

        $options = array(
            'one' => 1.23,
            'two' => false,
        );

        $this->assertEquals(array(
            'one' => 1.23,
            'two' => false,
        ), $this->resolver->resolve($options));
    }

    public function testResolveSucceedsIfOptionalWithTypeAndWithoutValue()
    {
        $this->resolver->setOptional(array(
            'one',
            'two',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'string',
            'two' => 'int',
        ));

        $options = array(
            'two' => 1,
        );

        $this->assertEquals(array(
            'two' => 1,
        ), $this->resolver->resolve($options));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testResolveFailsIfOptionTypeNotAllowed()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => array('string', 'bool'),
        ));

        $this->resolver->resolve(array(
            'one' => 1.23,
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testResolveFailsIfOptionTypeNotAllowedMultipleOptions()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
            'two' => '2',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'string',
            'two' => 'bool',
        ));

        $this->resolver->resolve(array(
            'one' => 'foo',
            'two' => 1.23,
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
     */
    public function testResolveFailsIfOptionTypeNotAllowedAddTypes()
    {
        $this->resolver->setDefaults(array(
            'one' => '1',
        ));

        $this->resolver->setAllowedTypes(array(
            'one' => 'string',
        ));
        $this->resolver->addAllowedTypes(array(
            'one' => 'bool',
        ));

        $this->resolver->resolve(array(
            'one' => 1.23,
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testSetRequiredFailsIfDefaultIsPassed()
    {
        $this->resolver->setRequired(array(
            'one' => '1',
        ));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testSetOptionalFailsIfDefaultIsPassed()
    {
        $this->resolver->setOptional(array(
            'one' => '1',
        ));
    }

    public function testFluidInterface()
    {
        $this->resolver->setDefaults(array('one' => '1'))
            ->replaceDefaults(array('one' => '2'))
            ->setAllowedValues(array('one' => array('1', '2')))
            ->addAllowedValues(array('one' => array('3')))
            ->setRequired(array('two'))
            ->setOptional(array('three'));

        $options = array(
            'two' => '2',
        );

        $this->assertEquals(array(
            'one' => '2',
            'two' => '2',
        ), $this->resolver->resolve($options));
    }

    public function testKnownIfDefaultWasSet()
    {
        $this->assertFalse($this->resolver->isKnown('foo'));

        $this->resolver->setDefaults(array(
            'foo' => 'bar',
        ));

        $this->assertTrue($this->resolver->isKnown('foo'));
    }

    public function testKnownIfRequired()
    {
        $this->assertFalse($this->resolver->isKnown('foo'));

        $this->resolver->setRequired(array(
            'foo',
        ));

        $this->assertTrue($this->resolver->isKnown('foo'));
    }

    public function testKnownIfOptional()
    {
        $this->assertFalse($this->resolver->isKnown('foo'));

        $this->resolver->setOptional(array(
            'foo',
        ));

        $this->assertTrue($this->resolver->isKnown('foo'));
    }

    public function testRequiredIfRequired()
    {
        $this->assertFalse($this->resolver->isRequired('foo'));

        $this->resolver->setRequired(array(
            'foo',
        ));

        $this->assertTrue($this->resolver->isRequired('foo'));
    }

    public function testNotRequiredIfRequiredAndDefaultValue()
    {
        $this->assertFalse($this->resolver->isRequired('foo'));

        $this->resolver->setRequired(array(
            'foo',
        ));
        $this->resolver->setDefaults(array(
            'foo' => 'bar',
        ));

        $this->assertFalse($this->resolver->isRequired('foo'));
    }

    public function testNormalizersTransformFinalOptions()
    {
        $this->resolver->setDefaults(array(
            'foo' => 'bar',
            'bam' => 'baz',
        ));
        $this->resolver->setNormalizers(array(
            'foo' => function (Options $options, $value) {
                return $options['bam'].'['.$value.']';
            },
        ));

        $expected = array(
            'foo' => 'baz[bar]',
            'bam' => 'baz',
        );

        $this->assertEquals($expected, $this->resolver->resolve(array()));

        $expected = array(
            'foo' => 'boo[custom]',
            'bam' => 'boo',
        );

        $this->assertEquals($expected, $this->resolver->resolve(array(
            'foo' => 'custom',
            'bam' => 'boo',
        )));
    }

    public function testResolveWithoutOptionSucceedsIfRequiredAndDefaultValue()
    {
        $this->resolver->setRequired(array(
            'foo',
        ));
        $this->resolver->setDefaults(array(
            'foo' => 'bar',
        ));

        $this->assertEquals(array(
            'foo' => 'bar'
        ), $this->resolver->resolve(array()));
    }

    public function testResolveWithoutOptionSucceedsIfDefaultValueAndRequired()
    {
        $this->resolver->setDefaults(array(
            'foo' => 'bar',
        ));
        $this->resolver->setRequired(array(
            'foo',
        ));

        $this->assertEquals(array(
            'foo' => 'bar'
        ), $this->resolver->resolve(array()));
    }

    public function testResolveSucceedsIfOptionRequiredAndValueAllowed()
    {
        $this->resolver->setRequired(array(
            'one', 'two',
        ));
        $this->resolver->setAllowedValues(array(
            'two' => array('2'),
        ));

        $options = array(
            'one' => '1',
            'two' => '2'
        );

        $this->assertEquals($options, $this->resolver->resolve($options));
    }

    public function testClone()
    {
        $this->resolver->setDefaults(array('one' => '1'));

        $clone = clone $this->resolver;

        // Changes after cloning don't affect each other
        $this->resolver->setDefaults(array('two' => '2'));
        $clone->setDefaults(array('three' => '3'));

        $this->assertEquals(array(
            'one' => '1',
            'two' => '2',
        ), $this->resolver->resolve());

        $this->assertEquals(array(
            'one' => '1',
            'three' => '3',
        ), $clone->resolve());
    }
}
PKG1[ν�3;3;GOptionsResolver/Symfony/Component/OptionsResolver/Tests/OptionsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\OptionsResolver\Tests;

use Symfony\Component\OptionsResolver\Options;

class OptionsTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Options
     */
    private $options;

    protected function setUp()
    {
        $this->options = new Options();
    }

    public function testArrayAccess()
    {
        $this->assertFalse(isset($this->options['foo']));
        $this->assertFalse(isset($this->options['bar']));

        $this->options['foo'] = 0;
        $this->options['bar'] = 1;

        $this->assertTrue(isset($this->options['foo']));
        $this->assertTrue(isset($this->options['bar']));

        unset($this->options['bar']);

        $this->assertTrue(isset($this->options['foo']));
        $this->assertFalse(isset($this->options['bar']));
        $this->assertEquals(0, $this->options['foo']);
    }

    public function testCountable()
    {
        $this->options->set('foo', 0);
        $this->options->set('bar', 1);

        $this->assertCount(2, $this->options);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetNonExisting()
    {
        $this->options->get('foo');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testSetNotSupportedAfterGet()
    {
        $this->options->set('foo', 'bar');
        $this->options->get('foo');
        $this->options->set('foo', 'baz');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testRemoveNotSupportedAfterGet()
    {
        $this->options->set('foo', 'bar');
        $this->options->get('foo');
        $this->options->remove('foo');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testSetNormalizerNotSupportedAfterGet()
    {
        $this->options->set('foo', 'bar');
        $this->options->get('foo');
        $this->options->setNormalizer('foo', function () {});
    }

    public function testSetLazyOption()
    {
        $test = $this;

        $this->options->set('foo', function (Options $options) use ($test) {
           return 'dynamic';
        });

        $this->assertEquals('dynamic', $this->options->get('foo'));
    }

    public function testSetDiscardsPreviousValue()
    {
        $test = $this;

        // defined by superclass
        $this->options->set('foo', 'bar');

        // defined by subclass
        $this->options->set('foo', function (Options $options, $previousValue) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertNull($previousValue);

            return 'dynamic';
        });

        $this->assertEquals('dynamic', $this->options->get('foo'));
    }

    public function testOverloadKeepsPreviousValue()
    {
        $test = $this;

        // defined by superclass
        $this->options->set('foo', 'bar');

        // defined by subclass
        $this->options->overload('foo', function (Options $options, $previousValue) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $previousValue);

            return 'dynamic';
        });

        $this->assertEquals('dynamic', $this->options->get('foo'));
    }

    public function testPreviousValueIsEvaluatedIfLazy()
    {
        $test = $this;

        // defined by superclass
        $this->options->set('foo', function (Options $options) {
            return 'bar';
        });

        // defined by subclass
        $this->options->overload('foo', function (Options $options, $previousValue) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $previousValue);

            return 'dynamic';
        });

        $this->assertEquals('dynamic', $this->options->get('foo'));
    }

    public function testPreviousValueIsNotEvaluatedIfNoSecondArgument()
    {
        $test = $this;

        // defined by superclass
        $this->options->set('foo', function (Options $options) use ($test) {
            $test->fail('Should not be called');
        });

        // defined by subclass, no $previousValue argument defined!
        $this->options->overload('foo', function (Options $options) use ($test) {
            return 'dynamic';
        });

        $this->assertEquals('dynamic', $this->options->get('foo'));
    }

    public function testLazyOptionCanAccessOtherOptions()
    {
        $test = $this;

        $this->options->set('foo', 'bar');

        $this->options->set('bam', function (Options $options) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $options->get('foo'));

            return 'dynamic';
        });

        $this->assertEquals('bar', $this->options->get('foo'));
        $this->assertEquals('dynamic', $this->options->get('bam'));
    }

    public function testLazyOptionCanAccessOtherLazyOptions()
    {
        $test = $this;

        $this->options->set('foo', function (Options $options) {
            return 'bar';
        });

        $this->options->set('bam', function (Options $options) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $options->get('foo'));

            return 'dynamic';
        });

        $this->assertEquals('bar', $this->options->get('foo'));
        $this->assertEquals('dynamic', $this->options->get('bam'));
    }

    public function testNormalizer()
    {
        $this->options->set('foo', 'bar');

        $this->options->setNormalizer('foo', function () {
            return 'normalized';
        });

        $this->assertEquals('normalized', $this->options->get('foo'));
    }

    public function testNormalizerReceivesUnnormalizedValue()
    {
        $this->options->set('foo', 'bar');

        $this->options->setNormalizer('foo', function (Options $options, $value) {
            return 'normalized['.$value.']';
        });

        $this->assertEquals('normalized[bar]', $this->options->get('foo'));
    }

    public function testNormalizerCanAccessOtherOptions()
    {
        $test = $this;

        $this->options->set('foo', 'bar');
        $this->options->set('bam', 'baz');

        $this->options->setNormalizer('bam', function (Options $options) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $options->get('foo'));

            return 'normalized';
        });

        $this->assertEquals('bar', $this->options->get('foo'));
        $this->assertEquals('normalized', $this->options->get('bam'));
    }

    public function testNormalizerCanAccessOtherLazyOptions()
    {
        $test = $this;

        $this->options->set('foo', function (Options $options) {
            return 'bar';
        });
        $this->options->set('bam', 'baz');

        $this->options->setNormalizer('bam', function (Options $options) use ($test) {
            /* @var \PHPUnit_Framework_TestCase $test */
            $test->assertEquals('bar', $options->get('foo'));

            return 'normalized';
        });

        $this->assertEquals('bar', $this->options->get('foo'));
        $this->assertEquals('normalized', $this->options->get('bam'));
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testFailForCyclicDependencies()
    {
        $this->options->set('foo', function (Options $options) {
            $options->get('bam');
        });

        $this->options->set('bam', function (Options $options) {
            $options->get('foo');
        });

        $this->options->get('foo');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testFailForCyclicDependenciesBetweenNormalizers()
    {
        $this->options->set('foo', 'bar');
        $this->options->set('bam', 'baz');

        $this->options->setNormalizer('foo', function (Options $options) {
            $options->get('bam');
        });

        $this->options->setNormalizer('bam', function (Options $options) {
            $options->get('foo');
        });

        $this->options->get('foo');
    }

    /**
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testFailForCyclicDependenciesBetweenNormalizerAndLazyOption()
    {
        $this->options->set('foo', function (Options $options) {
            $options->get('bam');
        });
        $this->options->set('bam', 'baz');

        $this->options->setNormalizer('bam', function (Options $options) {
            $options->get('foo');
        });

        $this->options->get('foo');
    }

    public function testAllInvokesEachLazyOptionOnlyOnce()
    {
        $test = $this;
        $i = 1;

        $this->options->set('foo', function (Options $options) use ($test, &$i) {
            $test->assertSame(1, $i);
            ++$i;

            // Implicitly invoke lazy option for "bam"
            $options->get('bam');
        });
        $this->options->set('bam', function (Options $options) use ($test, &$i) {
            $test->assertSame(2, $i);
            ++$i;
        });

        $this->options->all();
    }

    public function testAllInvokesEachNormalizerOnlyOnce()
    {
        $test = $this;
        $i = 1;

        $this->options->set('foo', 'bar');
        $this->options->set('bam', 'baz');

        $this->options->setNormalizer('foo', function (Options $options) use ($test, &$i) {
            $test->assertSame(1, $i);
            ++$i;

            // Implicitly invoke normalizer for "bam"
            $options->get('bam');
        });
        $this->options->setNormalizer('bam', function (Options $options) use ($test, &$i) {
            $test->assertSame(2, $i);
            ++$i;
        });

        $this->options->all();
    }

    public function testReplaceClearsAndSets()
    {
        $this->options->set('one', '1');

        $this->options->replace(array(
            'two' => '2',
            'three' => function (Options $options) {
                return '2' === $options['two'] ? '3' : 'foo';
            }
        ));

        $this->assertEquals(array(
            'two' => '2',
            'three' => '3',
        ), $this->options->all());
    }

    public function testClearRemovesAllOptions()
    {
        $this->options->set('one', 1);
        $this->options->set('two', 2);

        $this->options->clear();

        $this->assertEmpty($this->options->all());

    }

    /**
     * @covers Symfony\Component\OptionsResolver\Options::replace
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testCannotReplaceAfterOptionWasRead()
    {
        $this->options->set('one', 1);
        $this->options->all();

        $this->options->replace(array(
            'two' => '2',
        ));
    }

    /**
     * @covers Symfony\Component\OptionsResolver\Options::overload
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testCannotOverloadAfterOptionWasRead()
    {
        $this->options->set('one', 1);
        $this->options->all();

        $this->options->overload('one', 2);
    }

    /**
     * @covers Symfony\Component\OptionsResolver\Options::clear
     * @expectedException \Symfony\Component\OptionsResolver\Exception\OptionDefinitionException
     */
    public function testCannotClearAfterOptionWasRead()
    {
        $this->options->set('one', 1);
        $this->options->all();

        $this->options->clear();
    }

    public function testOverloadCannotBeEvaluatedLazilyWithoutExpectedClosureParams()
    {
        $this->options->set('foo', 'bar');

        $this->options->overload('foo', function () {
            return 'test';
        });

        $this->assertNotEquals('test', $this->options->get('foo'));
        $this->assertTrue(is_callable($this->options->get('foo')));
    }

    public function testOverloadCannotBeEvaluatedLazilyWithoutFirstParamTypeHint()
    {
        $this->options->set('foo', 'bar');

        $this->options->overload('foo', function ($object) {
            return 'test';
        });

        $this->assertNotEquals('test', $this->options->get('foo'));
        $this->assertTrue(is_callable($this->options->get('foo')));
    }

    public function testOptionsIteration()
    {
        $this->options->set('foo', 'bar');
        $this->options->set('foo1', 'bar1');
        $expectedResult = array('foo' => 'bar', 'foo1' => 'bar1');

        $this->assertEquals($expectedResult, iterator_to_array($this->options, true));
    }

    public function testHasWithNullValue()
    {
        $this->options->set('foo', null);

        $this->assertTrue($this->options->has('foo'));
    }

    public function testRemoveOptionAndNormalizer()
    {
        $this->options->set('foo1', 'bar');
        $this->options->setNormalizer('foo1', function (Options $options) {
            return '';
        });
        $this->options->set('foo2', 'bar');
        $this->options->setNormalizer('foo2', function (Options $options) {
            return '';
        });

        $this->options->remove('foo2');
        $this->assertEquals(array('foo1' => ''), $this->options->all());
    }

    public function testReplaceOptionAndNormalizer()
    {
        $this->options->set('foo1', 'bar');
        $this->options->setNormalizer('foo1', function (Options $options) {
            return '';
        });
        $this->options->set('foo2', 'bar');
        $this->options->setNormalizer('foo2', function (Options $options) {
            return '';
        });

        $this->options->replace(array('foo1' => 'new'));
        $this->assertEquals(array('foo1' => 'new'), $this->options->all());
    }

    public function testClearOptionAndNormalizer()
    {
        $this->options->set('foo1', 'bar');
        $this->options->setNormalizer('foo1', function (Options $options) {
            return '';
        });
        $this->options->set('foo2', 'bar');
        $this->options->setNormalizer('foo2', function (Options $options) {
            return '';
        });

        $this->options->clear();
        $this->assertEmpty($this->options->all());
    }

    public function testNormalizerWithoutCorrespondingOption()
    {
        $test = $this;

        $this->options->setNormalizer('foo', function (Options $options, $previousValue) use ($test) {
            $test->assertNull($previousValue);

            return '';
        });
        $this->assertEquals(array('foo' => ''), $this->options->all());
    }
}
PKG1[��*/AABOptionsResolver/Symfony/Component/OptionsResolver/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony OptionsResolver Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKG1[<ȸB!!Net_SMTP/tests/auth.phptnu�[���--TEST--
Net_SMTP: SMTP Authentication
--SKIPIF--
<?php if (!@include('config.php')) die("skip\n");
--FILE--
<?php

require_once 'Net/SMTP.php';
require_once 'config.php';

if (! ($smtp = new Net_SMTP(TEST_HOSTNAME, TEST_PORT, TEST_LOCALHOST))) {
	die("Unable to instantiate Net_SMTP object\n");
}

if (PEAR::isError($e = $smtp->connect())) {
	die($e->getMessage() . "\n");
}

if (PEAR::isError($e = $smtp->auth(TEST_AUTH_USER, TEST_AUTH_PASS))) {
	die("Authentication failure\n");
}

$smtp->disconnect();

echo 'Success!';

--EXPECT--
Success!
PKG1[�߁Q��Net_SMTP/tests/quotedata.phptnu�[���--TEST--
Net_SMTP: quotedata()
--FILE--
<?php

require_once 'Net/SMTP.php';

$tests = array(
    /* Newlines */
    "\n"               => "\r\n",
    "\r\n"             => "\r\n",
    "\nxx"             => "\r\nxx",
    "xx\n"             => "xx\r\n",
    "xx\nxx"           => "xx\r\nxx",
    "\n\nxx"           => "\r\n\r\nxx",
    "xx\n\nxx"         => "xx\r\n\r\nxx",
    "xx\n\n"           => "xx\r\n\r\n",
    "\r\nxx"           => "\r\nxx",
    "xx\r\n"           => "xx\r\n",
    "xx\r\nxx"         => "xx\r\nxx",
    "\r\n\r\nxx"       => "\r\n\r\nxx",
    "xx\r\n\r\nxx"     => "xx\r\n\r\nxx",
    "xx\r\n\r\n"       => "xx\r\n\r\n",
    "\r\n\nxx"         => "\r\n\r\nxx",
    "\n\r\nxx"         => "\r\n\r\nxx",
    "xx\r\n\nxx"       => "xx\r\n\r\nxx",
    "xx\n\r\nxx"       => "xx\r\n\r\nxx",
    "xx\r\n\n"         => "xx\r\n\r\n",
    "xx\n\r\n"         => "xx\r\n\r\n",
    "\r"               => "\r\n",
    "\rxx"             => "\r\nxx",
    "xx\rxx"           => "xx\r\nxx",
    "xx\r"             => "xx\r\n",
    "\r\r"             => "\r\n\r\n",
    "\r\rxx"           => "\r\n\r\nxx",
    "xx\r\rxx"         => "xx\r\n\r\nxx",
    "xx\r\r"           => "xx\r\n\r\n",
    "xx\rxx\nxx\r\nxx" => "xx\r\nxx\r\nxx\r\nxx",
    "\r\r\n\n"         => "\r\n\r\n\r\n",

    /* Dots */
    "."                 => "..",
    "xxx\n."            => "xxx\r\n..",
    "xxx\n.\nxxx"       => "xxx\r\n..\r\nxxx",
    "xxx.\n.xxx"        => "xxx.\r\n..xxx",
);

function literal($x)
{
    return str_replace(array("\r", "\n"), array('\r', '\n'), $x);
}

$smtp = new Net_SMTP();
$error = false;
foreach ($tests as $input => $expected) {
    $output = $input;
    $smtp->quotedata($output);
    if ($output != $expected) {
        printf("Error: '%s' => '%s' (expected: '%s')",
            literal($input), literal($output), literal($expected));
        $error = true;
    }
}

if (!$error) {
    echo "success\n";
}

--EXPECT--
success
PKG1[�*�W��Net_SMTP/tests/basic.phptnu�[���--TEST--
Net_SMTP: Basic Functionality
--SKIPIF--
<?php if (!@include('config.php')) die("skip\n");
--FILE--
<?php

require_once 'Net/SMTP.php';
require_once 'config.php';

if (! ($smtp = new Net_SMTP(TEST_HOSTNAME, TEST_PORT, TEST_LOCALHOST))) {
    die("Unable to instantiate Net_SMTP object\n");
}

if (PEAR::isError($e = $smtp->connect())) {
    die($e->getMessage() . "\n");
}

if (PEAR::isError($e = $smtp->auth(TEST_AUTH_USER, TEST_AUTH_PASS))) {
    die("Authentication failure\n");
}

if (PEAR::isError($smtp->mailFrom(TEST_FROM))) {
    die('Unable to set sender to <' . TEST_FROM . ">\n");
}

if (PEAR::isError($res = $smtp->rcptTo(TEST_TO))) {
    die('Unable to add recipient <' . TEST_TO . '>: ' .
        $res->getMessage() . "\n");
}

$headers = 'Subject: ' . TEST_SUBJECT;
if (PEAR::isError($smtp->data(TEST_BODY, $headers))) {
    die("Unable to send data\n");
}

$smtp->disconnect();

echo 'Success!';

--EXPECT--
Success!
PKG1[�6����Net_SMTP/tests/config.php.distnu�[���<?php
/**
 * Copy this file to config.php and customize the following values to
 * suit your configuration.
 */

define('TEST_HOSTNAME',     'localhost');
define('TEST_PORT',         25);
define('TEST_LOCALHOST',    'localhost');
define('TEST_AUTH_USER',    'jon');
define('TEST_AUTH_PASS',    'secret');
define('TEST_FROM',         'from@example.com');
define('TEST_TO',           'to@example.com');
define('TEST_SUBJECT',      'Test Subject');
define('TEST_BODY',         'Test Body');
PKH1[�iH���AConfig/Symfony/Component/Config/Tests/Definition/EnumNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\EnumNode;

class EnumNodeTest extends \PHPUnit_Framework_TestCase
{
    public function testFinalizeValue()
    {
        $node = new EnumNode('foo', null, array('foo', 'bar'));
        $this->assertSame('foo', $node->finalize('foo'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testConstructionWithOneValue()
    {
        new EnumNode('foo', null, array('foo', 'foo'));
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar"
     */
    public function testFinalizeWithInvalidValue()
    {
        $node = new EnumNode('foo', null, array('foo', 'bar'));
        $node->finalize('foobar');
    }
}
PKH1[hͼ��FConfig/Symfony/Component/Config/Tests/Definition/NormalizationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\NodeInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class NormalizationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getEncoderTests
     */
    public function testNormalizeEncoders($denormalized)
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root_name', 'array')
                ->fixXmlConfig('encoder')
                ->children()
                    ->node('encoders', 'array')
                        ->useAttributeAsKey('class')
                        ->prototype('array')
                            ->beforeNormalization()->ifString()->then(function ($v) { return array('algorithm' => $v); })->end()
                            ->children()
                                ->node('algorithm', 'scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $normalized = array(
            'encoders' => array(
                'foo' => array('algorithm' => 'plaintext'),
            ),
        );

        $this->assertNormalized($tree, $denormalized, $normalized);
    }

    public function getEncoderTests()
    {
        $configs = array();

        // XML
        $configs[] = array(
            'encoder' => array(
                array('class' => 'foo', 'algorithm' => 'plaintext'),
            ),
        );

        // XML when only one element of this type
        $configs[] = array(
            'encoder' => array('class' => 'foo', 'algorithm' => 'plaintext'),
        );

        // YAML/PHP
        $configs[] = array(
            'encoders' => array(
                array('class' => 'foo', 'algorithm' => 'plaintext'),
            ),
        );

        // YAML/PHP
        $configs[] = array(
            'encoders' => array(
                'foo' => 'plaintext',
            ),
        );

        // YAML/PHP
        $configs[] = array(
            'encoders' => array(
                'foo' => array('algorithm' => 'plaintext'),
            ),
        );

        return array_map(function ($v) {
            return array($v);
        }, $configs);
    }

    /**
     * @dataProvider getAnonymousKeysTests
     */
    public function testAnonymousKeysArray($denormalized)
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root', 'array')
                ->children()
                    ->node('logout', 'array')
                        ->fixXmlConfig('handler')
                        ->children()
                            ->node('handlers', 'array')
                                ->prototype('scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $normalized = array('logout' => array('handlers' => array('a', 'b', 'c')));

        $this->assertNormalized($tree, $denormalized, $normalized);
    }

    public function getAnonymousKeysTests()
    {
        $configs = array();

        $configs[] = array(
            'logout' => array(
                'handlers' => array('a', 'b', 'c'),
            ),
        );

        $configs[] = array(
            'logout' => array(
                'handler' => array('a', 'b', 'c'),
            ),
        );

        return array_map(function ($v) { return array($v); }, $configs);
    }

    /**
     * @dataProvider getNumericKeysTests
     */
    public function testNumericKeysAsAttributes($denormalized)
    {
        $normalized = array(
            'thing' => array(42 => array('foo', 'bar'), 1337 => array('baz', 'qux')),
        );

        $this->assertNormalized($this->getNumericKeysTestTree(), $denormalized, $normalized);
    }

    public function getNumericKeysTests()
    {
        $configs = array();

        $configs[] = array(
            'thing' => array(
                42 => array('foo', 'bar'), 1337 => array('baz', 'qux'),
            ),
        );

        $configs[] = array(
            'thing' => array(
                array('foo', 'bar', 'id' => 42), array('baz', 'qux', 'id' => 1337),
            ),
        );

        return array_map(function ($v) { return array($v); }, $configs);
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The attribute "id" must be set for path "root.thing".
     */
    public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet()
    {
        $denormalized = array(
            'thing' => array(
                array('foo', 'bar'), array('baz', 'qux')
            )
        );

        $this->assertNormalized($this->getNumericKeysTestTree(), $denormalized, array());
    }

    public function testAssociativeArrayPreserveKeys()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root', 'array')
                ->prototype('array')
                    ->children()
                        ->node('foo', 'scalar')->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $data = array('first' => array('foo' => 'bar'));

        $this->assertNormalized($tree, $data, $data);
    }

    public static function assertNormalized(NodeInterface $tree, $denormalized, $normalized)
    {
        self::assertSame($normalized, $tree->normalize($denormalized));
    }

    private function getNumericKeysTestTree()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root', 'array')
                ->children()
                    ->node('thing', 'array')
                        ->useAttributeAsKey('id')
                        ->prototype('array')
                            ->prototype('scalar')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        return $tree;
    }
}
PKH1[�hE--BConfig/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\ScalarNode;

class ArrayNodeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException
     */
    public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed()
    {
        $node = new ArrayNode('root');
        $node->normalize(false);
    }

    /**
     * @expectedException        \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage Unrecognized options "foo" under "root"
     */
    public function testExceptionThrownOnUnrecognizedChild()
    {
        $node = new ArrayNode('root');
        $node->normalize(array('foo' => 'bar'));
    }

    /**
     * Tests that no exception is thrown for an unrecognized child if the
     * ignoreExtraKeys option is set to true.
     *
     * Related to testExceptionThrownOnUnrecognizedChild
     */
    public function testIgnoreExtraKeysNoException()
    {
        $node = new ArrayNode('roo');
        $node->setIgnoreExtraKeys(true);

        $node->normalize(array('foo' => 'bar'));
        $this->assertTrue(true, 'No exception was thrown when setIgnoreExtraKeys is true');
    }

    /**
     * @dataProvider getPreNormalizationTests
     */
    public function testPreNormalize($denormalized, $normalized)
    {
        $node = new ArrayNode('foo');

        $r = new \ReflectionMethod($node, 'preNormalize');
        $r->setAccessible(true);

        $this->assertSame($normalized, $r->invoke($node, $denormalized));
    }

    public function getPreNormalizationTests()
    {
        return array(
            array(
                array('foo-bar' => 'foo'),
                array('foo_bar' => 'foo'),
            ),
            array(
                array('foo-bar_moo' => 'foo'),
                array('foo-bar_moo' => 'foo'),
            ),
            array(
                array('foo-bar' => null, 'foo_bar' => 'foo'),
                array('foo-bar' => null, 'foo_bar' => 'foo'),
            )
        );
    }

    /**
     * @dataProvider getZeroNamedNodeExamplesData
     */
    public function testNodeNameCanBeZero($denormalized, $normalized)
    {
        $zeroNode = new ArrayNode(0);
        $zeroNode->addChild(new ScalarNode('name'));
        $fiveNode = new ArrayNode(5);
        $fiveNode->addChild(new ScalarNode(0));
        $fiveNode->addChild(new ScalarNode('new_key'));
        $rootNode = new ArrayNode('root');
        $rootNode->addChild($zeroNode);
        $rootNode->addChild($fiveNode);
        $rootNode->addChild(new ScalarNode('string_key'));
        $r = new \ReflectionMethod($rootNode, 'normalizeValue');
        $r->setAccessible(true);

        $this->assertSame($normalized, $r->invoke($rootNode, $denormalized));
    }

    public function getZeroNamedNodeExamplesData()
    {
        return array(
            array(
                array(
                    0 => array(
                        'name'    => 'something',
                    ),
                    5 => array(
                        0         => 'this won\'t work too',
                        'new_key' => 'some other value',
                    ),
                    'string_key'  => 'just value',
                ),
                array(
                    0 => array (
                        'name' => 'something',
                    ),
                    5 => array (
                        0 => 'this won\'t work too',
                        'new_key' => 'some other value',
                    ),
                    'string_key' => 'just value',
                ),
            ),
        );
    }

    /**
     * @dataProvider getPreNormalizedNormalizedOrderedData
     */
    public function testChildrenOrderIsMaintainedOnNormalizeValue($prenormalized, $normalized)
    {
        $scalar1 = new ScalarNode('1');
        $scalar2 = new ScalarNode('2');
        $scalar3 = new ScalarNode('3');
        $node = new ArrayNode('foo');
        $node->addChild($scalar1);
        $node->addChild($scalar3);
        $node->addChild($scalar2);

        $r = new \ReflectionMethod($node, 'normalizeValue');
        $r->setAccessible(true);

        $this->assertSame($normalized, $r->invoke($node, $prenormalized));
    }

    public function getPreNormalizedNormalizedOrderedData()
    {
        return array(
            array(
                array('2' => 'two', '1' => 'one', '3' => 'three'),
                array('2' => 'two', '1' => 'one', '3' => 'three'),
            ),
        );
    }
}
PKH1[����DConfig/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\IntegerNode;

class IntegerNodeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getValidValues
     */
    public function testNormalize($value)
    {
        $node = new IntegerNode('test');
        $this->assertSame($value, $node->normalize($value));
    }

    public function getValidValues()
    {
        return array(
            array(1798),
            array(-678),
            array(0),
        );
    }

    /**
     * @dataProvider getInvalidValues
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException
     */
    public function testNormalizeThrowsExceptionOnInvalidValues($value)
    {
        $node = new IntegerNode('test');
        $node->normalize($value);
    }

    public function getInvalidValues()
    {
        return array(
            array(null),
            array(''),
            array('foo'),
            array(true),
            array(false),
            array(0.0),
            array(0.1),
            array(array()),
            array(array('foo' => 'bar')),
            array(new \stdClass()),
        );
    }
}
PKH1[&]��BConfig/Symfony/Component/Config/Tests/Definition/FloatNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\FloatNode;

class FloatNodeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getValidValues
     */
    public function testNormalize($value)
    {
        $node = new FloatNode('test');
        $this->assertSame($value, $node->normalize($value));
    }

    public function getValidValues()
    {
        return array(
            array(1798.0),
            array(-678.987),
            array(12.56E45),
            array(0.0),
            // Integer are accepted too, they will be cast
            array(17),
            array(-10),
            array(0)
        );
    }

    /**
     * @dataProvider getInvalidValues
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException
     */
    public function testNormalizeThrowsExceptionOnInvalidValues($value)
    {
        $node = new FloatNode('test');
        $node->normalize($value);
    }

    public function getInvalidValues()
    {
        return array(
            array(null),
            array(''),
            array('foo'),
            array(true),
            array(false),
            array(array()),
            array(array('foo' => 'bar')),
            array(new \stdClass()),
        );
    }
}
PKH1[�-1��LConfig/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class ExprBuilderTest extends \PHPUnit_Framework_TestCase
{

    public function testAlwaysExpression()
    {
        $test = $this->getTestBuilder()
            ->always($this->returnClosure('new_value'))
        ->end();

        $this->assertFinalizedValueIs('new_value', $test);
    }

    public function testIfTrueExpression()
    {
        $test = $this->getTestBuilder()
            ->ifTrue()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test, array('key'=>true));

        $test = $this->getTestBuilder()
            ->ifTrue( function ($v) { return true; })
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test);

        $test = $this->getTestBuilder()
            ->ifTrue( function ($v) { return false; })
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('value',$test);
    }

    public function testIfStringExpression()
    {
        $test = $this->getTestBuilder()
            ->ifString()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test);

        $test = $this->getTestBuilder()
            ->ifString()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs(45, $test, array('key'=>45));

    }

    public function testIfNullExpression()
    {
        $test = $this->getTestBuilder()
            ->ifNull()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test, array('key'=>null));

        $test = $this->getTestBuilder()
            ->ifNull()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('value', $test);
    }

    public function testIfArrayExpression()
    {
        $test = $this->getTestBuilder()
            ->ifArray()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test, array('key'=>array()));

        $test = $this->getTestBuilder()
            ->ifArray()
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('value', $test);
    }

    public function testIfInArrayExpression()
    {
        $test = $this->getTestBuilder()
            ->ifInArray(array('foo', 'bar', 'value'))
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test);

        $test = $this->getTestBuilder()
            ->ifInArray(array('foo', 'bar'))
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('value', $test);
    }

    public function testIfNotInArrayExpression()
    {
        $test = $this->getTestBuilder()
            ->ifNotInArray(array('foo', 'bar'))
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test);

        $test = $this->getTestBuilder()
            ->ifNotInArray(array('foo', 'bar', 'value_from_config' ))
            ->then($this->returnClosure('new_value'))
        ->end();
        $this->assertFinalizedValueIs('new_value', $test);
    }

    public function testThenEmptyArrayExpression()
    {
        $test = $this->getTestBuilder()
            ->ifString()
            ->thenEmptyArray()
        ->end();
        $this->assertFinalizedValueIs(array(), $test);
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     */
    public function testThenInvalid()
    {
        $test = $this->getTestBuilder()
            ->ifString()
            ->thenInvalid('Invalid value')
        ->end();
        $this->finalizeTestBuilder($test);
    }

    public function testThenUnsetExpression()
    {
        $test = $this->getTestBuilder()
            ->ifString()
            ->thenUnset()
        ->end();
        $this->assertEquals(array(), $this->finalizeTestBuilder($test));
    }

    /**
     * Create a test treebuilder with a variable node, and init the validation
     * @return TreeBuilder
     */
    protected function getTestBuilder()
    {
        $builder = new TreeBuilder();

        return $builder
            ->root('test')
            ->children()
            ->variableNode('key')
            ->validate()
       ;
    }

    /**
     * Close the validation process and finalize with the given config
     * @param TreeBuilder $testBuilder The tree builder to finalize
     * @param array       $config      The config you want to use for the finalization, if nothing provided
     *                       a simple array('key'=>'value') will be used
     * @return array The finalized config values
     */
    protected function finalizeTestBuilder($testBuilder, $config = null)
    {
        return $testBuilder
            ->end()
            ->end()
            ->end()
            ->buildTree()
            ->finalize($config === null ? array('key'=>'value') : $config)
        ;
    }

    /**
     * Return a closure that will return the given value
     * @param $val The value that the closure must return
     * @return Closure
     */
    protected function returnClosure($val)
    {
        return function ($v) use ($val) {
            return $val;
        };
    }

    /**
     * Assert that the given test builder, will return the given value
     *
     * @param mixed       $value       The value to test
     * @param TreeBuilder $treeBuilder The tree builder to finalize
     * @param mixed       $config      The config values that new to be finalized
     */
    protected function assertFinalizedValueIs($value, $treeBuilder, $config = null)
    {
        $this->assertEquals(array('key'=>$value), $this->finalizeTestBuilder($treeBuilder, $config));
    }
}
PKH1[<�C��SConfig/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\EnumNodeDefinition;

class EnumNodeDefinitionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage ->values() must be called with at least two distinct values.
     */
    public function testNoDistinctValues()
    {
        $def = new EnumNodeDefinition('foo');
        $def->values(array('foo', 'foo'));
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage You must call ->values() on enum nodes.
     */
    public function testNoValuesPassed()
    {
        $def = new EnumNodeDefinition('foo');
        $def->getNode();
    }

    public function testGetNode()
    {
        $def = new EnumNodeDefinition('foo');
        $def->values(array('foo', 'bar'));

        $node = $def->getNode();
        $this->assertEquals(array('foo', 'bar'), $node->getValues());
    }
}
PKH1[wX��TConfig/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Definition\Builder\ScalarNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidDefinitionException;

class ArrayNodeDefinitionTest extends \PHPUnit_Framework_TestCase
{
    public function testAppendingSomeNode()
    {
        $parent = new ArrayNodeDefinition('root');
        $child = new ScalarNodeDefinition('child');

        $parent
            ->children()
                ->scalarNode('foo')->end()
                ->scalarNode('bar')->end()
            ->end()
            ->append($child);

        $this->assertCount(3, $this->getField($parent, 'children'));
        $this->assertTrue(in_array($child, $this->getField($parent, 'children')));
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
     * @dataProvider providePrototypeNodeSpecificCalls
     */
    public function testPrototypeNodeSpecificOption($method, $args)
    {
        $node = new ArrayNodeDefinition('root');

        call_user_func_array(array($node, $method), $args);

        $node->getNode();
    }

    public function providePrototypeNodeSpecificCalls()
    {
        return array(
            array('defaultValue', array(array())),
            array('addDefaultChildrenIfNoneSet', array()),
            array('requiresAtLeastOneElement', array()),
            array('useAttributeAsKey', array('foo'))
        );
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
     */
    public function testConcreteNodeSpecificOption()
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->addDefaultsIfNotSet()
            ->prototype('array')
        ;
        $node->getNode();
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException
     */
    public function testPrototypeNodesCantHaveADefaultValueWhenUsingDefaultChildren()
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->defaultValue(array())
            ->addDefaultChildrenIfNoneSet('foo')
            ->prototype('array')
        ;
        $node->getNode();
    }

    public function testPrototypedArrayNodeDefaultWhenUsingDefaultChildren()
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->addDefaultChildrenIfNoneSet()
            ->prototype('array')
        ;
        $tree = $node->getNode();
        $this->assertEquals(array(array()), $tree->getDefaultValue());
    }

    /**
     * @dataProvider providePrototypedArrayNodeDefaults
     */
    public function testPrototypedArrayNodeDefault($args, $shouldThrowWhenUsingAttrAsKey, $shouldThrowWhenNotUsingAttrAsKey, $defaults)
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->addDefaultChildrenIfNoneSet($args)
            ->prototype('array')
        ;

        try {
            $tree = $node->getNode();
            $this->assertFalse($shouldThrowWhenNotUsingAttrAsKey);
            $this->assertEquals($defaults, $tree->getDefaultValue());
        } catch (InvalidDefinitionException $e) {
            $this->assertTrue($shouldThrowWhenNotUsingAttrAsKey);
        }

        $node = new ArrayNodeDefinition('root');
        $node
            ->useAttributeAsKey('attr')
            ->addDefaultChildrenIfNoneSet($args)
            ->prototype('array')
        ;

        try {
            $tree = $node->getNode();
            $this->assertFalse($shouldThrowWhenUsingAttrAsKey);
            $this->assertEquals($defaults, $tree->getDefaultValue());
        } catch (InvalidDefinitionException $e) {
            $this->assertTrue($shouldThrowWhenUsingAttrAsKey);
        }
    }

    public function providePrototypedArrayNodeDefaults()
    {
        return array(
            array(null, true, false, array(array())),
            array(2, true, false, array(array(), array())),
            array('2', false, true, array('2' => array())),
            array('foo', false, true, array('foo' => array())),
            array(array('foo'), false, true, array('foo' => array())),
            array(array('foo', 'bar'), false, true, array('foo' => array(), 'bar' => array())),
        );
    }

    public function testNestedPrototypedArrayNodes()
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->addDefaultChildrenIfNoneSet()
            ->prototype('array')
                  ->prototype('array')
        ;
        $node->getNode();
    }

    public function testEnabledNodeDefaults()
    {
        $node = new ArrayNodeDefinition('root');
        $node
            ->canBeEnabled()
            ->children()
                ->scalarNode('foo')->defaultValue('bar')->end()
        ;

        $this->assertEquals(array('enabled' => false, 'foo' => 'bar'), $node->getNode()->getDefaultValue());
    }

    /**
     * @dataProvider getEnableableNodeFixtures
     */
    public function testTrueEnableEnabledNode($expected, $config, $message)
    {
        $processor = new Processor();
        $node = new ArrayNodeDefinition('root');
        $node
            ->canBeEnabled()
            ->children()
                ->scalarNode('foo')->defaultValue('bar')->end()
        ;

        $this->assertEquals(
            $expected,
            $processor->process($node->getNode(), $config),
            $message
        );
    }

    public function getEnableableNodeFixtures()
    {
        return array(
            array(array('enabled' => true, 'foo' => 'bar'), array(true), 'true enables an enableable node'),
            array(array('enabled' => true, 'foo' => 'bar'), array(null), 'null enables an enableable node'),
            array(array('enabled' => true, 'foo' => 'bar'), array(array('enabled' => true)), 'An enableable node can be enabled'),
            array(array('enabled' => true, 'foo' => 'baz'), array(array('foo' => 'baz')), 'any configuration enables an enableable node'),
            array(array('enabled' => false, 'foo' => 'baz'), array(array('foo' => 'baz', 'enabled' => false)), 'An enableable node can be disabled'),
            array(array('enabled' => false, 'foo' => 'bar'), array(false), 'false disables an enableable node'),
        );
    }

    protected function getField($object, $field)
    {
        $reflection = new \ReflectionProperty($object, $field);
        $reflection->setAccessible(true);

        return $reflection->getValue($object);
    }
}
PKH1[
Kmޮ
�
LConfig/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder;
use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition;

class NodeBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \RuntimeException
     */
    public function testThrowsAnExceptionWhenTryingToCreateANonRegisteredNodeType()
    {
        $builder = new BaseNodeBuilder();
        $builder->node('', 'foobar');
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testThrowsAnExceptionWhenTheNodeClassIsNotFound()
    {
        $builder = new BaseNodeBuilder();
        $builder
            ->setNodeClass('noclasstype', '\\foo\\bar\\noclass')
            ->node('', 'noclasstype');
    }

    public function testAddingANewNodeType()
    {
        $class = __NAMESPACE__.'\\SomeNodeDefinition';

        $builder = new BaseNodeBuilder();
        $node = $builder
            ->setNodeClass('newtype', $class)
            ->node('', 'newtype');

        $this->assertInstanceOf($class, $node);
    }

    public function testOverridingAnExistingNodeType()
    {
        $class = __NAMESPACE__.'\\SomeNodeDefinition';

        $builder = new BaseNodeBuilder();
        $node = $builder
            ->setNodeClass('variable', $class)
            ->node('', 'variable');

        $this->assertInstanceOf($class, $node);
    }

    public function testNodeTypesAreNotCaseSensitive()
    {
        $builder = new BaseNodeBuilder();

        $node1 = $builder->node('', 'VaRiAbLe');
        $node2 = $builder->node('', 'variable');

        $this->assertInstanceOf(get_class($node1), $node2);

        $builder->setNodeClass('CuStOm', __NAMESPACE__.'\\SomeNodeDefinition');

        $node1 = $builder->node('', 'CUSTOM');
        $node2 = $builder->node('', 'custom');

        $this->assertInstanceOf(get_class($node1), $node2);
    }

    public function testNumericNodeCreation()
    {
        $builder = new NodeBuilder();

        $node = $builder->integerNode('foo')->min(3)->max(5);
        $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition', $node);

        $node = $builder->floatNode('bar')->min(3.0)->max(5.0);
        $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\FloatNodeDefinition', $node);
    }
}

class SomeNodeDefinition extends BaseVariableNodeDefinition
{
}
PKH1[�����LConfig/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Tests\Definition\Builder\NodeBuilder as CustomNodeBuilder;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;

require __DIR__.'/../../Fixtures/Builder/NodeBuilder.php';
require __DIR__.'/../../Fixtures/Builder/BarNodeDefinition.php';
require __DIR__.'/../../Fixtures/Builder/VariableNodeDefinition.php';

class TreeBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testUsingACustomNodeBuilder()
    {
        $builder = new TreeBuilder();
        $root = $builder->root('custom', 'array', new CustomNodeBuilder());

        $nodeBuilder = $root->children();

        $this->assertInstanceOf('Symfony\Component\Config\Tests\Definition\Builder\NodeBuilder', $nodeBuilder);

        $nodeBuilder = $nodeBuilder->arrayNode('deeper')->children();

        $this->assertInstanceOf('Symfony\Component\Config\Tests\Definition\Builder\NodeBuilder', $nodeBuilder);
    }

    public function testOverrideABuiltInNodeType()
    {
        $builder = new TreeBuilder();
        $root = $builder->root('override', 'array', new CustomNodeBuilder());

        $definition = $root->children()->variableNode('variable');

        $this->assertInstanceOf('Symfony\Component\Config\Tests\Definition\Builder\VariableNodeDefinition', $definition);
    }

    public function testAddANodeType()
    {
        $builder = new TreeBuilder();
        $root = $builder->root('override', 'array', new CustomNodeBuilder());

        $definition = $root->children()->barNode('variable');

        $this->assertInstanceOf('Symfony\Component\Config\Tests\Definition\Builder\BarNodeDefinition', $definition);
    }

    public function testCreateABuiltInNodeTypeWithACustomNodeBuilder()
    {
        $builder = new TreeBuilder();
        $root = $builder->root('builtin', 'array', new CustomNodeBuilder());

        $definition = $root->children()->booleanNode('boolean');

        $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition', $definition);
    }

    public function testPrototypedArrayNodeUseTheCustomNodeBuilder()
    {
        $builder = new TreeBuilder();
        $root = $builder->root('override', 'array', new CustomNodeBuilder());

        $root->prototype('bar')->end();
    }

    public function testAnExtendedNodeBuilderGetsPropagatedToTheChildren()
    {
        $builder = new TreeBuilder();

        $builder->root('propagation')
            ->children()
                ->setNodeClass('extended', 'Symfony\Component\Config\Tests\Definition\Builder\VariableNodeDefinition')
                ->node('foo', 'extended')->end()
                ->arrayNode('child')
                    ->children()
                        ->node('foo', 'extended')
                    ->end()
                ->end()
            ->end()
        ->end();
    }

    public function testDefinitionInfoGetsTransferredToNode()
    {
        $builder = new TreeBuilder();

        $builder->root('test')->info('root info')
            ->children()
                ->node('child', 'variable')->info('child info')->defaultValue('default')
            ->end()
        ->end();

        $tree = $builder->buildTree();
        $children = $tree->getChildren();

        $this->assertEquals('root info', $tree->getInfo());
        $this->assertEquals('child info', $children['child']->getInfo());
    }

    public function testDefinitionExampleGetsTransferredToNode()
    {
        $builder = new TreeBuilder();

        $builder->root('test')
            ->example(array('key' => 'value'))
            ->children()
                ->node('child', 'variable')->info('child info')->defaultValue('default')->example('example')
            ->end()
        ->end();

        $tree = $builder->buildTree();
        $children = $tree->getChildren();

        $this->assertTrue(is_array($tree->getExample()));
        $this->assertEquals('example', $children['child']->getExample());
    }
}
PKH1[Ej~�jjVConfig/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition as NumericNodeDefinition;
use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition;
use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition;

class NumericNodeDefinitionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage You cannot define a min(4) as you already have a max(3)
     */
    public function testIncoherentMinAssertion()
    {
        $def = new NumericNodeDefinition('foo');
        $def->max(3)->min(4);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage You cannot define a max(2) as you already have a min(3)
     */
    public function testIncoherentMaxAssertion()
    {
        $node = new NumericNodeDefinition('foo');
        $node->min(3)->max(2);
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The value 4 is too small for path "foo". Should be greater than or equal to 5
     */
    public function testIntegerMinAssertion()
    {
        $def = new IntegerNodeDefinition('foo');
        $def->min(5)->getNode()->finalize(4);
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The value 4 is too big for path "foo". Should be less than or equal to 3
     */
    public function testIntegerMaxAssertion()
    {
        $def = new IntegerNodeDefinition('foo');
        $def->max(3)->getNode()->finalize(4);
    }

    public function testIntegerValidMinMaxAssertion()
    {
        $def = new IntegerNodeDefinition('foo');
        $node = $def->min(3)->max(7)->getNode();
        $this->assertEquals(4, $node->finalize(4));
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The value 400 is too small for path "foo". Should be greater than or equal to 500
     */
    public function testFloatMinAssertion()
    {
        $def = new FloatNodeDefinition('foo');
        $def->min(5E2)->getNode()->finalize(4e2);
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     * @expectedExceptionMessage The value 4.3 is too big for path "foo". Should be less than or equal to 0.3
     */
    public function testFloatMaxAssertion()
    {
        $def = new FloatNodeDefinition('foo');
        $def->max(0.3)->getNode()->finalize(4.3);
    }

    public function testFloatValidMinMaxAssertion()
    {
        $def = new FloatNodeDefinition('foo');
        $node = $def->min(3.0)->max(7e2)->getNode();
        $this->assertEquals(4.5, $node->finalize(4.5));
    }
}
PKH1[jO灃�CConfig/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\ScalarNode;

class ScalarNodeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getValidValues
     */
    public function testNormalize($value)
    {
        $node = new ScalarNode('test');
        $this->assertSame($value, $node->normalize($value));
    }

    public function getValidValues()
    {
        return array(
            array(false),
            array(true),
            array(null),
            array(''),
            array('foo'),
            array(0),
            array(1),
            array(0.0),
            array(0.1),
        );
    }

    /**
     * @dataProvider getInvalidValues
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException
     */
    public function testNormalizeThrowsExceptionOnInvalidValues($value)
    {
        $node = new ScalarNode('test');
        $node->normalize($value);
    }

    public function getInvalidValues()
    {
        return array(
            array(array()),
            array(array('foo' => 'bar')),
            array(new \stdClass()),
        );
    }
}
PKH1[�y���SConfig/Symfony/Component/Config/Tests/Definition/Dumper/YamlReferenceDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Dumper;

use Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper;
use Symfony\Component\Config\Tests\Fixtures\Configuration\ExampleConfiguration;

class YamlReferenceDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDumper()
    {
        $configuration = new ExampleConfiguration();

        $dumper = new YamlReferenceDumper();

        $this->markTestIncomplete('The Yaml Dumper currently does not support prototyped arrays');
        $this->assertEquals($this->getConfigurationAsString(), $dumper->dump($configuration));
    }

    private function getConfigurationAsString()
    {
      return <<<EOL
acme_root:
    boolean:              true
    scalar_empty:         ~
    scalar_null:          ~
    scalar_true:          true
    scalar_false:         false
    scalar_default:       default
    scalar_array_empty:   []
    scalar_array_defaults:

        # Defaults:
        - elem1
        - elem2
    scalar_required:      ~ # Required
    enum:                 ~ # One of "this"; "that"

    # some info
    array:
        child1:               ~
        child2:               ~

        # this is a long
        # multi-line info text
        # which should be indented
        child3:               ~ # Example: example setting
    parameters:

        # Prototype
        name:                 ~
    connections:
        # Prototype
        - { user: ~, pass: ~ }

EOL;
    }
}
PKH1[~�P+RConfig/Symfony/Component/Config/Tests/Definition/Dumper/XmlReferenceDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Dumper;

use Symfony\Component\Config\Definition\Dumper\XmlReferenceDumper;
use Symfony\Component\Config\Tests\Fixtures\Configuration\ExampleConfiguration;

class XmlReferenceDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testDumper()
    {
        $configuration = new ExampleConfiguration();

        $dumper = new XmlReferenceDumper();
        $this->assertEquals($this->getConfigurationAsString(), $dumper->dump($configuration));
    }

    public function testNamespaceDumper()
    {
        $configuration = new ExampleConfiguration();

        $dumper = new XmlReferenceDumper();
        $this->assertEquals(str_replace('http://example.org/schema/dic/acme_root', 'http://symfony.com/schema/dic/symfony', $this->getConfigurationAsString()), $dumper->dump($configuration, 'http://symfony.com/schema/dic/symfony'));
    }

    private function getConfigurationAsString()
    {
      return <<<EOL
<!-- Namespace: http://example.org/schema/dic/acme_root -->
<!-- scalar-required: Required -->
<!-- enum: One of "this"; "that" -->
<config
    boolean="true"
    scalar-empty=""
    scalar-null="null"
    scalar-true="true"
    scalar-false="false"
    scalar-default="default"
    scalar-array-empty=""
    scalar-array-defaults="elem1,elem2"
    scalar-required=""
    enum=""
>

    <!-- some info -->
    <!--
        child3: this is a long
                multi-line info text
                which should be indented;
                Example: example setting
    -->
    <array
        child1=""
        child2=""
        child3=""
    />

    <!-- prototype -->
    <parameter name="parameter name">scalar value</parameter>

    <!-- prototype -->
    <connection
        user=""
        pass=""
    />

</config>

EOL;
    }
}
PKH1[D�99>Config/Symfony/Component/Config/Tests/Definition/MergeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;

class MergeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException
     */
    public function testForbiddenOverwrite()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root', 'array')
                ->children()
                    ->node('foo', 'scalar')
                        ->cannotBeOverwritten()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $a = array(
            'foo' => 'bar',
        );

        $b = array(
            'foo' => 'moo',
        );

        $tree->merge($a, $b);
    }

    public function testUnsetKey()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('root', 'array')
                ->children()
                    ->node('foo', 'scalar')->end()
                    ->node('bar', 'scalar')->end()
                    ->node('unsettable', 'array')
                        ->canBeUnset()
                        ->children()
                            ->node('foo', 'scalar')->end()
                            ->node('bar', 'scalar')->end()
                        ->end()
                    ->end()
                    ->node('unsetted', 'array')
                        ->canBeUnset()
                        ->prototype('scalar')->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $a = array(
            'foo' => 'bar',
            'unsettable' => array(
                'foo' => 'a',
                'bar' => 'b',
            ),
            'unsetted' => false,
        );

        $b = array(
            'foo' => 'moo',
            'bar' => 'b',
            'unsettable' => false,
            'unsetted' => array('a', 'b'),
        );

        $this->assertEquals(array(
            'foo' => 'moo',
            'bar' => 'b',
            'unsettable' => false,
            'unsetted' => array('a', 'b'),
        ), $tree->merge($a, $b));
    }

    /**
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     */
    public function testDoesNotAllowNewKeysInSubsequentConfigs()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('config', 'array')
                ->children()
                    ->node('test', 'array')
                        ->disallowNewKeysInSubsequentConfigs()
                        ->useAttributeAsKey('key')
                        ->prototype('array')
                            ->children()
                                ->node('value', 'scalar')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree();

        $a = array(
            'test' => array(
                'a' => array('value' => 'foo')
            )
        );

        $b = array(
            'test' => array(
                'b' => array('value' => 'foo')
            )
        );

        $tree->merge($a, $b);
    }

    public function testPerformsNoDeepMerging()
    {
        $tb = new TreeBuilder();

        $tree = $tb
            ->root('config', 'array')
                ->children()
                    ->node('no_deep_merging', 'array')
                        ->performNoDeepMerging()
                        ->children()
                            ->node('foo', 'scalar')->end()
                            ->node('bar', 'scalar')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $a = array(
            'no_deep_merging' => array(
                'foo' => 'a',
                'bar' => 'b',
            ),
        );

        $b = array(
            'no_deep_merging' => array(
                'c' => 'd',
            )
        );

        $this->assertEquals(array(
            'no_deep_merging' => array(
                'c' => 'd',
            )
        ), $tree->merge($a, $b));
    }

    public function testPrototypeWithoutAKeyAttribute()
    {
        $tb = new TreeBuilder();

        $tree = $tb
            ->root('config', 'array')
                ->children()
                    ->arrayNode('append_elements')
                        ->prototype('scalar')->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $a = array(
            'append_elements' => array('a', 'b'),
        );

        $b = array(
            'append_elements' => array('c', 'd'),
        );

        $this->assertEquals(array('append_elements' => array('a', 'b', 'c', 'd')), $tree->merge($a, $b));
    }
}
PKI1[A�RREConfig/Symfony/Component/Config/Tests/Definition/FinalizationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\Definition\NodeInterface;

class FinalizationTest extends \PHPUnit_Framework_TestCase
{
    public function testUnsetKeyWithDeepHierarchy()
    {
        $tb = new TreeBuilder();
        $tree = $tb
            ->root('config', 'array')
                ->children()
                    ->node('level1', 'array')
                        ->canBeUnset()
                        ->children()
                            ->node('level2', 'array')
                                ->canBeUnset()
                                ->children()
                                    ->node('somevalue', 'scalar')->end()
                                    ->node('anothervalue', 'scalar')->end()
                                ->end()
                            ->end()
                            ->node('level1_scalar', 'scalar')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
            ->buildTree()
        ;

        $a = array(
            'level1' => array(
                'level2' => array(
                    'somevalue' => 'foo',
                    'anothervalue' => 'bar',
                ),
                'level1_scalar' => 'foo',
            ),
        );

        $b = array(
            'level1' => array(
                'level2' => false,
            ),
        );

        $this->assertEquals(array(
            'level1' => array(
                'level1_scalar' => 'foo',
            ),
        ), $this->process($tree, array($a, $b)));
    }

    protected function process(NodeInterface $tree, array $configs)
    {
        $processor = new Processor();

        return $processor->process($tree, $configs);
    }
}
PKI1[{���DConfig/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\BooleanNode;

class BooleanNodeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getValidValues
     */
    public function testNormalize($value)
    {
        $node = new BooleanNode('test');
        $this->assertSame($value, $node->normalize($value));
    }

    public function getValidValues()
    {
        return array(
            array(false),
            array(true),
        );
    }

    /**
     * @dataProvider getInvalidValues
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException
     */
    public function testNormalizeThrowsExceptionOnInvalidValues($value)
    {
        $node = new BooleanNode('test');
        $node->normalize($value);
    }

    public function getInvalidValues()
    {
        return array(
            array(null),
            array(''),
            array('foo'),
            array(0),
            array(1),
            array(0.0),
            array(0.1),
            array(array()),
            array(array('foo' => 'bar')),
            array(new \stdClass()),
        );
    }
}
PKI1[%Jbx��LConfig/Symfony/Component/Config/Tests/Definition/PrototypedArrayNodeTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition;

use Symfony\Component\Config\Definition\PrototypedArrayNode;
use Symfony\Component\Config\Definition\ArrayNode;
use Symfony\Component\Config\Definition\ScalarNode;

class PrototypedArrayNodeTest extends \PHPUnit_Framework_TestCase
{
    public function testGetDefaultValueReturnsAnEmptyArrayForPrototypes()
    {
        $node = new PrototypedArrayNode('root');
        $prototype = new ArrayNode(null, $node);
        $node->setPrototype($prototype);
        $this->assertEmpty($node->getDefaultValue());
    }

    public function testGetDefaultValueReturnsDefaultValueForPrototypes()
    {
        $node = new PrototypedArrayNode('root');
        $prototype = new ArrayNode(null, $node);
        $node->setPrototype($prototype);
        $node->setDefaultValue(array('test'));
        $this->assertEquals(array('test'), $node->getDefaultValue());
    }

    // a remapped key (e.g. "mapping" -> "mappings") should be unset after being used
    public function testRemappedKeysAreUnset()
    {
        $node = new ArrayNode('root');
        $mappingsNode = new PrototypedArrayNode('mappings');
        $node->addChild($mappingsNode);

        // each item under mappings is just a scalar
        $prototype = new ScalarNode(null, $mappingsNode);
        $mappingsNode->setPrototype($prototype);

        $remappings = array();
        $remappings[] = array('mapping', 'mappings');
        $node->setXmlRemappings($remappings);

        $normalized = $node->normalize(array('mapping' => array('foo', 'bar')));
        $this->assertEquals(array('mappings' => array('foo', 'bar')), $normalized);
    }

    /**
     * Tests that when a key attribute is mapped, that key is removed from the array:
     *
     *     <things>
     *         <option id="option1" value="foo">
     *         <option id="option2" value="bar">
     *     </things>
     *
     * The above should finally be mapped to an array that looks like this
     * (because "id" is the key attribute).
     *
     *     array(
     *         'things' => array(
     *             'option1' => 'foo',
     *             'option2' => 'bar',
     *         )
     *     )
     */
    public function testMappedAttributeKeyIsRemoved()
    {
        $node = new PrototypedArrayNode('root');
        $node->setKeyAttribute('id', true);

        // each item under the root is an array, with one scalar item
        $prototype = new ArrayNode(null, $node);
        $prototype->addChild(new ScalarNode('foo'));
        $node->setPrototype($prototype);

        $children = array();
        $children[] = array('id' => 'item_name', 'foo' => 'bar');
        $normalized = $node->normalize($children);

        $expected = array();
        $expected['item_name'] = array('foo' => 'bar');
        $this->assertEquals($expected, $normalized);
    }

    /**
     * Tests the opposite of the testMappedAttributeKeyIsRemoved because
     * the removal can be toggled with an option.
     */
    public function testMappedAttributeKeyNotRemoved()
    {
        $node = new PrototypedArrayNode('root');
        $node->setKeyAttribute('id', false);

        // each item under the root is an array, with two scalar items
        $prototype = new ArrayNode(null, $node);
        $prototype->addChild(new ScalarNode('foo'));
        $prototype->addChild(new ScalarNode('id')); // the key attribute will remain
        $node->setPrototype($prototype);

        $children = array();
        $children[] = array('id' => 'item_name', 'foo' => 'bar');
        $normalized = $node->normalize($children);

        $expected = array();
        $expected['item_name'] = array('id' => 'item_name', 'foo' => 'bar');
        $this->assertEquals($expected, $normalized);
    }

    public function testAddDefaultChildren()
    {
        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setAddChildrenIfNoneSet();
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array(array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setKeyAttribute('foobar');
        $node->setAddChildrenIfNoneSet();
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array('defaults' => array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setKeyAttribute('foobar');
        $node->setAddChildrenIfNoneSet('defaultkey');
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array('defaultkey' => array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setKeyAttribute('foobar');
        $node->setAddChildrenIfNoneSet(array('defaultkey'));
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array('defaultkey' => array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setKeyAttribute('foobar');
        $node->setAddChildrenIfNoneSet(array('dk1', 'dk2'));
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array('dk1' => array('foo' => 'bar'), 'dk2' => array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setAddChildrenIfNoneSet(array(5, 6));
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array(0 => array('foo' => 'bar'), 1 => array('foo' => 'bar')), $node->getDefaultValue());

        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setAddChildrenIfNoneSet(2);
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array(array('foo' => 'bar'), array('foo' => 'bar')), $node->getDefaultValue());
    }

    public function testDefaultChildrenWinsOverDefaultValue()
    {
        $node = $this->getPrototypeNodeWithDefaultChildren();
        $node->setAddChildrenIfNoneSet();
        $node->setDefaultValue(array('bar' => 'foo'));
        $this->assertTrue($node->hasDefaultValue());
        $this->assertEquals(array(array('foo' => 'bar')), $node->getDefaultValue());
    }

    protected function getPrototypeNodeWithDefaultChildren()
    {
        $node = new PrototypedArrayNode('root');
        $prototype = new ArrayNode(null, $node);
        $child = new ScalarNode('foo');
        $child->setDefaultValue('bar');
        $prototype->addChild($child);
        $prototype->setAddIfNotSet(true);
        $node->setPrototype($prototype);

        return $node;
    }
}
PKI1[�b�..?Config/Symfony/Component/Config/Tests/Fixtures/Util/invalid.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<root>
PKI1[c=���EConfig/Symfony/Component/Config/Tests/Fixtures/Util/document_type.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE scan [<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource={{ resource }}">]>
<scan></scan>
PKI1[Gɩ�SSFConfig/Symfony/Component/Config/Tests/Fixtures/Util/invalid_schema.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<root2 xmlns="http://example.com/schema" />
PKI1[\�XX=Config/Symfony/Component/Config/Tests/Fixtures/Util/valid.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="http://example.com/schema">
</root>
PKI1[�&�>Config/Symfony/Component/Config/Tests/Fixtures/Util/schema.xsdnu�[���<?xml version="1.0" encoding="UTF-8"?>

<xsd:schema xmlns="http://example.com/schema"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://example.com/schema"
    elementFormDefault="qualified">

  <xsd:element name="root" />
</xsd:schema>
PKI1[�r_���LConfig/Symfony/Component/Config/Tests/Fixtures/Builder/BarNodeDefinition.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\NodeDefinition;

class BarNodeDefinition extends NodeDefinition
{
    protected function createNode()
    {
    }
}
PKI1[��@��QConfig/Symfony/Component/Config/Tests/Fixtures/Builder/VariableNodeDefinition.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVariableNodeDefinition;

class VariableNodeDefinition extends BaseVariableNodeDefinition
{
}
PKI1[�u�;ssFConfig/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Definition\Builder;

use Symfony\Component\Config\Definition\Builder\NodeBuilder as BaseNodeBuilder;

class NodeBuilder extends BaseNodeBuilder
{
    public function barNode($name)
    {
        return $this->node($name, 'bar');
    }

    protected function getNodeClass($type)
    {
        switch ($type) {
            case 'variable':
                return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition';
            case 'bar':
                return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition';
            default:
                return parent::getNodeClass($type);
        }
    }
}
PKI1[�����
�
UConfig/Symfony/Component/Config/Tests/Fixtures/Configuration/ExampleConfiguration.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Fixtures\Configuration;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class ExampleConfiguration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('acme_root');

        $rootNode
            ->fixXmlConfig('parameter')
            ->fixXmlConfig('connection')
            ->children()
                ->booleanNode('boolean')->defaultTrue()->end()
                ->scalarNode('scalar_empty')->end()
                ->scalarNode('scalar_null')->defaultNull()->end()
                ->scalarNode('scalar_true')->defaultTrue()->end()
                ->scalarNode('scalar_false')->defaultFalse()->end()
                ->scalarNode('scalar_default')->defaultValue('default')->end()
                ->scalarNode('scalar_array_empty')->defaultValue(array())->end()
                ->scalarNode('scalar_array_defaults')->defaultValue(array('elem1', 'elem2'))->end()
                ->scalarNode('scalar_required')->isRequired()->end()
                ->enumNode('enum')->values(array('this', 'that'))->end()
                ->arrayNode('array')
                    ->info('some info')
                    ->canBeUnset()
                    ->children()
                        ->scalarNode('child1')->end()
                        ->scalarNode('child2')->end()
                        ->scalarNode('child3')
                            ->info(
                                "this is a long\n".
                                "multi-line info text\n".
                                "which should be indented"
                            )
                            ->example('example setting')
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('parameters')
                    ->useAttributeAsKey('name')
                    ->prototype('scalar')->end()
                ->end()
                ->arrayNode('connections')
                    ->prototype('array')
                        ->children()
                            ->scalarNode('user')->end()
                            ->scalarNode('pass')->end()
                        ->end()
                    ->end()
                ->end()
            ->end()
        ;

        return $treeBuilder;
    }
}
PKI1[<Config/Symfony/Component/Config/Tests/Fixtures/Again/foo.xmlnu�[���PKI1[6Config/Symfony/Component/Config/Tests/Fixtures/foo.xmlnu�[���PKI1[������HConfig/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Resource;

use Symfony\Component\Config\Resource\DirectoryResource;

class DirectoryResourceTest extends \PHPUnit_Framework_TestCase
{
    protected $directory;

    protected function setUp()
    {
        $this->directory = sys_get_temp_dir().'/symfonyDirectoryIterator';
        if (!file_exists($this->directory)) {
            mkdir($this->directory);
        }
        touch($this->directory.'/tmp.xml');
    }

    protected function tearDown()
    {
        if (!is_dir($this->directory)) {
            return;
        }
        $this->removeDirectory($this->directory);
    }

    protected function removeDirectory($directory)
    {
        $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory), \RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($iterator as $path) {
            if (preg_match('#[/\\\\]\.\.?$#', $path->__toString())) {
                continue;
            }
            if ($path->isDir()) {
               rmdir($path->__toString());
            } else {
               unlink($path->__toString());
            }
        }
        rmdir($directory);
    }

    public function testGetResource()
    {
        $resource = new DirectoryResource($this->directory);
        $this->assertSame($this->directory, $resource->getResource(), '->getResource() returns the path to the resource');
        $this->assertSame($this->directory, (string) $resource, '->__toString() returns the path to the resource');
    }

    public function testGetPattern()
    {
        $resource = new DirectoryResource('foo', 'bar');
        $this->assertEquals('bar', $resource->getPattern());
    }

    public function testIsFresh()
    {
        $resource = new DirectoryResource($this->directory);
        $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if the resource has not changed');
        $this->assertFalse($resource->isFresh(time() - 86400), '->isFresh() returns false if the resource has been updated');

        $resource = new DirectoryResource('/____foo/foobar'.rand(1, 999999));
        $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the resource does not exist');
    }

    public function testIsFreshUpdateFile()
    {
        $resource = new DirectoryResource($this->directory);
        touch($this->directory.'/tmp.xml', time() + 20);
        $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if an existing file is modified');
    }

    public function testIsFreshNewFile()
    {
        $resource = new DirectoryResource($this->directory);
        touch($this->directory.'/new.xml', time() + 20);
        $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a new file is added');
    }

    public function testIsFreshDeleteFile()
    {
        $resource = new DirectoryResource($this->directory);
        unlink($this->directory.'/tmp.xml');
        $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if an existing file is removed');
    }

    public function testIsFreshDeleteDirectory()
    {
        $resource = new DirectoryResource($this->directory);
        $this->removeDirectory($this->directory);
        $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the whole resource is removed');
    }

    public function testIsFreshCreateFileInSubdirectory()
    {
        $subdirectory = $this->directory.'/subdirectory';
        mkdir($subdirectory);

        $resource = new DirectoryResource($this->directory);
        $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if an unmodified subdirectory exists');

        touch($subdirectory.'/newfile.xml', time() + 20);
        $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a new file in a subdirectory is added');
    }

    public function testIsFreshModifySubdirectory()
    {
        $resource = new DirectoryResource($this->directory);

        $subdirectory = $this->directory.'/subdirectory';
        mkdir($subdirectory);
        touch($subdirectory, time() + 20);

        $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if a subdirectory is modified (e.g. a file gets deleted)');
    }

    public function testFilterRegexListNoMatch()
    {
        $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/');

        touch($this->directory.'/new.bar', time() + 20);
        $this->assertTrue($resource->isFresh(time() + 10), '->isFresh() returns true if a new file not matching the filter regex is created');
    }

    public function testFilterRegexListMatch()
    {
        $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/');

        touch($this->directory.'/new.xml', time() + 20);
        $this->assertFalse($resource->isFresh(time() + 10), '->isFresh() returns false if an new file matching the filter regex is created ');
    }

    public function testSerializeUnserialize()
    {
        $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/');

        $unserialized = unserialize(serialize($resource));

        $this->assertSame($this->directory, $resource->getResource());
        $this->assertSame('/\.(foo|xml)$/', $resource->getPattern());
    }
}
PKI1[�D-��CConfig/Symfony/Component/Config/Tests/Resource/FileResourceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Resource;

use Symfony\Component\Config\Resource\FileResource;

class FileResourceTest extends \PHPUnit_Framework_TestCase
{
    protected $resource;
    protected $file;

    protected function setUp()
    {
        $this->file = realpath(sys_get_temp_dir()).'/tmp.xml';
        touch($this->file);
        $this->resource = new FileResource($this->file);
    }

    protected function tearDown()
    {
        unlink($this->file);
    }

    public function testGetResource()
    {
        $this->assertSame(realpath($this->file), $this->resource->getResource(), '->getResource() returns the path to the resource');
    }

    public function testToString()
    {
        $this->assertSame(realpath($this->file), (string) $this->resource);
    }

    public function testIsFresh()
    {
        $this->assertTrue($this->resource->isFresh(time() + 10), '->isFresh() returns true if the resource has not changed');
        $this->assertFalse($this->resource->isFresh(time() - 86400), '->isFresh() returns false if the resource has been updated');

        $resource = new FileResource('/____foo/foobar'.rand(1, 999999));
        $this->assertFalse($resource->isFresh(time()), '->isFresh() returns false if the resource does not exist');
    }

    public function testSerializeUnserialize()
    {
        $unserialized = unserialize(serialize($this->resource));

        $this->assertSame(realpath($this->file), $this->resource->getResource());
    }
}
PKI1[��s;Config/Symfony/Component/Config/Tests/Util/XmlUtilsTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Loader;

use Symfony\Component\Config\Util\XmlUtils;

class XmlUtilsTest extends \PHPUnit_Framework_TestCase
{
    public function testLoadFile()
    {
        $fixtures = __DIR__.'/../Fixtures/Util/';

        try {
            XmlUtils::loadFile($fixtures.'invalid.xml');
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertContains('ERROR 77', $e->getMessage());
        }

        try {
            XmlUtils::loadFile($fixtures.'document_type.xml');
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertContains('Document types are not allowed', $e->getMessage());
        }

        try {
            XmlUtils::loadFile($fixtures.'invalid_schema.xml', $fixtures.'schema.xsd');
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertContains('ERROR 1845', $e->getMessage());
        }

        try {
            XmlUtils::loadFile($fixtures.'invalid_schema.xml', 'invalid_callback_or_file');
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertContains('XSD file or callable', $e->getMessage());
        }

        $mock = $this->getMock(__NAMESPACE__.'\Validator');
        $mock->expects($this->exactly(2))->method('validate')->will($this->onConsecutiveCalls(false, true));

        try {
            XmlUtils::loadFile($fixtures.'valid.xml', array($mock, 'validate'));
            $this->fail();
        } catch (\InvalidArgumentException $e) {
            $this->assertContains('is not valid', $e->getMessage());
        }

        $this->assertInstanceOf('DOMDocument', XmlUtils::loadFile($fixtures.'valid.xml', array($mock, 'validate')));
    }

    /**
     * @dataProvider getDataForConvertDomToArray
     */
    public function testConvertDomToArray($expected, $xml, $root = false, $checkPrefix = true)
    {
        $dom = new \DOMDocument();
        $dom->loadXML($root ? $xml : '<root>'.$xml.'</root>');

        $this->assertSame($expected, XmlUtils::convertDomElementToArray($dom->documentElement, $checkPrefix));
    }

    public function getDataForConvertDomToArray()
    {
        return array(
            array(null, ''),
            array('bar', 'bar'),
            array(array('bar' => 'foobar'), '<foo bar="foobar" />', true),
            array(array('foo' => null), '<foo />'),
            array(array('foo' => 'bar'), '<foo>bar</foo>'),
            array(array('foo' => array('foo' => 'bar')), '<foo foo="bar"/>'),
            array(array('foo' => array('foo' => 0)), '<foo><foo>0</foo></foo>'),
            array(array('foo' => array('foo' => 'bar')), '<foo><foo>bar</foo></foo>'),
            array(array('foo' => array('foo' => 'bar', 'value' => 'text')), '<foo foo="bar">text</foo>'),
            array(array('foo' => array('attr' => 'bar', 'foo' => 'text')), '<foo attr="bar"><foo>text</foo></foo>'),
            array(array('foo' => array('bar', 'text')), '<foo>bar</foo><foo>text</foo>'),
            array(array('foo' => array(array('foo' => 'bar'), array('foo' => 'text'))), '<foo foo="bar"/><foo foo="text" />'),
            array(array('foo' => array('foo' => array('bar', 'text'))), '<foo foo="bar"><foo>text</foo></foo>'),
            array(array('foo' => 'bar'), '<foo><!-- Comment -->bar</foo>'),
            array(array('foo' => 'text'), '<foo xmlns:h="http://www.example.org/bar" h:bar="bar">text</foo>'),
            array(array('foo' => array('bar' => 'bar', 'value' => 'text')), '<foo xmlns:h="http://www.example.org/bar" h:bar="bar">text</foo>', false, false),
            array(array('attr' => 1, 'b' => 'hello'), '<foo:a xmlns:foo="http://www.example.org/foo" xmlns:h="http://www.example.org/bar" attr="1" h:bar="bar"><foo:b>hello</foo:b><h:c>2</h:c></foo:a>', true),
        );
    }

    /**
     * @dataProvider getDataForPhpize
     */
    public function testPhpize($expected, $value)
    {
        $this->assertSame($expected, XmlUtils::phpize($value));
    }

    public function getDataForPhpize()
    {
        return array(
            array('', ''),
            array(null, 'null'),
            array(true, 'true'),
            array(false, 'false'),
            array(null, 'Null'),
            array(true, 'True'),
            array(false, 'False'),
            array(0, '0'),
            array(1, '1'),
            array(-1, '-1'),
            array(0777, '0777'),
            array(255, '0xFF'),
            array(100.0, '1e2'),
            array(-120.0, '-1.2E2'),
            array(-10100.1, '-10100.1'),
            array('-10,100.1', '-10,100.1'),
            array('1234 5678 9101 1121 3141', '1234 5678 9101 1121 3141'),
            array('1,2,3,4', '1,2,3,4'),
            array('11,22,33,44', '11,22,33,44'),
            array('11,222,333,4', '11,222,333,4'),
            array('1,222,333,444', '1,222,333,444'),
            array('11,222,333,444', '11,222,333,444'),
            array('111,222,333,444', '111,222,333,444'),
            array('1111,2222,3333,4444,5555', '1111,2222,3333,4444,5555'),
            array('foo', 'foo'),
            array(6, '0b0110'),
        );
    }

    public function testLoadEmptyXmlFile()
    {
        $file = __DIR__.'/../Fixtures/foo.xml';
        $this->setExpectedException('InvalidArgumentException', 'File '.$file.' does not contain valid XML, it is empty.');
        XmlUtils::loadFile($file);
    }

    // test for issue https://github.com/symfony/symfony/issues/9731
    public function testLoadWrongEmptyXMLWithErrorHandler()
    {
        $originalDisableEntities = libxml_disable_entity_loader(false);
        $errorReporting = error_reporting(-1);

        set_error_handler(function ($errno, $errstr) {
            throw new \Exception($errstr, $errno);
        });

        $file = __DIR__.'/../Fixtures/foo.xml';
        try {
            XmlUtils::loadFile($file);
            $this->fail('An exception should have been raised');
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals(sprintf('File %s does not contain valid XML, it is empty.', $file), $e->getMessage());
        }

        restore_error_handler();
        error_reporting($errorReporting);

        $disableEntities = libxml_disable_entity_loader(true);
        libxml_disable_entity_loader($disableEntities);

        libxml_disable_entity_loader($originalDisableEntities);

        $this->assertFalse($disableEntities);

        // should not throw an exception
        XmlUtils::loadFile(__DIR__.'/../Fixtures/Util/valid.xml', __DIR__.'/../Fixtures/Util/schema.xsd');
    }
}

interface Validator
{
    public function validate();
}
PKI1[ Z��^^9Config/Symfony/Component/Config/Tests/ConfigCacheTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests;

use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource;

class ConfigCacheTest extends \PHPUnit_Framework_TestCase
{
    private $resourceFile = null;

    private $cacheFile = null;

    private $metaFile = null;

    public function setUp()
    {
        $this->resourceFile = tempnam(sys_get_temp_dir(), '_resource');
        $this->cacheFile = tempnam(sys_get_temp_dir(), 'config_');
        $this->metaFile = $this->cacheFile.'.meta';

        $this->makeCacheFresh();
        $this->generateMetaFile();
    }

    public function tearDown()
    {
        $files = array($this->cacheFile, $this->metaFile, $this->resourceFile);

        foreach ($files as $file) {
            if (file_exists($file)) {
                unlink($file);
            }
        }
    }

    public function testToString()
    {
        $cache = new ConfigCache($this->cacheFile, true);

        $this->assertSame($this->cacheFile, (string) $cache);
    }

    public function testCacheIsNotFreshIfFileDoesNotExist()
    {
        unlink($this->cacheFile);

        $cache = new ConfigCache($this->cacheFile, false);

        $this->assertFalse($cache->isFresh());
    }

    public function testCacheIsAlwaysFreshIfFileExistsWithDebugDisabled()
    {
        $this->makeCacheStale();

        $cache = new ConfigCache($this->cacheFile, false);

        $this->assertTrue($cache->isFresh());
    }

    public function testCacheIsNotFreshWithoutMetaFile()
    {
        unlink($this->metaFile);

        $cache = new ConfigCache($this->cacheFile, true);

        $this->assertFalse($cache->isFresh());
    }

    public function testCacheIsFreshIfResourceIsFresh()
    {
        $cache = new ConfigCache($this->cacheFile, true);

        $this->assertTrue($cache->isFresh());
    }

    public function testCacheIsNotFreshIfOneOfTheResourcesIsNotFresh()
    {
        $this->makeCacheStale();

        $cache = new ConfigCache($this->cacheFile, true);

        $this->assertFalse($cache->isFresh());
    }

    public function testWriteDumpsFile()
    {
        unlink($this->cacheFile);
        unlink($this->metaFile);

        $cache = new ConfigCache($this->cacheFile, false);
        $cache->write('FOOBAR');

        $this->assertFileExists($this->cacheFile, 'Cache file is created');
        $this->assertSame('FOOBAR', file_get_contents($this->cacheFile));
        $this->assertFileNotExists($this->metaFile, 'Meta file is not created');
    }

    public function testWriteDumpsMetaFileWithDebugEnabled()
    {
        unlink($this->cacheFile);
        unlink($this->metaFile);

        $metadata = array(new FileResource($this->resourceFile));

        $cache = new ConfigCache($this->cacheFile, true);
        $cache->write('FOOBAR', $metadata);

        $this->assertFileExists($this->cacheFile, 'Cache file is created');
        $this->assertFileExists($this->metaFile, 'Meta file is created');
        $this->assertSame(serialize($metadata), file_get_contents($this->metaFile));
    }

    private function makeCacheFresh()
    {
        touch($this->resourceFile, filemtime($this->cacheFile) - 3600);
    }

    private function makeCacheStale()
    {
        touch($this->cacheFile, time() - 3600);
    }

    private function generateMetaFile()
    {
        file_put_contents($this->metaFile, serialize(array(new FileResource($this->resourceFile))));
    }
}
PKI1[K�OCC9Config/Symfony/Component/Config/Tests/FileLocatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests;

use Symfony\Component\Config\FileLocator;

class FileLocatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getIsAbsolutePathTests
     */
    public function testIsAbsolutePath($path)
    {
        $loader = new FileLocator(array());
        $r = new \ReflectionObject($loader);
        $m = $r->getMethod('isAbsolutePath');
        $m->setAccessible(true);

        $this->assertTrue($m->invoke($loader, $path), '->isAbsolutePath() returns true for an absolute path');
    }

    public function getIsAbsolutePathTests()
    {
        return array(
            array('/foo.xml'),
            array('c:\\\\foo.xml'),
            array('c:/foo.xml'),
            array('\\server\\foo.xml'),
            array('https://server/foo.xml'),
            array('phar://server/foo.xml'),
        );
    }

    public function testLocate()
    {
        $loader = new FileLocator(__DIR__.'/Fixtures');

        $this->assertEquals(
            __DIR__.DIRECTORY_SEPARATOR.'FileLocatorTest.php',
            $loader->locate('FileLocatorTest.php', __DIR__),
            '->locate() returns the absolute filename if the file exists in the given path'
        );

        $this->assertEquals(
            __DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml',
            $loader->locate('foo.xml', __DIR__),
            '->locate() returns the absolute filename if the file exists in one of the paths given in the constructor'
        );

        $this->assertEquals(
            __DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml',
            $loader->locate(__DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml', __DIR__),
            '->locate() returns the absolute filename if the file exists in one of the paths given in the constructor'
        );

        $loader = new FileLocator(array(__DIR__.'/Fixtures', __DIR__.'/Fixtures/Again'));

        $this->assertEquals(
            array(__DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.DIRECTORY_SEPARATOR.'foo.xml'),
            $loader->locate('foo.xml', __DIR__, false),
            '->locate() returns an array of absolute filenames'
        );

        $this->assertEquals(
            array(__DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.DIRECTORY_SEPARATOR.'foo.xml'),
            $loader->locate('foo.xml', __DIR__.'/Fixtures', false),
            '->locate() returns an array of absolute filenames'
        );

        $loader = new FileLocator(__DIR__.'/Fixtures/Again');

        $this->assertEquals(
            array(__DIR__.'/Fixtures'.DIRECTORY_SEPARATOR.'foo.xml', __DIR__.'/Fixtures/Again'.DIRECTORY_SEPARATOR.'foo.xml'),
            $loader->locate('foo.xml', __DIR__.'/Fixtures', false),
            '->locate() returns an array of absolute filenames'
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLocateThrowsAnExceptionIfTheFileDoesNotExists()
    {
        $loader = new FileLocator(array(__DIR__.'/Fixtures'));

        $loader->locate('foobar.xml', __DIR__);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath()
    {
        $loader = new FileLocator(array(__DIR__.'/Fixtures'));

        $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__);
    }
}
PKI1[L��{?Config/Symfony/Component/Config/Tests/Loader/FileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Loader;

use Symfony\Component\Config\Loader\FileLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException;

class FileLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\Config\Loader\FileLoader
     */
    public function testImportWithFileLocatorDelegation()
    {
        $locatorMock = $this->getMock('Symfony\Component\Config\FileLocatorInterface');

        $locatorMockForAdditionalLoader = $this->getMock('Symfony\Component\Config\FileLocatorInterface');
        $locatorMockForAdditionalLoader->expects($this->any())->method('locate')->will($this->onConsecutiveCalls(
                array('path/to/file1'),                    // Default
                array('path/to/file1', 'path/to/file2'),   // First is imported
                array('path/to/file1', 'path/to/file2'),   // Second is imported
                array('path/to/file1'),                    // Exception
                array('path/to/file1', 'path/to/file2')    // Exception
                ));

        $fileLoader = new TestFileLoader($locatorMock);
        $fileLoader->setSupports(false);
        $fileLoader->setCurrentDir('.');

        $additionalLoader = new TestFileLoader($locatorMockForAdditionalLoader);
        $additionalLoader->setCurrentDir('.');

        $fileLoader->setResolver($loaderResolver = new LoaderResolver(array($fileLoader, $additionalLoader)));

        // Default case
        $this->assertSame('path/to/file1', $fileLoader->import('my_resource'));

        // Check first file is imported if not already loading
        $this->assertSame('path/to/file1', $fileLoader->import('my_resource'));

        // Check second file is imported if first is already loading
        $fileLoader->addLoading('path/to/file1');
        $this->assertSame('path/to/file2', $fileLoader->import('my_resource'));

        // Check exception throws if first (and only available) file is already loading
        try {
            $fileLoader->import('my_resource');
            $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException', $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading');
        }

        // Check exception throws if all files are already loading
        try {
            $fileLoader->addLoading('path/to/file2');
            $fileLoader->import('my_resource');
            $this->fail('->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\Config\Exception\FileLoaderImportCircularReferenceException', $e, '->import() throws a FileLoaderImportCircularReferenceException if the resource is already loading');
        }
    }
}

class TestFileLoader extends FileLoader
{
    private $supports = true;

    public function load($resource, $type = null)
    {
        return $resource;
    }

    public function supports($resource, $type = null)
    {
        return $this->supports;
    }

    public function addLoading($resource)
    {
        self::$loading[$resource] = true;
    }

    public function removeLoading($resource)
    {
        unset(self::$loading[$resource]);
    }

    public function clearLoading()
    {
        self::$loading = array();
    }

    public function setSupports($supports)
    {
        $this->supports = $supports;
    }
}
PKI1[5bc�@@;Config/Symfony/Component/Config/Tests/Loader/LoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Loader;

use Symfony\Component\Config\Loader\Loader;

class LoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetSetResolver()
    {
        $resolver = $this->getMock('Symfony\Component\Config\Loader\LoaderResolverInterface');

        $loader = new ProjectLoader1();
        $loader->setResolver($resolver);

        $this->assertSame($resolver, $loader->getResolver(), '->setResolver() sets the resolver loader');
    }

    public function testResolve()
    {
        $resolvedLoader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');

        $resolver = $this->getMock('Symfony\Component\Config\Loader\LoaderResolverInterface');
        $resolver->expects($this->once())
            ->method('resolve')
            ->with('foo.xml')
            ->will($this->returnValue($resolvedLoader));

        $loader = new ProjectLoader1();
        $loader->setResolver($resolver);

        $this->assertSame($loader, $loader->resolve('foo.foo'), '->resolve() finds a loader');
        $this->assertSame($resolvedLoader, $loader->resolve('foo.xml'), '->resolve() finds a loader');
    }

    /**
     * @expectedException \Symfony\Component\Config\Exception\FileLoaderLoadException
     */
    public function testResolveWhenResolverCannotFindLoader()
    {
        $resolver = $this->getMock('Symfony\Component\Config\Loader\LoaderResolverInterface');
        $resolver->expects($this->once())
            ->method('resolve')
            ->with('FOOBAR')
            ->will($this->returnValue(false));

        $loader = new ProjectLoader1();
        $loader->setResolver($resolver);

        $loader->resolve('FOOBAR');
    }

    public function testImport()
    {
        $resolvedLoader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $resolvedLoader->expects($this->once())
            ->method('load')
            ->with('foo')
            ->will($this->returnValue('yes'));

        $resolver = $this->getMock('Symfony\Component\Config\Loader\LoaderResolverInterface');
        $resolver->expects($this->once())
            ->method('resolve')
            ->with('foo')
            ->will($this->returnValue($resolvedLoader));

        $loader = new ProjectLoader1();
        $loader->setResolver($resolver);

        $this->assertEquals('yes', $loader->import('foo'));
    }

    public function testImportWithType()
    {
        $resolvedLoader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $resolvedLoader->expects($this->once())
            ->method('load')
            ->with('foo', 'bar')
            ->will($this->returnValue('yes'));

        $resolver = $this->getMock('Symfony\Component\Config\Loader\LoaderResolverInterface');
        $resolver->expects($this->once())
            ->method('resolve')
            ->with('foo', 'bar')
            ->will($this->returnValue($resolvedLoader));

        $loader = new ProjectLoader1();
        $loader->setResolver($resolver);

        $this->assertEquals('yes', $loader->import('foo', 'bar'));
    }
}

class ProjectLoader1 extends Loader
{
    public function load($resource, $type = null)
    {
    }

    public function supports($resource, $type = null)
    {
        return is_string($resource) && 'foo' === pathinfo($resource, PATHINFO_EXTENSION);
    }

    public function getType()
    {
    }
}
PKI1[oq*,��EConfig/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Loader;

use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\Loader\DelegatingLoader;

class DelegatingLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\Config\Loader\DelegatingLoader::__construct
     */
    public function testConstructor()
    {
        $loader = new DelegatingLoader($resolver = new LoaderResolver());
        $this->assertTrue(true, '__construct() takes a loader resolver as its first argument');
    }

    /**
     * @covers Symfony\Component\Config\Loader\DelegatingLoader::getResolver
     * @covers Symfony\Component\Config\Loader\DelegatingLoader::setResolver
     */
    public function testGetSetResolver()
    {
        $resolver = new LoaderResolver();
        $loader = new DelegatingLoader($resolver);
        $this->assertSame($resolver, $loader->getResolver(), '->getResolver() gets the resolver loader');
        $loader->setResolver($resolver = new LoaderResolver());
        $this->assertSame($resolver, $loader->getResolver(), '->setResolver() sets the resolver loader');
    }

    /**
     * @covers Symfony\Component\Config\Loader\DelegatingLoader::supports
     */
    public function testSupports()
    {
        $loader1 = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $loader1->expects($this->once())->method('supports')->will($this->returnValue(true));
        $loader = new DelegatingLoader(new LoaderResolver(array($loader1)));
        $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');

        $loader1 = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $loader1->expects($this->once())->method('supports')->will($this->returnValue(false));
        $loader = new DelegatingLoader(new LoaderResolver(array($loader1)));
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns false if the resource is not loadable');
    }

    /**
     * @covers Symfony\Component\Config\Loader\DelegatingLoader::load
     */
    public function testLoad()
    {
        $loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $loader->expects($this->once())->method('supports')->will($this->returnValue(true));
        $loader->expects($this->once())->method('load');
        $resolver = new LoaderResolver(array($loader));
        $loader = new DelegatingLoader($resolver);

        $loader->load('foo');
    }

    /**
     * @expectedException \Symfony\Component\Config\Exception\FileLoaderLoadException
     */
    public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded()
    {
        $loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $loader->expects($this->once())->method('supports')->will($this->returnValue(false));
        $resolver = new LoaderResolver(array($loader));
        $loader = new DelegatingLoader($resolver);

        $loader->load('foo');
    }
}
PKI1[�YCConfig/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Config\Tests\Loader;

use Symfony\Component\Config\Loader\LoaderResolver;

class LoaderResolverTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\Config\Loader\LoaderResolver::__construct
     */
    public function testConstructor()
    {
        $resolver = new LoaderResolver(array(
            $loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface'),
        ));

        $this->assertEquals(array($loader), $resolver->getLoaders(), '__construct() takes an array of loaders as its first argument');
    }

    /**
     * @covers Symfony\Component\Config\Loader\LoaderResolver::resolve
     */
    public function testResolve()
    {
        $loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $resolver = new LoaderResolver(array($loader));
        $this->assertFalse($resolver->resolve('foo.foo'), '->resolve() returns false if no loader is able to load the resource');

        $loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface');
        $loader->expects($this->once())->method('supports')->will($this->returnValue(true));
        $resolver = new LoaderResolver(array($loader));
        $this->assertEquals($loader, $resolver->resolve(function () {}), '->resolve() returns the loader for the given resource');
    }

    /**
     * @covers Symfony\Component\Config\Loader\LoaderResolver::getLoaders
     * @covers Symfony\Component\Config\Loader\LoaderResolver::addLoader
     */
    public function testLoaders()
    {
        $resolver = new LoaderResolver();
        $resolver->addLoader($loader = $this->getMock('Symfony\Component\Config\Loader\LoaderInterface'));

        $this->assertEquals(array($loader), $resolver->getLoaders(), 'addLoader() adds a loader');
    }
}
PKI1[�Y�hh0Config/Symfony/Component/Config/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony Config Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKI1[����Net_Sieve/tests/largescript.sivnu�[���require ["fileinto", "reject", "vacation", "regex", "relational", "comparator-i;ascii-numeric"];
if header :is ["X-Spam-Flag", "X-Spam-Status"] ["YES","Yes"] {
fileinto "INBOX.Spam";
stop;
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["cvs-all.freebsd.org"] {
fileinto "INBOX.FreeBSD.CVS All";
}
if header :contains ["List-Id"] ["freebsd-acpi.freebsd.org"] {
fileinto "INBOX.FreeBSD.ACPI";
}
if header :contains ["List-Id"] ["freebsd-current.freebsd.org"] {
fileinto "INBOX.FreeBSD.Current";
}
if header :contains ["List-Id"] ["freebsd-hackers.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hackers";
}
if header :contains ["List-Id"] ["freebsd-multimedia.freebsd.org"] {
fileinto "INBOX.FreeBSD.Multimedia";
}
if header :contains ["List-Id"] ["freebsd-questions.freebsd.org"] {
fileinto "INBOX.FreeBSD.Questions";
}
if header :contains ["List-Id"] ["freebsd-stable.freebsd.org"] {
fileinto "INBOX.FreeBSD.Stable";
}
if header :contains ["List-Id"] ["freebsd-mobile.freebsd.org"] {
fileinto "INBOX.FreeBSD.Mobile";
}
if header :contains ["List-Id"] ["wine-devel.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Devel";
}
if header :contains ["List-Id"] ["wine-users.winehq.org"] {
fileinto "INBOX.FreeBSD.Wine.Users";
}
if header :contains ["List-Id"] ["dri-devel.lists.sourceforge.net"] {
fileinto "INBOX.FreeBSD.dri-devel";
}
if header :contains ["List-Id"] ["freebsd-threads.freebsd.org"] {
fileinto "INBOX.FreeBSD.Threads";
}
if header :contains ["List-Id"] ["freebsd-hardware.freebsd.org"] {
fileinto "INBOX.FreeBSD.Hardware";
}
if header :contains ["List-Id"] ["freebsd-usb.freebsd.org"] {
fileinto "INBOX.FreeBSD.USB";
}
if header :contains ["List-Id"] ["freebsd-ports.freebsd.org"] {
fileinto "INBOX.FreeBSD.Ports";
}
if header :contains ["To"] ["amistry@php.net"] {
fileinto "INBOX.PEAR.Account";
}
if header :contains ["list-post"] ["pear-qa@lists.php.net"] {
fileinto "INBOX.PEAR.QA";
}
if header :contains ["Delivered-To"] ["php-general@lists.php.net"] {
fileinto "INBOX.PHP.General";
}
if header :contains ["Delivered-to"] ["internals@lists.php.net"] {
fileinto "INBOX.PEAR.Internals";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
if header :contains ["List-Id"] ["suphp.lists.marsching.biz"] {
fileinto "INBOX.suPHP";
}
PKI1[�g��-�-Net_Sieve/tests/SieveTest.phpnu�[���<?php
/**
 * This file contains the PHPUnit test case for Net_Sieve.
 *
 * PHP version 5
 *
 * +-----------------------------------------------------------------------+
 * | All rights reserved.                                                  |
 * |                                                                       |
 * | Redistribution and use in source and binary forms, with or without    |
 * | modification, are permitted provided that the following conditions    |
 * | are met:                                                              |
 * |                                                                       |
 * | o Redistributions of source code must retain the above copyright      |
 * |   notice, this list of conditions and the following disclaimer.       |
 * | o Redistributions in binary form must reproduce the above copyright   |
 * |   notice, this list of conditions and the following disclaimer in the |
 * |   documentation and/or other materials provided with the distribution.|
 * |                                                                       |
 * | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
 * | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
 * | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
 * | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
 * | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
 * | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
 * | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
 * | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
 * +-----------------------------------------------------------------------+
 *
 * @category  Networking
 * @package   Net_Sieve
 * @author    Anish Mistry <amistry@am-productions.biz>
 * @copyright 2006 Anish Mistry
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD
 * @version   SVN: $Id$
 * @link      http://pear.php.net/package/Net_Sieve
 */

require_once dirname(__FILE__) . '/../Sieve.php';

/**
 * PHPUnit test case for Net_Sieve.
 *
 * @category  Networking
 * @package   Net_Sieve
 * @author    Anish Mistry <amistry@am-productions.biz>
 * @copyright 2006 Anish Mistry
 * @license   http://www.opensource.org/licenses/bsd-license.php BSD
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/Net_Sieve
 */
class SieveTest extends PHPUnit\Framework\TestCase
{
    // contains the object handle of the string class
    protected $fixture;

    protected function setUp()
    {
        if (!file_exists(dirname(__FILE__) . '/config.php')) {
            $this->markTestSkipped('Test configuration incomplete. Copy config.php.dist to config.php.');
        }
        require_once dirname(__FILE__) . '/config.php';

        // Create a new instance of Net_Sieve.
        $this->_pear = new PEAR();
        $this->fixture = new Net_Sieve();
        $this->scripts = array(
            'test script1' => "require \"fileinto\";\r\nif header :contains \"From\" \"@cnba.uba.ar\" \r\n{fileinto \"INBOX.Test1\";}\r\nelse \r\n{fileinto \"INBOX\";}",
            'test script2' => "require \"fileinto\";\r\nif header :contains \"From\" \"@cnba.uba.ar\" \r\n{fileinto \"INBOX.Test\";}\r\nelse \r\n{fileinto \"INBOX\";}",
            'test"scriptäöü3' => "require \"vacation\";\nvacation\n:days 7\n:addresses [\"matthew@de-construct.com\"]\n:subject \"This is a test\"\n\"I'm on my holiday!\nsadfafs\";",
            'test script4' => file_get_contents(dirname(__FILE__) . '/largescript.siv'));
    }
    
    protected function tearDown()
    {
        // Delete the instance.
        unset($this->fixture);
    }
    
    protected function login()
    {
        $result = $this->fixture->connect(HOST, PORT);
        $this->assertTrue($this->check($result), 'Can not connect');
        $result = $this->fixture->login(USERNAME, PASSWORD, null, '', false);
        $this->assertTrue($this->check($result), 'Can not login');
    }

    protected function logout()
    {
        $result = $this->fixture->disconnect();
        $this->assertFalse($this->_pear->isError($result), 'Error on disconnect');
    }

    protected function clear()
    {
        // Clear all the scripts in the account.
        $this->login();
        $active = $this->fixture->getActive();
        if (isset($this->scripts[$active])) {
            $this->fixture->setActive(null);
        }
        foreach (array_keys($this->scripts) as $script) {
            $this->fixture->removeScript($script);
        }
        $this->logout();
    }

    protected function check($result)
    {
        if ($this->_pear->isError($result)) {
            throw new Exception($result->getMessage());
        }
        return $result;
    }

    public function testConnect()
    {
        $result = $this->fixture->connect(HOST, PORT);
        $this->assertTrue($this->check($result), 'Cannot connect');
    }
    
    public function testLogin()
    {
        $result = $this->fixture->connect(HOST, PORT);
        $this->assertTrue($this->check($result), 'Cannot connect');
        $result = $this->fixture->login(USERNAME, PASSWORD, null, '', false);
        $this->assertTrue($this->check($result), 'Cannot login');
    }

    public function testDisconnect()
    {
        $result = $this->fixture->connect(HOST, PORT);
        $this->assertFalse($this->_pear->isError($result), 'Cannot connect');
        $result = $this->fixture->login(USERNAME, PASSWORD, null, '', false);
        $this->assertFalse($this->_pear->isError($result), 'Cannot login');
        $result = $this->fixture->disconnect();
        $this->assertFalse($this->_pear->isError($result), 'Error on disconnect');
    }

    public function testListScripts()
    {
        $this->login();
        $scripts = $this->fixture->listScripts();
        $this->logout();
        $this->assertFalse($this->_pear->isError($scripts), 'Can not list scripts');
    }

    public function testInstallScript()
    {
        $this->clear();
        $this->login();

        // First script.
        $scriptname = 'test script1';
        $before_scripts = $this->fixture->listScripts();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $this->assertFalse($this->_pear->isError($result), 'Can not install script ' . $scriptname);
        $after_scripts = $this->fixture->listScripts();
        $diff_scripts = array_values(array_diff($after_scripts, $before_scripts));
        $this->assertTrue(count($diff_scripts) > 0, 'Script not installed');
        $this->assertEquals($scriptname, $diff_scripts[0], 'Added script has a different name');

        // Second script (install and activate)
        $scriptname = 'test script2';
        $before_scripts = $this->fixture->listScripts();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname], true);
        $this->assertFalse($this->_pear->isError($result), 'Can not install script ' . $scriptname);
        $after_scripts = $this->fixture->listScripts();
        $diff_scripts = array_values(array_diff($after_scripts, $before_scripts));
        $this->assertTrue(count($diff_scripts) > 0, 'Script not installed');
        $this->assertEquals($scriptname, $diff_scripts[0], 'Added script has a different name');
        $active_script = $this->fixture->getActive();
        $this->assertEquals($scriptname, $active_script, 'Added script has a different name');
        $this->logout();
    }

    /**
     * There is a good chance that this test will fail since most servers have
     * a 32KB limit on uploaded scripts.
     */
    public function testInstallScriptLarge()
    {
        $this->clear();
        $this->login();
        $scriptname = 'test script4';
        $before_scripts = $this->fixture->listScripts();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $this->assertFalse($this->_pear->isError($result), 'Unable to upload large script (expected behavior for most servers)');
        $after_scripts = $this->fixture->listScripts();
        $diff_scripts = array_diff($after_scripts, $before_scripts);
        $this->assertEquals($scriptname, reset($diff_scripts), 'Added script has a different name');
        $this->logout();
    }

    /**
     * See bug #16691.
     */
    public function testInstallNonAsciiScript()
    {
        $this->clear();
        $this->login();

        $scriptname = 'test"scriptäöü3';
        $before_scripts = $this->fixture->listScripts();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $this->assertFalse($this->_pear->isError($result), 'Can not install script ' . $scriptname);
        $after_scripts = $this->fixture->listScripts();
        $diff_scripts = array_values(array_diff($after_scripts, $before_scripts));
        $this->assertTrue(count($diff_scripts) > 0, 'Script not installed');
        $this->assertEquals($scriptname, $diff_scripts[0], 'Added script has a different name');

        $this->logout();
    }

    public function testGetScript()
    {
        $this->clear();
        $this->login();
        $scriptname = 'test script1';
        $before_scripts = $this->fixture->listScripts();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $this->assertFalse($this->_pear->isError($result), 'Can not install script ' . $scriptname);
        $after_scripts = $this->fixture->listScripts();
        $diff_scripts = array_values(array_diff($after_scripts, $before_scripts));
        $this->assertTrue(count($diff_scripts) > 0);
        $this->assertEquals($scriptname, $diff_scripts[0], 'Added script has a different name');
        $script = $this->fixture->getScript($scriptname);
        $this->assertEquals(trim($this->scripts[$scriptname]), trim($script), 'Script installed is not the same script retrieved');
        $this->logout();
    }

    public function testGetActive()
    {
        $this->clear();
        $this->login();
        $active_script = $this->fixture->getActive();
        $this->assertFalse($this->_pear->isError($active_script), 'Error getting the active script');
        $this->logout();
    }

    public function testSetActive()
    {
        $this->clear();
        $scriptname = 'test script1';
        $this->login();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $result = $this->fixture->setActive($scriptname);
        $this->assertFalse($this->_pear->isError($result), 'Can not set active script');
        $active_script = $this->fixture->getActive();
        $this->assertEquals($scriptname, $active_script, 'Active script does not match');

        // Test for non-existant script.
        $result = $this->fixture->setActive('non existant script');
        $this->assertTrue($this->_pear->isError($result));
        $this->logout();
    }

    public function testRemoveScript()
    {
        $this->clear();
        $scriptname = 'test script1';
        $this->login();
        $result = $this->fixture->installScript($scriptname, $this->scripts[$scriptname]);
        $result = $this->fixture->removeScript($scriptname);
        $this->assertFalse($this->_pear->isError($result), 'Error removing active script');
        $this->logout();
    }
}
PKI1[�Y�nppNet_Sieve/tests/config.php.distnu�[���<?php
define('HOST', 'localhost');
define('PORT', 4190);
define('USERNAME', 'user');
define('PASSWORD', 'pass');PKI1[ҵ3��9Mail_mimeDecode/tests/semicolon_content_type_bug1724.phptnu�[���--TEST--
Bug #1724   Quoted Semicolons in Content-Type
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$Mime = new Mail_Mime();
$Mime->setTXTBody('Test message.');
$Mime->addAttachment('test file contents', 'text/plain; testparam="test1;semicolon"', 'test.txt', FALSE);

$body = $Mime->get();

$hdrs = '';
foreach ($Mime->headers() AS $name => $val) {
    $hdrs .= "$name: $val\n";
}
$hdrs .= "To: Receiver <receiver@example.com>\n";
$hdrs .= "From: Sender <sender@example.com>\n";
$hdrs .= "Subject: PEAR::Mail_Mime test mail\n";

require_once('Mail/mimeDecode.php');

$mime_message = "$hdrs\n$body";
$Decoder = new Mail_mimeDecode($mime_message);
$params = array(
    'include_bodies' => TRUE,
    'decode_bodies'  => TRUE,
    'decode_headers' => TRUE
);
$Decoded = $Decoder->decode($params);
$test_param = $Decoded->parts[1]->ctype_parameters['testparam'];

echo $test_param;

?>
--EXPECT--
test1;semicolon
PKJ1[s��%��-Mail_mimeDecode/tests/parse_header_value.phptnu�[���--TEST--
Tests for _parseHeaderValue
--SKIPIF--
--FILE--
<?php
require_once 'Mail/mime.php';

$Mime = new Mail_Mime();
$Mime->setTXTBody('Test message.');
$contentAppend = 'testparam1="test1;semicolon";testparam2=two; testparam3="three"; '
                .'testparam4="four\;4\;four"; testparam5=five\;5\;five; '
                ."testparam6='six'; testparam7='seven;7';testparam8='eight\;8'; "
                .'testparam9="nine;9";testparam10="ten\;10"; '
                .'testparam11=\'a "double" quote\'; testparam12="a \'simple\' quote"; '
                .'testparam13=\'another " quote\'; testparam14="another \' quote";'
                .'testparam15=last';

$Mime->addAttachment('test file contents', "text/plain; $contentAppend", 'test.txt', FALSE);

$body = $Mime->get();

$hdrs = '';
foreach ($Mime->headers() AS $name => $val) {
    $hdrs .= "$name: $val\n";
}
$hdrs .= "To: Receiver <receiver@example.com>\n";
$hdrs .= "From: Sender <sender@example.com>\n";
$hdrs .= "Subject: PEAR::Mail_Mime test mail\n";

require_once 'Mail/mimeDecode.php';

$mime_message = "$hdrs\n$body";
$Decoder = new Mail_mimeDecode($mime_message);
$params = array(
    'include_bodies' => TRUE,
    'decode_bodies'  => TRUE,
    'decode_headers' => TRUE
);
$Decoded = $Decoder->decode($params);
$decodedParts = $Decoded->parts[1]->ctype_parameters;
//Bug #4057: Content-type params now have a name attribute.
unset($decodedParts['name']);
print_r($decodedParts);
?>
--EXPECT--
Array
(
    [testparam1] => test1;semicolon
    [testparam2] => two
    [testparam3] => three
    [testparam4] => four;4;four
    [testparam5] => five;5;five
    [testparam6] => six
    [testparam7] => seven;7
    [testparam8] => eight;8
    [testparam9] => nine;9
    [testparam10] => ten;10
    [testparam11] => a "double" quote
    [testparam12] => a 'simple' quote
    [testparam13] => another " quote
    [testparam14] => another ' quote
    [testparam15] => last
)
PKJ1[�?7|�f�f<HttpKernel/Symfony/Component/HttpKernel/Tests/KernelTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest;
use Symfony\Component\HttpKernel\Tests\Fixtures\KernelForOverrideName;
use Symfony\Component\HttpKernel\Tests\Fixtures\FooBarBundle;

class KernelTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $env = 'test_env';
        $debug = true;
        $kernel = new KernelForTest($env, $debug);

        $this->assertEquals($env, $kernel->getEnvironment());
        $this->assertEquals($debug, $kernel->isDebug());
        $this->assertFalse($kernel->isBooted());
        $this->assertLessThanOrEqual(microtime(true), $kernel->getStartTime());
        $this->assertNull($kernel->getContainer());
    }

    public function testClone()
    {
        $env = 'test_env';
        $debug = true;
        $kernel = new KernelForTest($env, $debug);

        $clone = clone $kernel;

        $this->assertEquals($env, $clone->getEnvironment());
        $this->assertEquals($debug, $clone->isDebug());
        $this->assertFalse($clone->isBooted());
        $this->assertLessThanOrEqual(microtime(true), $clone->getStartTime());
        $this->assertNull($clone->getContainer());
    }

    public function testBootInitializesBundlesAndContainer()
    {
        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
        $kernel->expects($this->once())
            ->method('initializeBundles');
        $kernel->expects($this->once())
            ->method('initializeContainer');

        $kernel->boot();
    }

    public function testBootSetsTheContainerToTheBundles()
    {
        $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
        $bundle->expects($this->once())
            ->method('setContainer');

        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'getBundles'));
        $kernel->expects($this->once())
            ->method('getBundles')
            ->will($this->returnValue(array($bundle)));

        $kernel->boot();
    }

    public function testBootSetsTheBootedFlagToTrue()
    {
        // use test kernel to access isBooted()
        $kernel = $this->getKernelForTest(array('initializeBundles', 'initializeContainer'));
        $kernel->boot();

        $this->assertTrue($kernel->isBooted());
    }

    public function testClassCacheIsLoaded()
    {
        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
        $kernel->loadClassCache('name', '.extension');
        $kernel->expects($this->once())
            ->method('doLoadClassCache')
            ->with('name', '.extension');

        $kernel->boot();
    }

    public function testClassCacheIsNotLoadedByDefault()
    {
        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
        $kernel->expects($this->never())
            ->method('doLoadClassCache');

        $kernel->boot();
    }

    public function testClassCacheIsNotLoadedWhenKernelIsNotBooted()
    {
        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer', 'doLoadClassCache'));
        $kernel->loadClassCache();
        $kernel->expects($this->never())
            ->method('doLoadClassCache');
    }

    public function testBootKernelSeveralTimesOnlyInitializesBundlesOnce()
    {
        $kernel = $this->getKernel(array('initializeBundles', 'initializeContainer'));
        $kernel->expects($this->once())
            ->method('initializeBundles');

        $kernel->boot();
        $kernel->boot();
    }

    public function testShutdownCallsShutdownOnAllBundles()
    {
        $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
        $bundle->expects($this->once())
            ->method('shutdown');

        $kernel = $this->getKernel(array(), array($bundle));

        $kernel->boot();
        $kernel->shutdown();
    }

    public function testShutdownGivesNullContainerToAllBundles()
    {
        $bundle = $this->getMock('Symfony\Component\HttpKernel\Bundle\Bundle');
        $bundle->expects($this->at(3))
            ->method('setContainer')
            ->with(null);

        $kernel = $this->getKernel(array('getBundles'));
        $kernel->expects($this->any())
            ->method('getBundles')
            ->will($this->returnValue(array($bundle)));

        $kernel->boot();
        $kernel->shutdown();
    }

    public function testHandleCallsHandleOnHttpKernel()
    {
        $type = HttpKernelInterface::MASTER_REQUEST;
        $catch = true;
        $request = new Request();

        $httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
            ->disableOriginalConstructor()
            ->getMock();
        $httpKernelMock
            ->expects($this->once())
            ->method('handle')
            ->with($request, $type, $catch);

        $kernel = $this->getKernel(array('getHttpKernel'));
        $kernel->expects($this->once())
            ->method('getHttpKernel')
            ->will($this->returnValue($httpKernelMock));

        $kernel->handle($request, $type, $catch);
    }

    public function testHandleBootsTheKernel()
    {
        $type = HttpKernelInterface::MASTER_REQUEST;
        $catch = true;
        $request = new Request();

        $httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
            ->disableOriginalConstructor()
            ->getMock();

        $kernel = $this->getKernel(array('getHttpKernel', 'boot'));
        $kernel->expects($this->once())
            ->method('getHttpKernel')
            ->will($this->returnValue($httpKernelMock));

        $kernel->expects($this->once())
            ->method('boot');

        $kernel->handle($request, $type, $catch);
    }

    public function testStripComments()
    {
        if (!function_exists('token_get_all')) {
            $this->markTestSkipped('The function token_get_all() is not available.');

            return;
        }
        $source = <<<'EOF'
<?php

$string = 'string should not be   modified';

$string = 'string should not be

modified';


$heredoc = <<<HD


Heredoc should not be   modified


HD;

$nowdoc = <<<'ND'


Nowdoc should not be   modified


ND;

/**
 * some class comments to strip
 */
class TestClass
{
    /**
     * some method comments to strip
     */
    public function doStuff()
    {
        // inline comment
    }
}
EOF;
        $expected = <<<'EOF'
<?php
$string = 'string should not be   modified';
$string = 'string should not be

modified';
$heredoc = <<<HD


Heredoc should not be   modified


HD;
$nowdoc = <<<'ND'


Nowdoc should not be   modified


ND;
class TestClass
{
    public function doStuff()
    {
        }
}
EOF;

        $output = Kernel::stripComments($source);

        // Heredocs are preserved, making the output mixing Unix and Windows line
        // endings, switching to "\n" everywhere on Windows to avoid failure.
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
            $expected = str_replace("\r\n", "\n", $expected);
            $output = str_replace("\r\n", "\n", $output);
        }

        $this->assertEquals($expected, $output);
    }

    public function testIsClassInActiveBundleFalse()
    {
        $kernel = $this->getKernelMockForIsClassInActiveBundleTest();

        $this->assertFalse($kernel->isClassInActiveBundle('Not\In\Active\Bundle'));
    }

    public function testIsClassInActiveBundleFalseNoNamespace()
    {
        $kernel = $this->getKernelMockForIsClassInActiveBundleTest();

        $this->assertFalse($kernel->isClassInActiveBundle('NotNamespacedClass'));
    }

    public function testIsClassInActiveBundleTrue()
    {
        $kernel = $this->getKernelMockForIsClassInActiveBundleTest();

        $this->assertTrue($kernel->isClassInActiveBundle(__NAMESPACE__.'\Fixtures\FooBarBundle\SomeClass'));
    }

    protected function getKernelMockForIsClassInActiveBundleTest()
    {
        $bundle = new FooBarBundle();

        $kernel = $this->getKernel(array('getBundles'));
        $kernel->expects($this->once())
            ->method('getBundles')
            ->will($this->returnValue(array($bundle)));

        return $kernel;
    }

    public function testGetRootDir()
    {
        $kernel = new KernelForTest('test', true);

        $this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures', realpath($kernel->getRootDir()));
    }

    public function testGetName()
    {
        $kernel = new KernelForTest('test', true);

        $this->assertEquals('Fixtures', $kernel->getName());
    }

    public function testOverrideGetName()
    {
        $kernel = new KernelForOverrideName('test', true);

        $this->assertEquals('overridden', $kernel->getName());
    }

    public function testSerialize()
    {
        $env = 'test_env';
        $debug = true;
        $kernel = new KernelForTest($env, $debug);

        $expected = serialize(array($env, $debug));
        $this->assertEquals($expected, $kernel->serialize());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLocateResourceThrowsExceptionWhenNameIsNotValid()
    {
        $this->getKernel()->locateResource('Foo');
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testLocateResourceThrowsExceptionWhenNameIsUnsafe()
    {
        $this->getKernel()->locateResource('@FooBundle/../bar');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist()
    {
        $this->getKernel()->locateResource('@FooBundle/config/routing.xml');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
        ;

        $kernel->locateResource('@Bundle1Bundle/config/routing.xml');
    }

    public function testLocateResourceReturnsTheFirstThatMatches()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
        ;

        $this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt', $kernel->locateResource('@Bundle1Bundle/foo.txt'));
    }

    public function testLocateResourceReturnsTheFirstThatMatchesWithParent()
    {
        $parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
        $child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');

        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->exactly(2))
            ->method('getBundle')
            ->will($this->returnValue(array($child, $parent)))
        ;

        $this->assertEquals(__DIR__.'/Fixtures/Bundle2Bundle/foo.txt', $kernel->locateResource('@ParentAABundle/foo.txt'));
        $this->assertEquals(__DIR__.'/Fixtures/Bundle1Bundle/bar.txt', $kernel->locateResource('@ParentAABundle/bar.txt'));
    }

    public function testLocateResourceReturnsAllMatches()
    {
        $parent = $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle');
        $child = $this->getBundle(__DIR__.'/Fixtures/Bundle2Bundle');

        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($child, $parent)))
        ;

        $this->assertEquals(array(
            __DIR__.'/Fixtures/Bundle2Bundle/foo.txt',
            __DIR__.'/Fixtures/Bundle1Bundle/foo.txt'),
            $kernel->locateResource('@Bundle1Bundle/foo.txt', null, false));
    }

    public function testLocateResourceReturnsAllMatchesBis()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array(
                $this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'),
                $this->getBundle(__DIR__.'/Foobar')
            )))
        ;

        $this->assertEquals(
            array(__DIR__.'/Fixtures/Bundle1Bundle/foo.txt'),
            $kernel->locateResource('@Bundle1Bundle/foo.txt', null, false)
        );
    }

    public function testLocateResourceIgnoresDirOnNonResource()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle'))))
        ;

        $this->assertEquals(
            __DIR__.'/Fixtures/Bundle1Bundle/foo.txt',
            $kernel->locateResource('@Bundle1Bundle/foo.txt', __DIR__.'/Fixtures')
        );
    }

    public function testLocateResourceReturnsTheDirOneForResources()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
        ;

        $this->assertEquals(
            __DIR__.'/Fixtures/Resources/FooBundle/foo.txt',
            $kernel->locateResource('@FooBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources')
        );
    }

    public function testLocateResourceReturnsTheDirOneForResourcesAndBundleOnes()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->once())
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
        ;

        $this->assertEquals(array(
            __DIR__.'/Fixtures/Resources/Bundle1Bundle/foo.txt',
            __DIR__.'/Fixtures/Bundle1Bundle/Resources/foo.txt'),
            $kernel->locateResource('@Bundle1Bundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
        );
    }

    public function testLocateResourceOverrideBundleAndResourcesFolders()
    {
        $parent = $this->getBundle(__DIR__.'/Fixtures/BaseBundle', null, 'BaseBundle', 'BaseBundle');
        $child = $this->getBundle(__DIR__.'/Fixtures/ChildBundle', 'ParentBundle', 'ChildBundle', 'ChildBundle');

        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->exactly(4))
            ->method('getBundle')
            ->will($this->returnValue(array($child, $parent)))
        ;

        $this->assertEquals(array(
            __DIR__.'/Fixtures/Resources/ChildBundle/foo.txt',
            __DIR__.'/Fixtures/ChildBundle/Resources/foo.txt',
            __DIR__.'/Fixtures/BaseBundle/Resources/foo.txt',
            ),
            $kernel->locateResource('@BaseBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources', false)
        );

        $this->assertEquals(
            __DIR__.'/Fixtures/Resources/ChildBundle/foo.txt',
            $kernel->locateResource('@BaseBundle/Resources/foo.txt', __DIR__.'/Fixtures/Resources')
        );

        try {
            $kernel->locateResource('@BaseBundle/Resources/hide.txt', __DIR__.'/Fixtures/Resources', false);
            $this->fail('Hidden resources should raise an exception when returning an array of matching paths');
        } catch (\RuntimeException $e) {
        }

        try {
            $kernel->locateResource('@BaseBundle/Resources/hide.txt', __DIR__.'/Fixtures/Resources', true);
            $this->fail('Hidden resources should raise an exception when returning the first matching path');
        } catch (\RuntimeException $e) {
        }
    }

    public function testLocateResourceOnDirectories()
    {
        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->exactly(2))
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/FooBundle', null, null, 'FooBundle'))))
        ;

        $this->assertEquals(
            __DIR__.'/Fixtures/Resources/FooBundle/',
            $kernel->locateResource('@FooBundle/Resources/', __DIR__.'/Fixtures/Resources')
        );
        $this->assertEquals(
            __DIR__.'/Fixtures/Resources/FooBundle',
            $kernel->locateResource('@FooBundle/Resources', __DIR__.'/Fixtures/Resources')
        );

        $kernel = $this->getKernel(array('getBundle'));
        $kernel
            ->expects($this->exactly(2))
            ->method('getBundle')
            ->will($this->returnValue(array($this->getBundle(__DIR__.'/Fixtures/Bundle1Bundle', null, null, 'Bundle1Bundle'))))
        ;

        $this->assertEquals(
            __DIR__.'/Fixtures/Bundle1Bundle/Resources/',
            $kernel->locateResource('@Bundle1Bundle/Resources/')
        );
        $this->assertEquals(
            __DIR__.'/Fixtures/Bundle1Bundle/Resources',
            $kernel->locateResource('@Bundle1Bundle/Resources')
        );
    }

    public function testInitializeBundles()
    {
        $parent = $this->getBundle(null, null, 'ParentABundle');
        $child = $this->getBundle(null, 'ParentABundle', 'ChildABundle');

        // use test kernel so we can access getBundleMap()
        $kernel = $this->getKernelForTest(array('registerBundles'));
        $kernel
            ->expects($this->once())
            ->method('registerBundles')
            ->will($this->returnValue(array($parent, $child)))
        ;
        $kernel->boot();

        $map = $kernel->getBundleMap();
        $this->assertEquals(array($child, $parent), $map['ParentABundle']);
    }

    public function testInitializeBundlesSupportInheritanceCascade()
    {
        $grandparent = $this->getBundle(null, null, 'GrandParentBBundle');
        $parent = $this->getBundle(null, 'GrandParentBBundle', 'ParentBBundle');
        $child = $this->getBundle(null, 'ParentBBundle', 'ChildBBundle');

        // use test kernel so we can access getBundleMap()
        $kernel = $this->getKernelForTest(array('registerBundles'));
        $kernel
            ->expects($this->once())
            ->method('registerBundles')
            ->will($this->returnValue(array($grandparent, $parent, $child)))
        ;
        $kernel->boot();

        $map = $kernel->getBundleMap();
        $this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentBBundle']);
        $this->assertEquals(array($child, $parent), $map['ParentBBundle']);
        $this->assertEquals(array($child), $map['ChildBBundle']);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Bundle "ChildCBundle" extends bundle "FooBar", which is not registered.
     */
    public function testInitializeBundlesThrowsExceptionWhenAParentDoesNotExists()
    {
        $child = $this->getBundle(null, 'FooBar', 'ChildCBundle');
        $kernel = $this->getKernel(array(), array($child));
        $kernel->boot();
    }

    public function testInitializeBundlesSupportsArbitraryBundleRegistrationOrder()
    {
        $grandparent = $this->getBundle(null, null, 'GrandParentCBundle');
        $parent = $this->getBundle(null, 'GrandParentCBundle', 'ParentCBundle');
        $child = $this->getBundle(null, 'ParentCBundle', 'ChildCBundle');

        // use test kernel so we can access getBundleMap()
        $kernel = $this->getKernelForTest(array('registerBundles'));
        $kernel
            ->expects($this->once())
            ->method('registerBundles')
            ->will($this->returnValue(array($parent, $grandparent, $child)))
        ;
        $kernel->boot();

        $map = $kernel->getBundleMap();
        $this->assertEquals(array($child, $parent, $grandparent), $map['GrandParentCBundle']);
        $this->assertEquals(array($child, $parent), $map['ParentCBundle']);
        $this->assertEquals(array($child), $map['ChildCBundle']);
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle".
     */
    public function testInitializeBundlesThrowsExceptionWhenABundleIsDirectlyExtendedByTwoBundles()
    {
        $parent = $this->getBundle(null, null, 'ParentCBundle');
        $child1 = $this->getBundle(null, 'ParentCBundle', 'ChildC1Bundle');
        $child2 = $this->getBundle(null, 'ParentCBundle', 'ChildC2Bundle');

        $kernel = $this->getKernel(array(), array($parent, $child1, $child2));
        $kernel->boot();
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName"
     */
    public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName()
    {
        $fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName');
        $barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName');

        $kernel = $this->getKernel(array(), array($fooBundle, $barBundle));
        $kernel->boot();
    }

    /**
     * @expectedException \LogicException
     * @expectedExceptionMessage Bundle "CircularRefBundle" can not extend itself.
     */
    public function testInitializeBundleThrowsExceptionWhenABundleExtendsItself()
    {
        $circularRef = $this->getBundle(null, 'CircularRefBundle', 'CircularRefBundle');

        $kernel = $this->getKernel(array(), array($circularRef));
        $kernel->boot();
    }

    public function testTerminateReturnsSilentlyIfKernelIsNotBooted()
    {
        $kernel = $this->getKernel(array('getHttpKernel'));
        $kernel->expects($this->never())
            ->method('getHttpKernel');

        $kernel->terminate(Request::create('/'), new Response());
    }

    public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
    {
        // does not implement TerminableInterface
        $httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $httpKernelMock
            ->expects($this->never())
            ->method('terminate');

        $kernel = $this->getKernel(array('getHttpKernel'));
        $kernel->expects($this->once())
            ->method('getHttpKernel')
            ->will($this->returnValue($httpKernelMock));

        $kernel->boot();
        $kernel->terminate(Request::create('/'), new Response());

        // implements TerminableInterface
        $httpKernelMock = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernel')
            ->disableOriginalConstructor()
            ->setMethods(array('terminate'))
            ->getMock();

        $httpKernelMock
            ->expects($this->once())
            ->method('terminate');

        $kernel = $this->getKernel(array('getHttpKernel'));
        $kernel->expects($this->exactly(2))
            ->method('getHttpKernel')
            ->will($this->returnValue($httpKernelMock));

        $kernel->boot();
        $kernel->terminate(Request::create('/'), new Response());
    }

    /**
     * Returns a mock for the BundleInterface
     *
     * @return BundleInterface
     */
    protected function getBundle($dir = null, $parent = null, $className = null, $bundleName = null)
    {
        $bundle = $this
            ->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')
            ->setMethods(array('getPath', 'getParent', 'getName'))
            ->disableOriginalConstructor()
        ;

        if ($className) {
            $bundle->setMockClassName($className);
        }

        $bundle = $bundle->getMockForAbstractClass();

        $bundle
            ->expects($this->any())
            ->method('getName')
            ->will($this->returnValue(null === $bundleName ? get_class($bundle) : $bundleName))
        ;

        $bundle
            ->expects($this->any())
            ->method('getPath')
            ->will($this->returnValue($dir))
        ;

        $bundle
            ->expects($this->any())
            ->method('getParent')
            ->will($this->returnValue($parent))
        ;

        return $bundle;
    }

    /**
     * Returns a mock for the abstract kernel.
     *
     * @param array $methods Additional methods to mock (besides the abstract ones)
     * @param array $bundles Bundles to register
     *
     * @return Kernel
     */
    protected function getKernel(array $methods = array(), array $bundles = array())
    {
        $methods[] = 'registerBundles';

        $kernel = $this
            ->getMockBuilder('Symfony\Component\HttpKernel\Kernel')
            ->setMethods($methods)
            ->setConstructorArgs(array('test', false))
            ->getMockForAbstractClass()
        ;
        $kernel->expects($this->any())
            ->method('registerBundles')
            ->will($this->returnValue($bundles))
        ;
        $p = new \ReflectionProperty($kernel, 'rootDir');
        $p->setAccessible(true);
        $p->setValue($kernel, __DIR__.'/Fixtures');

        return $kernel;
    }

    protected function getKernelForTest(array $methods = array())
    {
        $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest')
            ->setConstructorArgs(array('test', false))
            ->setMethods($methods)
            ->getMock();
        $p = new \ReflectionProperty($kernel, 'rootDir');
        $p->setAccessible(true);
        $p->setValue($kernel, __DIR__.'/Fixtures');

        return $kernel;
    }
}
PKJ1[6^P�THttpKernel/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\CacheClearer;

use Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface;
use Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer;

class ChainCacheClearerTest extends \PHPUnit_Framework_TestCase
{
    protected static $cacheDir;

    public static function setUpBeforeClass()
    {
        self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_clearer_dir');
    }

    public static function tearDownAfterClass()
    {
        @unlink(self::$cacheDir);
    }

    public function testInjectClearersInConstructor()
    {
        $clearer = $this->getMockClearer();
        $clearer
            ->expects($this->once())
            ->method('clear');

        $chainClearer = new ChainCacheClearer(array($clearer));
        $chainClearer->clear(self::$cacheDir);
    }

    public function testInjectClearerUsingAdd()
    {
        $clearer = $this->getMockClearer();
        $clearer
            ->expects($this->once())
            ->method('clear');

        $chainClearer = new ChainCacheClearer();
        $chainClearer->add($clearer);
        $chainClearer->clear(self::$cacheDir);
    }

    protected function getMockClearer()
    {
        return $this->getMock('Symfony\Component\HttpKernel\CacheClearer\CacheClearerInterface');
    }
}
PKJ1[32ET��NHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/TestEventDispatcher.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\EventDispatcher\Debug\TraceableEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class TestEventDispatcher extends EventDispatcher implements TraceableEventDispatcherInterface
{
    public function getCalledListeners()
    {
        return array('foo');
    }

    public function getNotCalledListeners()
    {
        return array('bar');
    }
}
PKJ1[g&��fHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionAbsentBundle/ExtensionAbsentBundle.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ExtensionAbsentBundle extends Bundle
{
}
PKJ1[x���dHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/BarCommand.phpnu�[���<?php

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;

use Symfony\Component\Console\Command\Command;

/**
 * This command has a required parameter on the constructor and will be ignored by the default Bundle implementation.
 *
 * @see Symfony\Component\HttpKernel\Bundle\Bundle::registerCommands
 */
class BarCommand extends Command
{
    public function __construct($example, $name = 'bar')
    {

    }
}
PKJ1[��W���dHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/FooCommand.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command;

use Symfony\Component\Console\Command\Command;

class FooCommand extends Command
{
    protected function configure()
    {
        $this->setName('foo');
    }

}
PKJ1[`A�hHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/ExtensionPresentBundle.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ExtensionPresentBundle extends Bundle
{
}
PKJ1[O�g�VVHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/DependencyInjection/ExtensionPresentExtension.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class ExtensionPresentExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
    }
}
PKJ1[GQ�>`
`
dHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/MockObjectTestProjectContainer.phpnu�[���<?php
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
class MockObjectTestProjectContainer extends Container
{
    private $parameters;
    public function __construct()
    {
        $this->parameters = $this->getDefaultParameters();
        $this->services =
        $this->scopedServices =
        $this->scopeStacks = array();
        $this->set('service_container', $this);
        $this->scopes = array();
        $this->scopeChildren = array();
        $this->aliases = array();
    }
    public function getParameter($name)
    {
        $name = strtolower($name);
        if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
            throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
        }
        return $this->parameters[$name];
    }
    public function hasParameter($name)
    {
        $name = strtolower($name);
        return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
    }
    public function setParameter($name, $value)
    {
        throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
    }
    public function getParameterBag()
    {
        if (null === $this->parameterBag) {
            $this->parameterBag = new FrozenParameterBag($this->parameters);
        }
        return $this->parameterBag;
    }
    protected function getDefaultParameters()
    {
        return array(
            'kernel.root_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures',
            'kernel.environment' => 'test',
            'kernel.debug' => false,
            'kernel.name' => 'MockObject',
            'kernel.cache_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test',
            'kernel.logs_dir' => '/Users/fabien/Code/github/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Fixtures/logs',
            'kernel.bundles' => array(
                'Mock_Bundle_7fc4ae26' => 'Mock_Bundle_7fc4ae26',
            ),
            'kernel.charset' => 'UTF-8',
            'kernel.container_class' => 'MockObjectTestProjectContainer',
        );
    }
}
PKJ1[#��MHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/classes.mapnu�[���<?php return array (
);PKJ1[LHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle2Bundle/foo.txtnu�[���PKJ1[q�}VffPHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/KernelForOverrideName.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class KernelForOverrideName extends Kernel
{
    protected $name = 'overridden';

    public function registerBundles()
    {

    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {

    }
}
PKJ1[THttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/foo.txtnu�[���PKJ1[UHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/hide.txtnu�[���PKJ1[LHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/foo.txtnu�[���PKJ1[LHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/bar.txtnu�[���PKJ1[VHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/Resources/foo.txtnu�[���PKJ1[RHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/FooBundle/foo.txtnu�[���PKJ1[THttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/ChildBundle/foo.txtnu�[���PKJ1[VHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/Bundle1Bundle/foo.txtnu�[���PKJ1[THttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/BaseBundle/hide.txtnu�[���PKJ1[SHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/foo.txtnu�[���PKJ1[THttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/hide.txtnu�[���PKJ1[&#�EHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/TestClient.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Client;

class TestClient extends Client
{
    protected function getScript($request)
    {
        $script = parent::getScript($request);

        $autoload = file_exists(__DIR__.'/../../vendor/autoload.php')
            ? __DIR__.'/../../vendor/autoload.php'
            : __DIR__.'/../../../../../../vendor/autoload.php'
        ;

        $script = preg_replace('/(\->register\(\);)/', "$0\nrequire_once '$autoload';\n", $script);

        return $script;
    }
}
PKJ1[y��h��HHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/KernelForTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class KernelForTest extends Kernel
{
    public function getBundleMap()
    {
        return $this->bundleMap;
    }

    public function registerBundles()
    {
        return array();
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }

    public function isBooted()
    {
        return $this->booted;
    }
}
PKK1[�0����GHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/FooBarBundle.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class FooBarBundle extends Bundle
{
    // We need a full namespaced bundle instance to test isClassInActiveBundle
}
PKK1[��?ɜ�fHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/ExtensionLoadedBundle.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionLoadedBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ExtensionLoadedBundle extends Bundle
{
}
PKK1[��_�TT}HttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/DependencyInjection/ExtensionLoadedExtension.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionLoadedBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;

class ExtensionLoadedExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
    }
}
PKK1[���S��VHttpKernel/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\CacheWarmer;

use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate;
use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;

class CacheWarmerAggregateTest extends \PHPUnit_Framework_TestCase
{
    protected static $cacheDir;

    public static function setUpBeforeClass()
    {
        self::$cacheDir = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
    }

    public static function tearDownAfterClass()
    {
        @unlink(self::$cacheDir);
    }

    public function testInjectWarmersUsingConstructor()
    {
        $warmer = $this->getCacheWarmerMock();
        $warmer
            ->expects($this->once())
            ->method('warmUp');
        $aggregate = new CacheWarmerAggregate(array($warmer));
        $aggregate->warmUp(self::$cacheDir);
    }

    public function testInjectWarmersUsingAdd()
    {
        $warmer = $this->getCacheWarmerMock();
        $warmer
            ->expects($this->once())
            ->method('warmUp');
        $aggregate = new CacheWarmerAggregate();
        $aggregate->add($warmer);
        $aggregate->warmUp(self::$cacheDir);
    }

    public function testInjectWarmersUsingSetWarmers()
    {
        $warmer = $this->getCacheWarmerMock();
        $warmer
            ->expects($this->once())
            ->method('warmUp');
        $aggregate = new CacheWarmerAggregate();
        $aggregate->setWarmers(array($warmer));
        $aggregate->warmUp(self::$cacheDir);
    }

    public function testWarmupDoesCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsEnabled()
    {
        $warmer = $this->getCacheWarmerMock();
        $warmer
            ->expects($this->never())
            ->method('isOptional');
        $warmer
            ->expects($this->once())
            ->method('warmUp');

        $aggregate = new CacheWarmerAggregate(array($warmer));
        $aggregate->enableOptionalWarmers();
        $aggregate->warmUp(self::$cacheDir);
    }

    public function testWarmupDoesNotCallWarmupOnOptionalWarmersWhenEnableOptionalWarmersIsNotEnabled()
    {
        $warmer = $this->getCacheWarmerMock();
        $warmer
            ->expects($this->once())
            ->method('isOptional')
            ->will($this->returnValue(true));
        $warmer
            ->expects($this->never())
            ->method('warmUp');

        $aggregate = new CacheWarmerAggregate(array($warmer));
        $aggregate->warmUp(self::$cacheDir);
    }

    protected function getCacheWarmerMock()
    {
        $warmer = $this->getMockBuilder('Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface')
            ->disableOriginalConstructor()
            ->getMock();

        return $warmer;
    }
}
PKK1[���,%%MHttpKernel/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\CacheWarmer;

use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer;

class CacheWarmerTest extends \PHPUnit_Framework_TestCase
{
    protected static $cacheFile;

    public static function setUpBeforeClass()
    {
        self::$cacheFile = tempnam(sys_get_temp_dir(), 'sf2_cache_warmer_dir');
    }

    public static function tearDownAfterClass()
    {
        @unlink(self::$cacheFile);
    }

    public function testWriteCacheFileCreatesTheFile()
    {
        $warmer = new TestCacheWarmer(self::$cacheFile);
        $warmer->warmUp(dirname(self::$cacheFile));

        $this->assertTrue(file_exists(self::$cacheFile));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testWriteNonWritableCacheFileThrowsARuntimeException()
    {
        $nonWritableFile = '/this/file/is/very/probably/not/writable';
        $warmer = new TestCacheWarmer($nonWritableFile);
        $warmer->warmUp(dirname($nonWritableFile));
    }
}

class TestCacheWarmer extends CacheWarmer
{
    protected $file;

    public function __construct($file)
    {
        $this->file = $file;
    }

    public function warmUp($cacheDir)
    {
        $this->writeCacheFile($this->file, 'content');
    }

    public function isOptional()
    {
        return false;
    }
}
PKK1[0��GG@HttpKernel/Symfony/Component/HttpKernel/Tests/TestHttpKernel.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class TestHttpKernel extends HttpKernel implements ControllerResolverInterface
{
    public function __construct()
    {
        parent::__construct(new EventDispatcher(), $this);
    }

    public function getController(Request $request)
    {
        return array($this, 'callController');
    }

    public function getArguments(Request $request, $controller)
    {
        return array($request);
    }

    public function callController(Request $request)
    {
        return new Response('Request: '.$request->getRequestUri());
    }
}
PKK1[q��<HttpKernel/Symfony/Component/HttpKernel/Tests/ClientTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Symfony\Component\HttpKernel\Client;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Tests\Fixtures\TestClient;

class ClientTest extends \PHPUnit_Framework_TestCase
{
    public function testDoRequest()
    {
        $client = new Client(new TestHttpKernel());

        $client->request('GET', '/');
        $this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Request', $client->getInternalRequest());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Request', $client->getRequest());
        $this->assertInstanceOf('Symfony\Component\BrowserKit\Response', $client->getInternalResponse());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $client->getResponse());

        $client->request('GET', 'http://www.example.com/');
        $this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request');
        $this->assertEquals('www.example.com', $client->getRequest()->getHost(), '->doRequest() uses the request handler to make the request');

        $client->request('GET', 'http://www.example.com/?parameter=http://google.com');
        $this->assertEquals('http://www.example.com/?parameter='.urlencode('http://google.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request');
    }

    public function testGetScript()
    {
        $client = new TestClient(new TestHttpKernel());
        $client->insulate();
        $client->request('GET', '/');

        $this->assertEquals('Request: /', $client->getResponse()->getContent(), '->getScript() returns a script that uses the request handler to make the request');
    }

    public function testFilterResponseConvertsCookies()
    {
        $client = new Client(new TestHttpKernel());

        $r = new \ReflectionObject($client);
        $m = $r->getMethod('filterResponse');
        $m->setAccessible(true);

        $expected = array(
            'foo=bar; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly',
            'foo1=bar1; expires=Sun, 15 Feb 2009 20:00:00 GMT; domain=http://example.com; path=/foo; secure; httponly'
        );

        $response = new Response();
        $response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
        $domResponse = $m->invoke($client, $response);
        $this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));

        $response = new Response();
        $response->headers->setCookie(new Cookie('foo', 'bar', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
        $response->headers->setCookie(new Cookie('foo1', 'bar1', \DateTime::createFromFormat('j-M-Y H:i:s T', '15-Feb-2009 20:00:00 GMT')->format('U'), '/foo', 'http://example.com', true, true));
        $domResponse = $m->invoke($client, $response);
        $this->assertEquals($expected[0], $domResponse->getHeader('Set-Cookie'));
        $this->assertEquals($expected, $domResponse->getHeader('Set-Cookie', false));
    }

    public function testFilterResponseSupportsStreamedResponses()
    {
        $client = new Client(new TestHttpKernel());

        $r = new \ReflectionObject($client);
        $m = $r->getMethod('filterResponse');
        $m->setAccessible(true);

        $response = new StreamedResponse(function () {
            echo 'foo';
        });

        $domResponse = $m->invoke($client, $response);
        $this->assertEquals('foo', $domResponse->getContent());
    }

    public function testUploadedFile()
    {
        $source = tempnam(sys_get_temp_dir(), 'source');
        $target = sys_get_temp_dir().'/sf.moved.file';
        @unlink($target);

        $kernel = new TestHttpKernel();
        $client = new Client($kernel);

        $files = array(
            array('tmp_name' => $source, 'name' => 'original', 'type' => 'mime/original', 'size' => 123, 'error' => UPLOAD_ERR_OK),
            new UploadedFile($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true),
        );

        $file = null;
        foreach ($files as $file) {
            $client->request('POST', '/', array(), array('foo' => $file));

            $files = $client->getRequest()->files->all();

            $this->assertCount(1, $files);

            $file = $files['foo'];

            $this->assertEquals('original', $file->getClientOriginalName());
            $this->assertEquals('mime/original', $file->getClientMimeType());
            $this->assertEquals('123', $file->getClientSize());
            $this->assertTrue($file->isValid());
        }

        $file->move(dirname($target), basename($target));

        $this->assertFileExists($target);
        unlink($target);
    }

    public function testUploadedFileWhenSizeExceedsUploadMaxFileSize()
    {
        $source = tempnam(sys_get_temp_dir(), 'source');

        $kernel = new TestHttpKernel();
        $client = new Client($kernel);

        $file = $this
            ->getMockBuilder('Symfony\Component\HttpFoundation\File\UploadedFile')
            ->setConstructorArgs(array($source, 'original', 'mime/original', 123, UPLOAD_ERR_OK, true))
            ->setMethods(array('getSize'))
            ->getMock()
        ;

        $file->expects($this->once())
            ->method('getSize')
            ->will($this->returnValue(INF))
        ;

        $client->request('POST', '/', array(), array($file));

        $files = $client->getRequest()->files->all();

        $this->assertCount(1, $files);

        $file = $files[0];

        $this->assertFalse($file->isValid());
        $this->assertEquals(UPLOAD_ERR_INI_SIZE, $file->getError());
        $this->assertEquals('mime/original', $file->getClientMimeType());
        $this->assertEquals('original', $file->getClientOriginalName());
        $this->assertEquals(0, $file->getClientSize());

        unlink($source);
    }
}
PKK1[݂(�$�$THttpKernel/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Debug;

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Stopwatch\Stopwatch;

class TraceableEventDispatcherTest extends \PHPUnit_Framework_TestCase
{
    public function testAddRemoveListener()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $tdispatcher->addListener('foo', $listener = function () { ; });
        $listeners = $dispatcher->getListeners('foo');
        $this->assertCount(1, $listeners);
        $this->assertSame($listener, $listeners[0]);

        $tdispatcher->removeListener('foo', $listener);
        $this->assertCount(0, $dispatcher->getListeners('foo'));
    }

    public function testGetListeners()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $tdispatcher->addListener('foo', $listener = function () { ; });
        $this->assertSame($dispatcher->getListeners('foo'), $tdispatcher->getListeners('foo'));
    }

    public function testHasListeners()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $this->assertFalse($dispatcher->hasListeners('foo'));
        $this->assertFalse($tdispatcher->hasListeners('foo'));

        $tdispatcher->addListener('foo', $listener = function () { ; });
        $this->assertTrue($dispatcher->hasListeners('foo'));
        $this->assertTrue($tdispatcher->hasListeners('foo'));
    }

    public function testAddRemoveSubscriber()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());

        $subscriber = new EventSubscriber();

        $tdispatcher->addSubscriber($subscriber);
        $listeners = $dispatcher->getListeners('foo');
        $this->assertCount(1, $listeners);
        $this->assertSame(array($subscriber, 'call'), $listeners[0]);

        $tdispatcher->removeSubscriber($subscriber);
        $this->assertCount(0, $dispatcher->getListeners('foo'));
    }

    public function testGetCalledListeners()
    {
        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
        $tdispatcher->addListener('foo', $listener = function () { ; });

        $this->assertEquals(array(), $tdispatcher->getCalledListeners());
        $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getNotCalledListeners());

        $tdispatcher->dispatch('foo');

        $this->assertEquals(array('foo.closure' => array('event' => 'foo', 'type' => 'Closure', 'pretty' => 'closure')), $tdispatcher->getCalledListeners());
        $this->assertEquals(array(), $tdispatcher->getNotCalledListeners());
    }

    public function testLogger()
    {
        $logger = $this->getMock('Psr\Log\LoggerInterface');

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
        $tdispatcher->addListener('foo', $listener1 = function () { ; });
        $tdispatcher->addListener('foo', $listener2 = function () { ; });

        $logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
        $logger->expects($this->at(1))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");

        $tdispatcher->dispatch('foo');
    }

    public function testLoggerWithStoppedEvent()
    {
        $logger = $this->getMock('Psr\Log\LoggerInterface');

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch(), $logger);
        $tdispatcher->addListener('foo', $listener1 = function (Event $event) { $event->stopPropagation(); });
        $tdispatcher->addListener('foo', $listener2 = function () { ; });

        $logger->expects($this->at(0))->method('debug')->with("Notified event \"foo\" to listener \"closure\".");
        $logger->expects($this->at(1))->method('debug')->with("Listener \"closure\" stopped propagation of the event \"foo\".");
        $logger->expects($this->at(2))->method('debug')->with("Listener \"closure\" was not called for event \"foo\".");

        $tdispatcher->dispatch('foo');
    }

    public function testDispatchCallListeners()
    {
        $called = array();

        $dispatcher = new EventDispatcher();
        $tdispatcher = new TraceableEventDispatcher($dispatcher, new Stopwatch());
        $tdispatcher->addListener('foo', $listener1 = function () use (&$called) { $called[] = 'foo1'; });
        $tdispatcher->addListener('foo', $listener2 = function () use (&$called) { $called[] = 'foo2'; });

        $tdispatcher->dispatch('foo');

        $this->assertEquals(array('foo1', 'foo2'), $called);
    }

    public function testDispatchNested()
    {
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $loop = 1;
        $dispatcher->addListener('foo', $listener1 = function () use ($dispatcher, &$loop) {
            ++$loop;
            if (2 == $loop) {
                $dispatcher->dispatch('foo');
            }
        });

        $dispatcher->dispatch('foo');
    }

    public function testDispatchReusedEventNested()
    {
        $nestedCall = false;
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), new Stopwatch());
        $dispatcher->addListener('foo', function (Event $e) use ($dispatcher) {
            $dispatcher->dispatch('bar', $e);
        });
        $dispatcher->addListener('bar', function (Event $e) use (&$nestedCall) {
            $nestedCall = true;
        });

        $this->assertFalse($nestedCall);
        $dispatcher->dispatch('foo');
        $this->assertTrue($nestedCall);
    }

    public function testStopwatchSections()
    {
        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch = new Stopwatch());
        $kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
        $request = Request::create('/');
        $response = $kernel->handle($request);
        $kernel->terminate($request, $response);

        $events = $stopwatch->getSectionEvents($response->headers->get('X-Debug-Token'));
        $this->assertEquals(array(
            '__section__',
            'kernel.request',
            'kernel.request.loading',
            'kernel.controller',
            'kernel.controller.loading',
            'controller',
            'kernel.response',
            'kernel.response.loading',
            'kernel.terminate',
            'kernel.terminate.loading',
        ), array_keys($events));
    }

    public function testStopwatchCheckControllerOnRequestEvent()
    {
        $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
            ->setMethods(array('isStarted'))
            ->getMock();
        $stopwatch->expects($this->once())
            ->method('isStarted')
            ->will($this->returnValue(false));

        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);

        $kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
        $request = Request::create('/');
        $kernel->handle($request);
    }

    public function testStopwatchStopControllerOnRequestEvent()
    {
        $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')
            ->setMethods(array('isStarted', 'stop', 'stopSection'))
            ->getMock();
        $stopwatch->expects($this->once())
            ->method('isStarted')
            ->will($this->returnValue(true));
        $stopwatch->expects($this->once())
            ->method('stop');
        $stopwatch->expects($this->once())
            ->method('stopSection');

        $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch);

        $kernel = $this->getHttpKernel($dispatcher, function () { return new Response(); });
        $request = Request::create('/');
        $kernel->handle($request);
    }

    protected function getHttpKernel($dispatcher, $controller)
    {
        $resolver = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolverInterface');
        $resolver->expects($this->once())->method('getController')->will($this->returnValue($controller));
        $resolver->expects($this->once())->method('getArguments')->will($this->returnValue(array()));

        return new HttpKernel($dispatcher, $resolver);
    }
}

class EventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('foo' => 'call');
    }
}
PKK1[���!/
/
THttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpKernel\EventListener\FragmentListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\UriSigner;

class FragmentListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testOnlyTriggeredOnFragmentRoute()
    {
        $request = Request::create('http://example.com/foo?_path=foo%3Dbar%26_controller%3Dfoo');

        $listener = new FragmentListener(new UriSigner('foo'));
        $event = $this->createGetResponseEvent($request);

        $expected = $request->attributes->all();

        $listener->onKernelRequest($event);

        $this->assertEquals($expected, $request->attributes->all());
        $this->assertTrue($request->query->has('_path'));
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     */
    public function testAccessDeniedWithNonSafeMethods()
    {
        $request = Request::create('http://example.com/_fragment', 'POST');

        $listener = new FragmentListener(new UriSigner('foo'));
        $event = $this->createGetResponseEvent($request);

        $listener->onKernelRequest($event);
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     */
    public function testAccessDeniedWithNonLocalIps()
    {
        $request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));

        $listener = new FragmentListener(new UriSigner('foo'));
        $event = $this->createGetResponseEvent($request);

        $listener->onKernelRequest($event);
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     */
    public function testAccessDeniedWithWrongSignature()
    {
        $request = Request::create('http://example.com/_fragment', 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));

        $listener = new FragmentListener(new UriSigner('foo'));
        $event = $this->createGetResponseEvent($request);

        $listener->onKernelRequest($event);
    }

    public function testWithSignature()
    {
        $signer = new UriSigner('foo');
        $request = Request::create($signer->sign('http://example.com/_fragment?_path=foo%3Dbar%26_controller%3Dfoo'), 'GET', array(), array(), array(), array('REMOTE_ADDR' => '10.0.0.1'));

        $listener = new FragmentListener($signer);
        $event = $this->createGetResponseEvent($request);

        $listener->onKernelRequest($event);

        $this->assertEquals(array('foo' => 'bar', '_controller' => 'foo'), $request->attributes->get('_route_params'));
        $this->assertFalse($request->query->has('_path'));
    }

    private function createGetResponseEvent(Request $request)
    {
        return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
    }
}
PKK1[�W:ttUHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Tests\Logger;

/**
 * ExceptionListenerTest
 *
 * @author Robert Schönthal <seroscho@googlemail.com>
 */
class ExceptionListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $logger = new TestLogger();
        $l = new ExceptionListener('foo', $logger);

        $_logger = new \ReflectionProperty(get_class($l), 'logger');
        $_logger->setAccessible(true);
        $_controller = new \ReflectionProperty(get_class($l), 'controller');
        $_controller->setAccessible(true);

        $this->assertSame($logger, $_logger->getValue($l));
        $this->assertSame('foo', $_controller->getValue($l));
    }

    /**
     * @dataProvider provider
     */
    public function testHandleWithoutLogger($event, $event2)
    {
        // store the current error_log, and disable it temporarily
        $errorLog = ini_set('error_log', file_exists('/dev/null') ? '/dev/null' : 'nul');

        $l = new ExceptionListener('foo');
        $l->onKernelException($event);

        $this->assertEquals(new Response('foo'), $event->getResponse());

        try {
            $l->onKernelException($event2);
        } catch (\Exception $e) {
            $this->assertSame('foo', $e->getMessage());
        }

        // restore the old error_log
        ini_set('error_log', $errorLog);
    }

    /**
     * @dataProvider provider
     */
    public function testHandleWithLogger($event, $event2)
    {
        $logger = new TestLogger();

        $l = new ExceptionListener('foo', $logger);
        $l->onKernelException($event);

        $this->assertEquals(new Response('foo'), $event->getResponse());

        try {
            $l->onKernelException($event2);
        } catch (\Exception $e) {
            $this->assertSame('foo', $e->getMessage());
        }

        $this->assertEquals(3, $logger->countErrors());
        $this->assertCount(3, $logger->getLogs('critical'));
    }

    public function provider()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            return array(array(null, null));
        }

        $request = new Request();
        $exception = new \Exception('foo');
        $event = new GetResponseForExceptionEvent(new TestKernel(), $request, 'foo', $exception);
        $event2 = new GetResponseForExceptionEvent(new TestKernelThatThrowsException(), $request, 'foo', $exception);

        return array(
            array($event, $event2)
        );
    }

    public function testSubRequestFormat()
    {
        $listener = new ExceptionListener('foo', $this->getMock('Psr\Log\LoggerInterface'));

        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
            return new Response($request->getRequestFormat());
        }));

        $request = Request::create('/');
        $request->setRequestFormat('xml');

        $event = new GetResponseForExceptionEvent($kernel, $request, 'foo', new \Exception('foo'));
        $listener->onKernelException($event);

        $response = $event->getResponse();
        $this->assertEquals('xml', $response->getContent());
    }
}

class TestLogger extends Logger implements DebugLoggerInterface
{
    public function countErrors()
    {
        return count($this->logs['critical']);
    }
}

class TestKernel implements HttpKernelInterface
{
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        return new Response('foo');
    }
}

class TestKernelThatThrowsException implements HttpKernelInterface
{
    public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
    {
        throw new \Exception('bar');
    }
}
PKK1[(��kkTHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpKernel\EventListener\ProfilerListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Kernel;

class ProfilerListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Test to ensure BC without RequestStack
     *
     * @deprecated Deprecated since version 2.4, to be removed in 3.0.
     */
    public function testEventsWithoutRequestStack()
    {
        $profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile')
            ->disableOriginalConstructor()
            ->getMock();

        $profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler')
            ->disableOriginalConstructor()
            ->getMock();
        $profiler->expects($this->once())
            ->method('collect')
            ->will($this->returnValue($profile));

        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');

        $request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
            ->disableOriginalConstructor()
            ->getMock();

        $response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response')
            ->disableOriginalConstructor()
            ->getMock();

        $listener = new ProfilerListener($profiler);
        $listener->onKernelRequest(new GetResponseEvent($kernel, $request, Kernel::MASTER_REQUEST));
        $listener->onKernelResponse(new FilterResponseEvent($kernel, $request, Kernel::MASTER_REQUEST, $response));
        $listener->onKernelTerminate(new PostResponseEvent($kernel, $request, $response));
    }

    /**
     * Test a master and sub request with an exception and `onlyException` profiler option enabled.
     */
    public function testKernelTerminate()
    {
        $profile = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profile')
            ->disableOriginalConstructor()
            ->getMock();

        $profiler = $this->getMockBuilder('Symfony\Component\HttpKernel\Profiler\Profiler')
            ->disableOriginalConstructor()
            ->getMock();

        $profiler->expects($this->once())
            ->method('collect')
            ->will($this->returnValue($profile));

        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');

        $masterRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
            ->disableOriginalConstructor()
            ->getMock();

        $subRequest =  $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')
            ->disableOriginalConstructor()
            ->getMock();

        $response = $this->getMockBuilder('Symfony\Component\HttpFoundation\Response')
            ->disableOriginalConstructor()
            ->getMock();

        $onlyException = true;
        $listener      = new ProfilerListener($profiler, null, $onlyException);

        // master request
        $listener->onKernelRequest(new GetResponseEvent($kernel, $masterRequest, Kernel::MASTER_REQUEST));
        $listener->onKernelResponse(new FilterResponseEvent($kernel, $masterRequest, Kernel::MASTER_REQUEST, $response));

        // sub request
        $listener->onKernelRequest(new GetResponseEvent($kernel, $subRequest, Kernel::SUB_REQUEST));
        $listener->onKernelException(new GetResponseForExceptionEvent($kernel, $subRequest, Kernel::SUB_REQUEST, new HttpException(404)));
        $listener->onKernelResponse(new FilterResponseEvent($kernel, $subRequest, Kernel::SUB_REQUEST, $response));

        $listener->onKernelTerminate(new PostResponseEvent($kernel, $masterRequest, $response));
    }
}
PKK1[=v?�
�
OHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/EsiListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\EventListener\EsiListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;

class EsiListenerTest extends \PHPUnit_Framework_TestCase
{
    public function testFilterDoesNothingForSubRequests()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $response = new Response('foo <esi:include src="" />');
        $listener = new EsiListener(new Esi());

        $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
        $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
        $dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
    }

    public function testFilterWhenThereIsSomeEsiIncludes()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $response = new Response('foo <esi:include src="" />');
        $listener = new EsiListener(new Esi());

        $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
        $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
        $dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('content="ESI/1.0"', $event->getResponse()->headers->get('Surrogate-Control'));
    }

    public function testFilterWhenThereIsNoEsiIncludes()
    {
        $dispatcher = new EventDispatcher();
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $response = new Response('foo');
        $listener = new EsiListener(new Esi());

        $dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
        $event = new FilterResponseEvent($kernel, new Request(), HttpKernelInterface::MASTER_REQUEST, $response);
        $dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('', $event->getResponse()->headers->get('Surrogate-Control'));
    }
}
PKK1[p�66RHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\RouterListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\RequestContext;

class RouterListenerTest extends \PHPUnit_Framework_TestCase
{
    private $requestStack;

    public function setUp()
    {
        $this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false);
    }

    /**
     * @dataProvider getPortData
     */
    public function testPort($defaultHttpPort, $defaultHttpsPort, $uri, $expectedHttpPort, $expectedHttpsPort)
    {
        $urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')
                             ->disableOriginalConstructor()
                             ->getMock();
        $context = new RequestContext();
        $context->setHttpPort($defaultHttpPort);
        $context->setHttpsPort($defaultHttpsPort);
        $urlMatcher->expects($this->any())
                     ->method('getContext')
                     ->will($this->returnValue($context));

        $listener = new RouterListener($urlMatcher, null, null, $this->requestStack);
        $event = $this->createGetResponseEventForUri($uri);
        $listener->onKernelRequest($event);

        $this->assertEquals($expectedHttpPort, $context->getHttpPort());
        $this->assertEquals($expectedHttpsPort, $context->getHttpsPort());
        $this->assertEquals(0 === strpos($uri, 'https') ? 'https' : 'http', $context->getScheme());
    }

    public function getPortData()
    {
        return array(
            array(80, 443, 'http://localhost/', 80, 443),
            array(80, 443, 'http://localhost:90/', 90, 443),
            array(80, 443, 'https://localhost/', 80, 443),
            array(80, 443, 'https://localhost:90/', 80, 90),
        );
    }

    /**
     * @param string $uri
     *
     * @return GetResponseEvent
     */
    private function createGetResponseEventForUri($uri)
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $request = Request::create($uri);
        $request->attributes->set('_controller', null); // Prevents going in to routing process

        return new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testInvalidMatcher()
    {
        new RouterListener(new \stdClass(), null, null, $this->requestStack);
    }

    public function testRequestMatcher()
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $request = Request::create('http://localhost/');
        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);

        $requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
        $requestMatcher->expects($this->once())
                       ->method('matchRequest')
                       ->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
                       ->will($this->returnValue(array()));

        $listener = new RouterListener($requestMatcher, new RequestContext(), null, $this->requestStack);
        $listener->onKernelRequest($event);
    }

    public function testSubRequestWithDifferentMethod()
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $request = Request::create('http://localhost/', 'post');
        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);

        $requestMatcher = $this->getMock('Symfony\Component\Routing\Matcher\RequestMatcherInterface');
        $requestMatcher->expects($this->any())
                       ->method('matchRequest')
                       ->with($this->isInstanceOf('Symfony\Component\HttpFoundation\Request'))
                       ->will($this->returnValue(array()));

        $context = new RequestContext();
        $requestMatcher->expects($this->any())
                       ->method('getContext')
                       ->will($this->returnValue($context));

        $listener = new RouterListener($requestMatcher, new RequestContext(), null, $this->requestStack);
        $listener->onKernelRequest($event);

        // sub-request with another HTTP method
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $request = Request::create('http://localhost/', 'get');
        $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::SUB_REQUEST);

        $listener->onKernelRequest($event);

        $this->assertEquals('GET', $context->getMethod());
    }
}
PKK1[���uuWHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

/**
 * SessionListenerTest.
 *
 * Tests SessionListener.
 *
 * @author Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class TestSessionListenerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var TestSessionListener
     */
    private $listener;

    /**
     * @var SessionInterface
     */
    private $session;

    protected function setUp()
    {
        $this->listener = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\EventListener\TestSessionListener');
        $this->session  = $this->getSession();
    }

    public function testShouldSaveMasterRequestSession()
    {
        $this->sessionHasBeenStarted();
        $this->sessionMustBeSaved();

        $this->filterResponse(new Request());
    }

    public function testShouldNotSaveSubRequestSession()
    {
        $this->sessionMustNotBeSaved();

        $this->filterResponse(new Request(), HttpKernelInterface::SUB_REQUEST);
    }

    public function testDoesNotDeleteCookieIfUsingSessionLifetime()
    {
        $this->sessionHasBeenStarted();

        $params = session_get_cookie_params();
        session_set_cookie_params(0, $params['path'], $params['domain'], $params['secure'], $params['httponly']);

        $response = $this->filterResponse(new Request(), HttpKernelInterface::MASTER_REQUEST);
        $cookies = $response->headers->getCookies();

        $this->assertEquals(0, reset($cookies)->getExpiresTime());
    }

    public function testUnstartedSessionIsNotSave()
    {
        $this->sessionHasNotBeenStarted();
        $this->sessionMustNotBeSaved();

        $this->filterResponse(new Request());
    }

    private function filterResponse(Request $request, $type = HttpKernelInterface::MASTER_REQUEST)
    {
        $request->setSession($this->session);
        $response = new Response();
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $event = new FilterResponseEvent($kernel, $request, $type, $response);

        $this->listener->onKernelResponse($event);

        $this->assertSame($response, $event->getResponse());

        return $response;
    }

    private function sessionMustNotBeSaved()
    {
        $this->session->expects($this->never())
            ->method('save');
    }

    private function sessionMustBeSaved()
    {
        $this->session->expects($this->once())
            ->method('save');
    }

    private function sessionHasBeenStarted()
    {
        $this->session->expects($this->once())
            ->method('isStarted')
            ->will($this->returnValue(true));
    }

    private function sessionHasNotBeenStarted()
    {
        $this->session->expects($this->once())
            ->method('isStarted')
            ->will($this->returnValue(false));
    }

    private function getSession()
    {
        $mock = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')
            ->disableOriginalConstructor()
            ->getMock();

        // set return value for getName()
        $mock->expects($this->any())->method('getName')->will($this->returnValue('MOCKSESSID'));

        return $mock;
    }
}
PKK1[�,ph
h
THttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpKernel\EventListener\ResponseListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ResponseListenerTest extends \PHPUnit_Framework_TestCase
{
    private $dispatcher;

    private $kernel;

    protected function setUp()
    {
        $this->dispatcher = new EventDispatcher();
        $listener = new ResponseListener('UTF-8');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));

        $this->kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');

    }

    protected function tearDown()
    {
        $this->dispatcher = null;
        $this->kernel = null;
    }

    public function testFilterDoesNothingForSubRequests()
    {
        $response = new Response('foo');

        $event = new FilterResponseEvent($this->kernel, new Request(), HttpKernelInterface::SUB_REQUEST, $response);
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('', $event->getResponse()->headers->get('content-type'));
    }

    public function testFilterSetsNonDefaultCharsetIfNotOverridden()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);

        $response = new Response('foo');

        $event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('ISO-8859-15', $response->getCharset());
    }

    public function testFilterDoesNothingIfCharsetIsOverridden()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);

        $response = new Response('foo');
        $response->setCharset('ISO-8859-1');

        $event = new FilterResponseEvent($this->kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $response);
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('ISO-8859-1', $response->getCharset());
    }

    public function testFiltersSetsNonDefaultCharsetIfNotOverriddenOnNonTextContentType()
    {
        $listener = new ResponseListener('ISO-8859-15');
        $this->dispatcher->addListener(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'), 1);

        $response = new Response('foo');
        $request = Request::create('/');
        $request->setRequestFormat('application/json');

        $event = new FilterResponseEvent($this->kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response);
        $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);

        $this->assertEquals('ISO-8859-15', $response->getCharset());
    }
}
PKK1[K�(^��RHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\EventListener;

use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\EventListener\LocaleListener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class LocaleListenerTest extends \PHPUnit_Framework_TestCase
{
    private $requestStack;

    protected function setUp()
    {
        $this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array(), array(), '', false);
    }

    public function testDefaultLocaleWithoutSession()
    {
        $listener = new LocaleListener('fr', null, $this->requestStack);
        $event = $this->getEvent($request = Request::create('/'));

        $listener->onKernelRequest($event);
        $this->assertEquals('fr', $request->getLocale());
    }

    public function testLocaleFromRequestAttribute()
    {
        $request = Request::create('/');
        session_name('foo');
        $request->cookies->set('foo', 'value');

        $request->attributes->set('_locale', 'es');
        $listener = new LocaleListener('fr', null, $this->requestStack);
        $event = $this->getEvent($request);

        $listener->onKernelRequest($event);
        $this->assertEquals('es', $request->getLocale());
    }

    public function testLocaleSetForRoutingContext()
    {
        // the request context is updated
        $context = $this->getMock('Symfony\Component\Routing\RequestContext');
        $context->expects($this->once())->method('setParameter')->with('_locale', 'es');

        $router = $this->getMock('Symfony\Component\Routing\Router', array('getContext'), array(), '', false);
        $router->expects($this->once())->method('getContext')->will($this->returnValue($context));

        $request = Request::create('/');

        $request->attributes->set('_locale', 'es');
        $listener = new LocaleListener('fr', $router, $this->requestStack);
        $listener->onKernelRequest($this->getEvent($request));
    }

    public function testRouterResetWithParentRequestOnKernelFinishRequest()
    {
        if (!class_exists('Symfony\Component\Routing\Router')) {
            $this->markTestSkipped('The "Routing" component is not available');
        }

        // the request context is updated
        $context = $this->getMock('Symfony\Component\Routing\RequestContext');
        $context->expects($this->once())->method('setParameter')->with('_locale', 'es');

        $router = $this->getMock('Symfony\Component\Routing\Router', array('getContext'), array(), '', false);
        $router->expects($this->once())->method('getContext')->will($this->returnValue($context));

        $parentRequest = Request::create('/');
        $parentRequest->setLocale('es');

        $this->requestStack->expects($this->once())->method('getParentRequest')->will($this->returnValue($parentRequest));

        $event = $this->getMock('Symfony\Component\HttpKernel\Event\FinishRequestEvent', array(), array(), '', false);

        $listener = new LocaleListener('fr', $router, $this->requestStack);
        $listener->onKernelFinishRequest($event);
    }

    public function testRequestLocaleIsNotOverridden()
    {
        $request = Request::create('/');
        $request->setLocale('de');
        $listener = new LocaleListener('fr', null, $this->requestStack);
        $event = $this->getEvent($request);

        $listener->onKernelRequest($event);
        $this->assertEquals('de', $request->getLocale());
    }

    private function getEvent(Request $request)
    {
        return new GetResponseEvent($this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface'), $request, HttpKernelInterface::MASTER_REQUEST);
    }
}
PKK1[�o�M��WHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\HIncludeFragmentRenderer;
use Symfony\Component\HttpKernel\UriSigner;
use Symfony\Component\HttpFoundation\Request;

class HIncludeFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \LogicException
     */
    public function testRenderExceptionWhenControllerAndNoSigner()
    {
        $strategy = new HIncludeFragmentRenderer();
        $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'));
    }

    public function testRenderWithControllerAndSigner()
    {
        $strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));

        $this->assertEquals('<hx:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller&amp;_hash=BP%2BOzCD5MRUI%2BHJpgPDOmoju00FnzLhP3TGcSHbbBLs%3D"></hx:include>', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
    }

    public function testRenderWithUri()
    {
        $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());

        $strategy = new HIncludeFragmentRenderer(null, new UriSigner('foo'));
        $this->assertEquals('<hx:include src="/foo"></hx:include>', $strategy->render('/foo', Request::create('/'))->getContent());
    }

    public function testRenderWithDefault()
    {
        // only default
        $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());

        // only global default
        $strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
        $this->assertEquals('<hx:include src="/foo">global_default</hx:include>', $strategy->render('/foo', Request::create('/'), array())->getContent());

        // global default and default
        $strategy = new HIncludeFragmentRenderer(null, null, 'global_default');
        $this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
    }

    public function testRenderWithAttributesOptions()
    {
        // with id
        $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar'))->getContent());

        // with attributes
        $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());

        // with id & attributes
        $strategy = new HIncludeFragmentRenderer();
        $this->assertEquals('<hx:include src="/foo" p1="v1" p2="v2" id="bar">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default', 'id' => 'bar', 'attributes' => array('p1' => 'v1', 'p2' => 'v2')))->getContent());
    }

    public function testRenderWithDefaultText()
    {
        $engine = $this->getMock('Symfony\\Component\\Templating\\EngineInterface');
        $engine->expects($this->once())
            ->method('exists')
            ->with('default')
            ->will($this->throwException(new \InvalidArgumentException()));

        // only default
        $strategy = new HIncludeFragmentRenderer($engine);
        $this->assertEquals('<hx:include src="/foo">default</hx:include>', $strategy->render('/foo', Request::create('/'), array('default' => 'default'))->getContent());
    }
}
PKK1[�
��((WHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Controller\ControllerReference;

class RoutableFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getGenerateFragmentUriData
     */
    public function testGenerateFragmentUri($uri, $controller)
    {
        $this->assertEquals($uri, $this->callGenerateFragmentUriMethod($controller, Request::create('/')));
    }

    /**
     * @dataProvider getGenerateFragmentUriData
     */
    public function testGenerateAbsoluteFragmentUri($uri, $controller)
    {
        $this->assertEquals('http://localhost'.$uri, $this->callGenerateFragmentUriMethod($controller, Request::create('/'), true));
    }

    public function getGenerateFragmentUriData()
    {
        return array(
            array('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array())),
            array('/_fragment?_path=_format%3Dxml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('_format' => 'xml'), array())),
            array('/_fragment?_path=foo%3Dfoo%26_format%3Djson%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo', '_format' => 'json'), array())),
            array('/_fragment?bar=bar&_path=foo%3Dfoo%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => 'foo'), array('bar' => 'bar'))),
            array('/_fragment?foo=foo&_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array(), array('foo' => 'foo'))),
            array('/_fragment?_path=foo%255B0%255D%3Dfoo%26foo%255B1%255D%3Dbar%26_format%3Dhtml%26_locale%3Den%26_controller%3Dcontroller', new ControllerReference('controller', array('foo' => array('foo', 'bar')), array())),
        );
    }

    public function testGenerateFragmentUriWithARequest()
    {
        $request = Request::create('/');
        $request->attributes->set('_format', 'json');
        $request->setLocale('fr');
        $controller = new ControllerReference('controller', array(), array());

        $this->assertEquals('/_fragment?_path=_format%3Djson%26_locale%3Dfr%26_controller%3Dcontroller', $this->callGenerateFragmentUriMethod($controller, $request));
    }

    /**
     * @expectedException LogicException
     * @dataProvider      getGenerateFragmentUriDataWithNonScalar
     */
    public function testGenerateFragmentUriWithNonScalar($controller)
    {
        $this->callGenerateFragmentUriMethod($controller, Request::create('/'));
    }

    public function getGenerateFragmentUriDataWithNonScalar()
    {
        return array(
            array(new ControllerReference('controller', array('foo' => new Foo(), 'bar' => 'bar'), array())),
            array(new ControllerReference('controller', array('foo' => array('foo' => 'foo'), 'bar' => array('bar' => new Foo())), array())),
        );
    }

    private function callGenerateFragmentUriMethod(ControllerReference $reference, Request $request, $absolute = false)
    {
        $renderer = $this->getMockForAbstractClass('Symfony\Component\HttpKernel\Fragment\RoutableFragmentRenderer');
        $r = new \ReflectionObject($renderer);
        $m = $r->getMethod('generateFragmentUri');
        $m->setAccessible(true);

        return $m->invoke($renderer, $reference, $request, $absolute);
    }
}

class Foo
{
    public $foo;

    public function getFoo()
    {
        return $this->foo;
    }
}
PKK1[�v��UHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\EventDispatcher\EventDispatcher;

class InlineFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
    public function testRender()
    {
        $strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));

        $this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
    }

    public function testRenderWithControllerReference()
    {
        $strategy = new InlineFragmentRenderer($this->getKernel($this->returnValue(new Response('foo'))));

        $this->assertEquals('foo', $strategy->render(new ControllerReference('main_controller', array(), array()), Request::create('/'))->getContent());
    }

    public function testRenderWithObjectsAsAttributes()
    {
        $object = new \stdClass();

        $subRequest = Request::create('/_fragment?_path=_format%3Dhtml%26_locale%3Den%26_controller%3Dmain_controller');
        $subRequest->attributes->replace(array('object' => $object, '_format' => 'html', '_controller' => 'main_controller', '_locale' => 'en'));
        $subRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
        $subRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($subRequest));

        $strategy->render(new ControllerReference('main_controller', array('object' => $object), array()), Request::create('/'));
    }

    public function testRenderWithObjectsAsAttributesPassedAsObjectsInTheController()
    {
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolver', array('getController'));
        $resolver
            ->expects($this->once())
            ->method('getController')
            ->will($this->returnValue(function (\stdClass $object, Bar $object1) {
                return new Response($object1->getBar());
            }))
        ;

        $kernel = new HttpKernel(new EventDispatcher(), $resolver);
        $renderer = new InlineFragmentRenderer($kernel);

        $response = $renderer->render(new ControllerReference('main_controller', array('object' => new \stdClass(), 'object1' => new Bar()), array()), Request::create('/'));
        $this->assertEquals('bar', $response->getContent());
    }

    public function testRenderWithTrustedHeaderDisabled()
    {
        $trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);

        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest(Request::create('/')));
        $strategy->render('/', Request::create('/'));

        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testRenderExceptionNoIgnoreErrors()
    {
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $dispatcher->expects($this->never())->method('dispatch');

        $strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);

        $this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
    }

    public function testRenderExceptionIgnoreErrors()
    {
        $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
        $dispatcher->expects($this->once())->method('dispatch')->with(KernelEvents::EXCEPTION);

        $strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo'))), $dispatcher);

        $this->assertEmpty($strategy->render('/', Request::create('/'), array('ignore_errors' => true))->getContent());
    }

    public function testRenderExceptionIgnoreErrorsWithAlt()
    {
        $strategy = new InlineFragmentRenderer($this->getKernel($this->onConsecutiveCalls(
            $this->throwException(new \RuntimeException('foo')),
            $this->returnValue(new Response('bar'))
        )));

        $this->assertEquals('bar', $strategy->render('/', Request::create('/'), array('ignore_errors' => true, 'alt' => '/foo'))->getContent());
    }

    private function getKernel($returnValue)
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $kernel
            ->expects($this->any())
            ->method('handle')
            ->will($returnValue)
        ;

        return $kernel;
    }

    /**
     * Creates a Kernel expecting a request equals to $request
     * Allows delta in comparison in case REQUEST_TIME changed by 1 second
     */
    private function getKernelExpectingRequest(Request $request)
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\HttpKernelInterface');
        $kernel
            ->expects($this->any())
            ->method('handle')
            ->with($this->equalTo($request, 1))
        ;

        return $kernel;
    }

    public function testExceptionInSubRequestsDoesNotMangleOutputBuffers()
    {
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $resolver
            ->expects($this->once())
            ->method('getController')
            ->will($this->returnValue(function () {
                ob_start();
                echo 'bar';
                throw new \RuntimeException();
            }))
        ;
        $resolver
            ->expects($this->once())
            ->method('getArguments')
            ->will($this->returnValue(array()))
        ;

        $kernel = new HttpKernel(new EventDispatcher(), $resolver);
        $renderer = new InlineFragmentRenderer($kernel);

        // simulate a main request with output buffering
        ob_start();
        echo 'Foo';

        // simulate a sub-request with output buffering and an exception
        $renderer->render('/', Request::create('/'), array('ignore_errors' => true));

        $this->assertEquals('Foo', ob_get_clean());
    }

    public function testESIHeaderIsKeptInSubrequest()
    {
        $expectedSubRequest = Request::create('/');
        $expectedSubRequest->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');

        if (Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP)) {
            $expectedSubRequest->headers->set('x-forwarded-for', array('127.0.0.1'));
            $expectedSubRequest->server->set('HTTP_X_FORWARDED_FOR', '127.0.0.1');
        }

        $strategy = new InlineFragmentRenderer($this->getKernelExpectingRequest($expectedSubRequest));

        $request = Request::create('/');
        $request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
        $strategy->render('/', $request);
    }

    public function testESIHeaderIsKeptInSubrequestWithTrustedHeaderDisabled()
    {
        $trustedHeaderName = Request::getTrustedHeaderName(Request::HEADER_CLIENT_IP);
        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, '');

        $this->testESIHeaderIsKeptInSubrequest();

        Request::setTrustedHeaderName(Request::HEADER_CLIENT_IP, $trustedHeaderName);
    }
}

class Bar
{
    public $bar = 'bar';

    public function getBar()
    {
        return $this->bar;
    }
}
PKK1[;����
�
NHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpKernel\Fragment\FragmentHandler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class FragmentHandlerTest extends \PHPUnit_Framework_TestCase
{
    private $requestStack;

    public function setUp()
    {
        $this->requestStack = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\RequestStack')
            ->disableOriginalConstructor()
            ->getMock()
        ;
        $this->requestStack
            ->expects($this->any())
            ->method('getCurrentRequest')
            ->will($this->returnValue(Request::create('/')))
        ;
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRenderWhenRendererDoesNotExist()
    {
        $handler = new FragmentHandler(array(), null, $this->requestStack);
        $handler->render('/', 'foo');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testRenderWithUnknownRenderer()
    {
        $handler = $this->getHandler($this->returnValue(new Response('foo')));

        $handler->render('/', 'bar');
    }

    /**
     * @expectedException \RuntimeException
     * @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404).
     */
    public function testDeliverWithUnsuccessfulResponse()
    {
        $handler = $this->getHandler($this->returnValue(new Response('foo', 404)));

        $handler->render('/', 'foo');
    }

    public function testRender()
    {
        $handler = $this->getHandler($this->returnValue(new Response('foo')), array('/', Request::create('/'), array('foo' => 'foo', 'ignore_errors' => true)));

        $this->assertEquals('foo', $handler->render('/', 'foo', array('foo' => 'foo')));
    }

    protected function getHandler($returnValue, $arguments = array())
    {
        $renderer = $this->getMock('Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface');
        $renderer
            ->expects($this->any())
            ->method('getName')
            ->will($this->returnValue('foo'))
        ;
        $e = $renderer
            ->expects($this->any())
            ->method('render')
            ->will($returnValue)
        ;

        if ($arguments) {
            call_user_func_array(array($e, 'with'), $arguments);
        }

        $handler = new FragmentHandler(array(), null, $this->requestStack);
        $handler->addRenderer($renderer);

        return $handler;
    }
}
PKK1[�҃��	�	RHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Fragment;

use Symfony\Component\HttpKernel\Controller\ControllerReference;
use Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;

class EsiFragmentRendererTest extends \PHPUnit_Framework_TestCase
{
    public function testRenderFallbackToInlineStrategyIfNoRequest()
    {
        $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true));
        $strategy->render('/', Request::create('/'));
    }

    public function testRenderFallbackToInlineStrategyIfEsiNotSupported()
    {
        $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy(true));
        $strategy->render('/', Request::create('/'));
    }

    public function testRender()
    {
        $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy());

        $request = Request::create('/');
        $request->setLocale('fr');
        $request->headers->set('Surrogate-Capability', 'ESI/1.0');

        $this->assertEquals('<esi:include src="/" />', $strategy->render('/', $request)->getContent());
        $this->assertEquals("<esi:comment text=\"This is a comment\" />\n<esi:include src=\"/\" />", $strategy->render('/', $request, array('comment' => 'This is a comment'))->getContent());
        $this->assertEquals('<esi:include src="/" alt="foo" />', $strategy->render('/', $request, array('alt' => 'foo'))->getContent());
        $this->assertEquals('<esi:include src="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dmain_controller" alt="/_fragment?_path=_format%3Dhtml%26_locale%3Dfr%26_controller%3Dalt_controller" />', $strategy->render(new ControllerReference('main_controller', array(), array()), $request, array('alt' => new ControllerReference('alt_controller', array(), array())))->getContent());
    }

    private function getInlineStrategy($called = false)
    {
        $inline = $this->getMockBuilder('Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer')->disableOriginalConstructor()->getMock();

        if ($called) {
            $inline->expects($this->once())->method('render');
        }

        return $inline;
    }
}
PKK1[p����8HttpKernel/Symfony/Component/HttpKernel/Tests/Logger.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Psr\Log\LoggerInterface;

class Logger implements LoggerInterface
{
    protected $logs;

    public function __construct()
    {
        $this->clear();
    }

    public function getLogs($level = false)
    {
        return false === $level ? $this->logs : $this->logs[$level];
    }

    public function clear()
    {
        $this->logs = array(
            'emergency' => array(),
            'alert' => array(),
            'critical' => array(),
            'error' => array(),
            'warning' => array(),
            'notice' => array(),
            'info' => array(),
            'debug' => array(),
        );
    }

    public function log($level, $message, array $context = array())
    {
        $this->logs[$level][] = $message;
    }

    public function emergency($message, array $context = array())
    {
        $this->log('emergency', $message, $context);
    }

    public function alert($message, array $context = array())
    {
        $this->log('alert', $message, $context);
    }

    public function critical($message, array $context = array())
    {
        $this->log('critical', $message, $context);
    }

    public function error($message, array $context = array())
    {
        $this->log('error', $message, $context);
    }

    public function warning($message, array $context = array())
    {
        $this->log('warning', $message, $context);
    }

    public function notice($message, array $context = array())
    {
        $this->log('notice', $message, $context);
    }

    public function info($message, array $context = array())
    {
        $this->log('info', $message, $context);
    }

    public function debug($message, array $context = array())
    {
        $this->log('debug', $message, $context);
    }

    /**
     * @deprecated
     */
    public function emerg($message, array $context = array())
    {
        trigger_error('Use emergency() which is PSR-3 compatible', E_USER_DEPRECATED);

        $this->log('emergency', $message, $context);
    }

    /**
     * @deprecated
     */
    public function crit($message, array $context = array())
    {
        trigger_error('Use critical() which is PSR-3 compatible', E_USER_DEPRECATED);

        $this->log('critical', $message, $context);
    }

    /**
     * @deprecated
     */
    public function err($message, array $context = array())
    {
        trigger_error('Use error() which is PSR-3 compatible', E_USER_DEPRECATED);

        $this->log('error', $message, $context);
    }

    /**
     * @deprecated
     */
    public function warn($message, array $context = array())
    {
        trigger_error('Use warning() which is PSR-3 compatible', E_USER_DEPRECATED);

        $this->log('warning', $message, $context);
    }
}
PKK1[��m*����IHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\StoreInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class HttpCacheTest extends HttpCacheTestCase
{
    public function testTerminateDelegatesTerminationOnlyForTerminableInterface()
    {
        $storeMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpCache\\StoreInterface')
            ->disableOriginalConstructor()
            ->getMock();

        // does not implement TerminableInterface
        $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpKernelInterface')
            ->disableOriginalConstructor()
            ->getMock();

        $kernelMock->expects($this->never())
            ->method('terminate');

        $kernel = new HttpCache($kernelMock, $storeMock);
        $kernel->terminate(Request::create('/'), new Response());

        // implements TerminableInterface
        $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel')
            ->disableOriginalConstructor()
            ->setMethods(array('terminate', 'registerBundles', 'registerContainerConfiguration'))
            ->getMock();

        $kernelMock->expects($this->once())
            ->method('terminate');

        $kernel = new HttpCache($kernelMock, $storeMock);
        $kernel->terminate(Request::create('/'), new Response());
    }

    public function testPassesOnNonGetHeadRequests()
    {
        $this->setNextResponse(200);
        $this->request('POST', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertResponseOk();
        $this->assertTraceContains('pass');
        $this->assertFalse($this->response->headers->has('Age'));
    }

    public function testInvalidatesOnPostPutDeleteRequests()
    {
        foreach (array('post', 'put', 'delete') as $method) {
            $this->setNextResponse(200);
            $this->request($method, '/');

            $this->assertHttpKernelIsCalled();
            $this->assertResponseOk();
            $this->assertTraceContains('invalidate');
            $this->assertTraceContains('pass');
        }
    }

    public function testDoesNotCacheWithAuthorizationRequestHeaderAndNonPublicResponse()
    {
        $this->setNextResponse(200, array('ETag' => '"Foo"'));
        $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz'));

        $this->assertHttpKernelIsCalled();
        $this->assertResponseOk();
        $this->assertEquals('private', $this->response->headers->get('Cache-Control'));

        $this->assertTraceContains('miss');
        $this->assertTraceNotContains('store');
        $this->assertFalse($this->response->headers->has('Age'));
    }

    public function testDoesCacheWithAuthorizationRequestHeaderAndPublicResponse()
    {
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"Foo"'));
        $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz'));

        $this->assertHttpKernelIsCalled();
        $this->assertResponseOk();
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertTrue($this->response->headers->has('Age'));
        $this->assertEquals('public', $this->response->headers->get('Cache-Control'));
    }

    public function testDoesNotCacheWithCookieHeaderAndNonPublicResponse()
    {
        $this->setNextResponse(200, array('ETag' => '"Foo"'));
        $this->request('GET', '/', array(), array('foo' => 'bar'));

        $this->assertHttpKernelIsCalled();
        $this->assertResponseOk();
        $this->assertEquals('private', $this->response->headers->get('Cache-Control'));
        $this->assertTraceContains('miss');
        $this->assertTraceNotContains('store');
        $this->assertFalse($this->response->headers->has('Age'));
    }

    public function testDoesNotCacheRequestsWithACookieHeader()
    {
        $this->setNextResponse(200);
        $this->request('GET', '/', array(), array('foo' => 'bar'));

        $this->assertHttpKernelIsCalled();
        $this->assertResponseOk();
        $this->assertEquals('private', $this->response->headers->get('Cache-Control'));
        $this->assertTraceContains('miss');
        $this->assertTraceNotContains('store');
        $this->assertFalse($this->response->headers->has('Age'));
    }

    public function testRespondsWith304WhenIfModifiedSinceMatchesLastModified()
    {
        $time = new \DateTime();

        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822), 'Content-Type' => 'text/plain'), 'Hello World');
        $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));

        $this->assertHttpKernelIsCalled();
        $this->assertEquals(304, $this->response->getStatusCode());
        $this->assertEquals('', $this->response->headers->get('Content-Type'));
        $this->assertEmpty($this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
    }

    public function testRespondsWith304WhenIfNoneMatchMatchesETag()
    {
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '12345', 'Content-Type' => 'text/plain'), 'Hello World');
        $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345'));

        $this->assertHttpKernelIsCalled();
        $this->assertEquals(304, $this->response->getStatusCode());
        $this->assertEquals('', $this->response->headers->get('Content-Type'));
        $this->assertTrue($this->response->headers->has('ETag'));
        $this->assertEmpty($this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
    }

    public function testRespondsWith304OnlyIfIfNoneMatchAndIfModifiedSinceBothMatch()
    {
        $time = new \DateTime();

        $this->setNextResponse(200, array(), '', function ($request, $response) use ($time) {
            $response->setStatusCode(200);
            $response->headers->set('ETag', '12345');
            $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
            $response->headers->set('Content-Type', 'text/plain');
            $response->setContent('Hello World');
        });

        // only ETag matches
        $t = \DateTime::createFromFormat('U', time() - 3600);
        $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(DATE_RFC2822)));
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());

        // only Last-Modified matches
        $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());

        // Both matches
        $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(304, $this->response->getStatusCode());
    }

    public function testValidatesPrivateResponsesCachedOnTheClient()
    {
        $this->setNextResponse(200, array(), '', function ($request, $response) {
            $etags = preg_split('/\s*,\s*/', $request->headers->get('IF_NONE_MATCH'));
            if ($request->cookies->has('authenticated')) {
                $response->headers->set('Cache-Control', 'private, no-store');
                $response->setETag('"private tag"');
                if (in_array('"private tag"', $etags)) {
                    $response->setStatusCode(304);
                } else {
                    $response->setStatusCode(200);
                    $response->headers->set('Content-Type', 'text/plain');
                    $response->setContent('private data');
                }
            } else {
                $response->headers->set('Cache-Control', 'public');
                $response->setETag('"public tag"');
                if (in_array('"public tag"', $etags)) {
                    $response->setStatusCode(304);
                } else {
                    $response->setStatusCode(200);
                    $response->headers->set('Content-Type', 'text/plain');
                    $response->setContent('public data');
                }
            }
        });

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('"public tag"', $this->response->headers->get('ETag'));
        $this->assertEquals('public data', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        $this->request('GET', '/', array(), array('authenticated' => ''));
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('"private tag"', $this->response->headers->get('ETag'));
        $this->assertEquals('private data', $this->response->getContent());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('invalid');
        $this->assertTraceNotContains('store');
    }

    public function testStoresResponsesWhenNoCacheRequestDirectivePresent()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);

        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));
        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));

        $this->assertHttpKernelIsCalled();
        $this->assertTraceContains('store');
        $this->assertTrue($this->response->headers->has('Age'));
    }

    public function testReloadsResponsesWhenCacheHitsButNoCacheRequestDirectivePresentWhenAllowReloadIsSetTrue()
    {
        $count = 0;

        $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) {
            ++$count;
            $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
        });

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('store');

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('fresh');

        $this->cacheConfig['allow_reload'] = true;
        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Goodbye World', $this->response->getContent());
        $this->assertTraceContains('reload');
        $this->assertTraceContains('store');
    }

    public function testDoesNotReloadResponsesWhenAllowReloadIsSetFalseDefault()
    {
        $count = 0;

        $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) {
            ++$count;
            $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
        });

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('store');

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('fresh');

        $this->cacheConfig['allow_reload'] = false;
        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceNotContains('reload');

        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceNotContains('reload');
    }

    public function testRevalidatesFreshCacheEntryWhenMaxAgeRequestDirectiveIsExceededWhenAllowRevalidateOptionIsSetTrue()
    {
        $count = 0;

        $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) {
            ++$count;
            $response->headers->set('Cache-Control', 'public, max-age=10000');
            $response->setETag($count);
            $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
        });

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('store');

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('fresh');

        $this->cacheConfig['allow_revalidate'] = true;
        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Goodbye World', $this->response->getContent());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('invalid');
        $this->assertTraceContains('store');
    }

    public function testDoesNotRevalidateFreshCacheEntryWhenEnableRevalidateOptionIsSetFalseDefault()
    {
        $count = 0;

        $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) {
            ++$count;
            $response->headers->set('Cache-Control', 'public, max-age=10000');
            $response->setETag($count);
            $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World');
        });

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('store');

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('fresh');

        $this->cacheConfig['allow_revalidate'] = false;
        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceNotContains('stale');
        $this->assertTraceNotContains('invalid');
        $this->assertTraceContains('fresh');

        $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceNotContains('stale');
        $this->assertTraceNotContains('invalid');
        $this->assertTraceContains('fresh');
    }

    public function testFetchesResponseFromBackendWhenCacheMisses()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceContains('miss');
        $this->assertTrue($this->response->headers->has('Age'));
    }

    public function testDoesNotCacheSomeStatusCodeResponses()
    {
        foreach (array_merge(range(201, 202), range(204, 206), range(303, 305), range(400, 403), range(405, 409), range(411, 417), range(500, 505)) as $code) {
            $time = \DateTime::createFromFormat('U', time() + 5);
            $this->setNextResponse($code, array('Expires' => $time->format(DATE_RFC2822)));

            $this->request('GET', '/');
            $this->assertEquals($code, $this->response->getStatusCode());
            $this->assertTraceNotContains('store');
            $this->assertFalse($this->response->headers->has('Age'));
        }
    }

    public function testDoesNotCacheResponsesWithExplicitNoStoreDirective()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'no-store'));

        $this->request('GET', '/');
        $this->assertTraceNotContains('store');
        $this->assertFalse($this->response->headers->has('Age'));
    }

    public function testDoesNotCacheResponsesWithoutFreshnessInformationOrAValidator()
    {
        $this->setNextResponse();

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceNotContains('store');
    }

    public function testCachesResponsesWithExplicitNoCacheDirective()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, no-cache'));

        $this->request('GET', '/');
        $this->assertTraceContains('store');
        $this->assertTrue($this->response->headers->has('Age'));
    }

    public function testCachesResponsesWithAnExpirationHeader()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        $values = $this->getMetaStorageValues();
        $this->assertCount(1, $values);
    }

    public function testCachesResponsesWithAMaxAgeDirective()
    {
        $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=5'));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        $values = $this->getMetaStorageValues();
        $this->assertCount(1, $values);
    }

    public function testCachesResponsesWithASMaxAgeDirective()
    {
        $this->setNextResponse(200, array('Cache-Control' => 's-maxage=5'));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        $values = $this->getMetaStorageValues();
        $this->assertCount(1, $values);
    }

    public function testCachesResponsesWithALastModifiedValidatorButNoFreshnessInformation()
    {
        $time = \DateTime::createFromFormat('U', time());
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822)));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
    }

    public function testCachesResponsesWithAnETagValidatorButNoFreshnessInformation()
    {
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"123456"'));

        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
    }

    public function testHitsCachedResponsesWithExpiresHeader()
    {
        $time1 = \DateTime::createFromFormat('U', time() - 5);
        $time2 = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Date' => $time1->format(DATE_RFC2822), 'Expires' => $time2->format(DATE_RFC2822)));

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());

        $this->request('GET', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
        $this->assertTrue($this->response->headers->get('Age') > 0);
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testHitsCachedResponseWithMaxAgeDirective()
    {
        $time = \DateTime::createFromFormat('U', time() - 5);
        $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, max-age=10'));

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());

        $this->request('GET', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
        $this->assertTrue($this->response->headers->get('Age') > 0);
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testHitsCachedResponseWithSMaxAgeDirective()
    {
        $time = \DateTime::createFromFormat('U', time() - 5);
        $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0'));

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());

        $this->request('GET', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2);
        $this->assertTrue($this->response->headers->get('Age') > 0);
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformation()
    {
        $this->setNextResponse();

        $this->cacheConfig['default_ttl'] = 10;
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control'));

        $this->cacheConfig['default_ttl'] = 10;
        $this->request('GET', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirective()
    {
        $this->setNextResponse(200, array('Cache-Control' => 'must-revalidate'));

        $this->cacheConfig['default_ttl'] = 10;
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceContains('miss');
        $this->assertTraceNotContains('store');
        $this->assertNotRegExp('/s-maxage/', $this->response->headers->get('Cache-Control'));
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent()
    {
        $time = \DateTime::createFromFormat('U', time() + 5);
        $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822)));

        // build initial request
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Date'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertNotNull($this->response->headers->get('Age'));
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());

        # go in and play around with the cached metadata directly ...
        $values = $this->getMetaStorageValues();
        $this->assertCount(1, $values);
        $tmp = unserialize($values[0]);
        $time = \DateTime::createFromFormat('U', time());
        $tmp[0][1]['expires'] = $time->format(DATE_RFC2822);
        $r = new \ReflectionObject($this->store);
        $m = $r->getMethod('save');
        $m->setAccessible(true);
        $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp));

        // build subsequent request; should be found but miss due to freshness
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTrue($this->response->headers->get('Age') <= 1);
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTraceContains('stale');
        $this->assertTraceNotContains('fresh');
        $this->assertTraceNotContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Hello World', $this->response->getContent());
    }

    public function testValidatesCachedResponsesWithLastModifiedAndNoFreshnessInformation()
    {
        $time = \DateTime::createFromFormat('U', time());
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) {
            $response->headers->set('Cache-Control', 'public');
            $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
            if ($time->format(DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) {
                $response->setStatusCode(304);
                $response->setContent('');
            }
        });

        // build initial request
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Last-Modified'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertTraceNotContains('stale');

        // build subsequent request; should be found but miss due to freshness
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('Last-Modified'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTrue($this->response->headers->get('Age') <= 1);
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('valid');
        $this->assertTraceContains('store');
        $this->assertTraceNotContains('miss');
    }

    public function testValidatesCachedResponsesWithETagAndNoFreshnessInformation()
    {
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
            $response->headers->set('Cache-Control', 'public');
            $response->headers->set('ETag', '"12345"');
            if ($response->getETag() == $request->headers->get('IF_NONE_MATCH')) {
                $response->setStatusCode(304);
                $response->setContent('');
            }
        });

        // build initial request
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('ETag'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        // build subsequent request; should be found but miss due to freshness
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertNotNull($this->response->headers->get('ETag'));
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $this->assertTrue($this->response->headers->get('Age') <= 1);
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('valid');
        $this->assertTraceContains('store');
        $this->assertTraceNotContains('miss');
    }

    public function testReplacesCachedResponsesWhenValidationResultsInNon304Response()
    {
        $time = \DateTime::createFromFormat('U', time());
        $count = 0;
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time, &$count) {
            $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
            $response->headers->set('Cache-Control', 'public');
            switch (++$count) {
                case 1:
                    $response->setContent('first response');
                    break;
                case 2:
                    $response->setContent('second response');
                    break;
                case 3:
                    $response->setContent('');
                    $response->setStatusCode(304);
                    break;
            }
        });

        // first request should fetch from backend and store in cache
        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('first response', $this->response->getContent());

        // second request is validated, is invalid, and replaces cached entry
        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('second response', $this->response->getContent());

        // third response is validated, valid, and returns cached entry
        $this->request('GET', '/');
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('second response', $this->response->getContent());

        $this->assertEquals(3, $count);
    }

    public function testPassesHeadRequestsThroughDirectlyOnPass()
    {
        $that = $this;
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that) {
            $response->setContent('');
            $response->setStatusCode(200);
            $that->assertEquals('HEAD', $request->getMethod());
        });

        $this->request('HEAD', '/', array('HTTP_EXPECT' => 'something ...'));
        $this->assertHttpKernelIsCalled();
        $this->assertEquals('', $this->response->getContent());
    }

    public function testUsesCacheToRespondToHeadRequestsWhenFresh()
    {
        $that = $this;
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that) {
            $response->headers->set('Cache-Control', 'public, max-age=10');
            $response->setContent('Hello World');
            $response->setStatusCode(200);
            $that->assertNotEquals('HEAD', $request->getMethod());
        });

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals('Hello World', $this->response->getContent());

        $this->request('HEAD', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('', $this->response->getContent());
        $this->assertEquals(strlen('Hello World'), $this->response->headers->get('Content-Length'));
    }

    public function testSendsNoContentWhenFresh()
    {
        $time = \DateTime::createFromFormat('U', time());
        $that = $this;
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($that, $time) {
            $response->headers->set('Cache-Control', 'public, max-age=10');
            $response->headers->set('Last-Modified', $time->format(DATE_RFC2822));
        });

        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals('Hello World', $this->response->getContent());

        $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822)));
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(304, $this->response->getStatusCode());
        $this->assertEquals('', $this->response->getContent());
    }

    public function testInvalidatesCachedResponsesOnPost()
    {
        $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) {
            if ('GET' == $request->getMethod()) {
                $response->setStatusCode(200);
                $response->headers->set('Cache-Control', 'public, max-age=500');
                $response->setContent('Hello World');
            } elseif ('POST' == $request->getMethod()) {
                $response->setStatusCode(303);
                $response->headers->set('Location', '/');
                $response->headers->remove('Cache-Control');
                $response->setContent('');
            }
        });

        // build initial request to enter into the cache
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        // make sure it is valid
        $this->request('GET', '/');
        $this->assertHttpKernelIsNotCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('fresh');

        // now POST to same URL
        $this->request('POST', '/helloworld');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals('/', $this->response->headers->get('Location'));
        $this->assertTraceContains('invalidate');
        $this->assertTraceContains('pass');
        $this->assertEquals('', $this->response->getContent());

        // now make sure it was actually invalidated
        $this->request('GET', '/');
        $this->assertHttpKernelIsCalled();
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Hello World', $this->response->getContent());
        $this->assertTraceContains('stale');
        $this->assertTraceContains('invalid');
        $this->assertTraceContains('store');
    }

    public function testServesFromCacheWhenHeadersMatch()
    {
        $count = 0;
        $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) {
            $response->headers->set('Vary', 'Accept User-Agent Foo');
            $response->headers->set('Cache-Control', 'public, max-age=10');
            $response->headers->set('X-Response-Count', ++$count);
            $response->setContent($request->headers->get('USER_AGENT'));
        });

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Bob/1.0', $this->response->getContent());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Bob/1.0', $this->response->getContent());
        $this->assertTraceContains('fresh');
        $this->assertTraceNotContains('store');
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
    }

    public function testStoresMultipleResponsesWhenHeadersDiffer()
    {
        $count = 0;
        $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) {
            $response->headers->set('Vary', 'Accept User-Agent Foo');
            $response->headers->set('Cache-Control', 'public, max-age=10');
            $response->headers->set('X-Response-Count', ++$count);
            $response->setContent($request->headers->get('USER_AGENT'));
        });

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertEquals('Bob/1.0', $this->response->getContent());
        $this->assertEquals(1, $this->response->headers->get('X-Response-Count'));

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0'));
        $this->assertEquals(200, $this->response->getStatusCode());
        $this->assertTraceContains('miss');
        $this->assertTraceContains('store');
        $this->assertEquals('Bob/2.0', $this->response->getContent());
        $this->assertEquals(2, $this->response->headers->get('X-Response-Count'));

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0'));
        $this->assertTraceContains('fresh');
        $this->assertEquals('Bob/1.0', $this->response->getContent());
        $this->assertEquals(1, $this->response->headers->get('X-Response-Count'));

        $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0'));
        $this->assertTraceContains('fresh');
        $this->assertEquals('Bob/2.0', $this->response->getContent());
        $this->assertEquals(2, $this->response->headers->get('X-Response-Count'));

        $this->request('GET', '/', array('HTTP_USER_AGENT' => 'Bob/2.0'));
        $this->assertTraceContains('miss');
        $this->assertEquals('Bob/2.0', $this->response->getContent());
        $this->assertEquals(3, $this->response->headers->get('X-Response-Count'));
    }

    public function testShouldCatchExceptions()
    {
        $this->catchExceptions();

        $this->setNextResponse();
        $this->request('GET', '/');

        $this->assertExceptionsAreCaught();
    }

    public function testShouldCatchExceptionsWhenReloadingAndNoCacheRequest()
    {
        $this->catchExceptions();

        $this->setNextResponse();
        $this->cacheConfig['allow_reload'] = true;
        $this->request('GET', '/', array(), array(), false, array('Pragma' => 'no-cache'));

        $this->assertExceptionsAreCaught();
    }

    public function testShouldNotCatchExceptions()
    {
        $this->catchExceptions(false);

        $this->setNextResponse();
        $this->request('GET', '/');

        $this->assertExceptionsAreNotCaught();
    }

    public function testEsiCacheSendsTheLowestTtl()
    {
        $responses = array(
            array(
                'status'  => 200,
                'body'    => '<esi:include src="/foo" /> <esi:include src="/bar" />',
                'headers' => array(
                    'Cache-Control'     => 's-maxage=300',
                    'Surrogate-Control' => 'content="ESI/1.0"',
                ),
            ),
            array(
                'status'  => 200,
                'body'    => 'Hello World!',
                'headers' => array('Cache-Control' => 's-maxage=300'),
            ),
            array(
                'status'  => 200,
                'body'    => 'My name is Bobby.',
                'headers' => array('Cache-Control' => 's-maxage=100'),
            ),
        );

        $this->setNextResponses($responses);

        $this->request('GET', '/', array(), array(), true);
        $this->assertEquals("Hello World! My name is Bobby.", $this->response->getContent());

        // check for 100 or 99 as the test can be executed after a second change
        $this->assertTrue(in_array($this->response->getTtl(), array(99, 100)));
    }

    public function testEsiCacheForceValidation()
    {
        $responses = array(
            array(
                'status'  => 200,
                'body'    => '<esi:include src="/foo" /> <esi:include src="/bar" />',
                'headers' => array(
                    'Cache-Control'     => 's-maxage=300',
                    'Surrogate-Control' => 'content="ESI/1.0"',
                ),
            ),
            array(
                'status'  => 200,
                'body'    => 'Hello World!',
                'headers' => array('ETag' => 'foobar'),
            ),
            array(
                'status'  => 200,
                'body'    => 'My name is Bobby.',
                'headers' => array('Cache-Control' => 's-maxage=100'),
            ),
        );

        $this->setNextResponses($responses);

        $this->request('GET', '/', array(), array(), true);
        $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
        $this->assertNull($this->response->getTtl());
        $this->assertTrue($this->response->mustRevalidate());
        $this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
        $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
    }

    public function testEsiRecalculateContentLengthHeader()
    {
        $responses = array(
            array(
                'status'  => 200,
                'body'    => '<esi:include src="/foo" />',
                'headers' => array(
                    'Content-Length'    => 26,
                    'Cache-Control'     => 's-maxage=300',
                    'Surrogate-Control' => 'content="ESI/1.0"',
                ),
            ),
            array(
                'status'  => 200,
                'body'    => 'Hello World!',
                'headers' => array(),
            ),
        );

        $this->setNextResponses($responses);

        $this->request('GET', '/', array(), array(), true);
        $this->assertEquals('Hello World!', $this->response->getContent());
        $this->assertEquals(12, $this->response->headers->get('Content-Length'));
    }

    public function testClientIpIsAlwaysLocalhostForForwardedRequests()
    {
        $this->setNextResponse();
        $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1'));

        $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR'));
    }

    /**
     * @dataProvider getXForwardedForData
     */
    public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected)
    {
        $this->setNextResponse();
        $server = array('REMOTE_ADDR' => '10.0.0.1');
        if (false !== $xForwardedFor) {
            $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor;
        }
        $this->request('GET', '/', $server);

        $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
    }

    public function getXForwardedForData()
    {
        return array(
            array(false, '10.0.0.1'),
            array('10.0.0.2', '10.0.0.2, 10.0.0.1'),
            array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'),
        );
    }

    public function testXForwarderForHeaderForPassRequests()
    {
        $this->setNextResponse();
        $server = array('REMOTE_ADDR' => '10.0.0.1');
        $this->request('POST', '/', $server);

        $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For'));
    }

    public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses()
    {
        $time = new \DateTime;

        $responses = array(
            array(
                'status'  => 200,
                'body'    => '<esi:include src="/hey" />',
                'headers' => array(
                    'Surrogate-Control' => 'content="ESI/1.0"',
                    'ETag' => 'hey',
                    'Last-Modified' => $time->format(DATE_RFC2822),
                ),
            ),
            array(
                'status'  => 200,
                'body'    => 'Hey!',
                'headers' => array(),
            ),
        );

        $this->setNextResponses($responses);

        $this->request('GET', '/', array(), array(), true);
        $this->assertNull($this->response->getETag());
        $this->assertNull($this->response->getLastModified());
    }
}
PKK1[�t~		JHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/TestHttpKernel.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class TestHttpKernel extends HttpKernel implements ControllerResolverInterface
{
    protected $body;
    protected $status;
    protected $headers;
    protected $called = false;
    protected $customizer;
    protected $catch = false;
    protected $backendRequest;

    public function __construct($body, $status, $headers, \Closure $customizer = null)
    {
        $this->body = $body;
        $this->status = $status;
        $this->headers = $headers;
        $this->customizer = $customizer;

        parent::__construct(new EventDispatcher(), $this);
    }

    public function getBackendRequest()
    {
        return $this->backendRequest;
    }

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
    {
        $this->catch = $catch;
        $this->backendRequest = $request;

        return parent::handle($request, $type, $catch);
    }

    public function isCatchingExceptions()
    {
        return $this->catch;
    }

    public function getController(Request $request)
    {
        return array($this, 'callController');
    }

    public function getArguments(Request $request, $controller)
    {
        return array($request);
    }

    public function callController(Request $request)
    {
        $this->called = true;

        $response = new Response($this->body, $this->status, $this->headers);

        if (null !== $this->customizer) {
            call_user_func($this->customizer, $request, $response);
        }

        return $response;
    }

    public function hasBeenCalled()
    {
        return $this->called;
    }

    public function reset()
    {
        $this->called = false;
    }
}
PKK1[`��uNNCHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class EsiTest extends \PHPUnit_Framework_TestCase
{
    public function testHasSurrogateEsiCapability()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"');
        $this->assertTrue($esi->hasSurrogateEsiCapability($request));

        $request = Request::create('/');
        $request->headers->set('Surrogate-Capability', 'foobar');
        $this->assertFalse($esi->hasSurrogateEsiCapability($request));

        $request = Request::create('/');
        $this->assertFalse($esi->hasSurrogateEsiCapability($request));
    }

    public function testAddSurrogateEsiCapability()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $esi->addSurrogateEsiCapability($request);
        $this->assertEquals('symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));

        $esi->addSurrogateEsiCapability($request);
        $this->assertEquals('symfony2="ESI/1.0", symfony2="ESI/1.0"', $request->headers->get('Surrogate-Capability'));
    }

    public function testAddSurrogateControl()
    {
        $esi = new Esi();

        $response = new Response('foo <esi:include src="" />');
        $esi->addSurrogateControl($response);
        $this->assertEquals('content="ESI/1.0"', $response->headers->get('Surrogate-Control'));

        $response = new Response('foo');
        $esi->addSurrogateControl($response);
        $this->assertEquals('', $response->headers->get('Surrogate-Control'));
    }

    public function testNeedsEsiParsing()
    {
        $esi = new Esi();

        $response = new Response();
        $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
        $this->assertTrue($esi->needsEsiParsing($response));

        $response = new Response();
        $this->assertFalse($esi->needsEsiParsing($response));
    }

    public function testRenderIncludeTag()
    {
        $esi = new Esi();

        $this->assertEquals('<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true));
        $this->assertEquals('<esi:include src="/" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', false));
        $this->assertEquals('<esi:include src="/" onerror="continue" />', $esi->renderIncludeTag('/'));
        $this->assertEquals('<esi:comment text="some comment" />'."\n".'<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true, 'some comment'));
    }

    public function testProcessDoesNothingIfContentTypeIsNotHtml()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $response = new Response();
        $response->headers->set('Content-Type', 'text/plain');
        $esi->process($request, $response);

        $this->assertFalse($response->headers->has('x-body-eval'));
    }

    public function testProcess()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $response = new Response('foo <esi:comment text="some comment" /><esi:include src="..." alt="alt" onerror="continue" />');
        $esi->process($request, $response);

        $this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent());
        $this->assertEquals('ESI', $response->headers->get('x-body-eval'));

        $response = new Response('foo <esi:include src="..." />');
        $esi->process($request, $response);

        $this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());

        $response = new Response('foo <esi:include src="..."></esi:include>');
        $esi->process($request, $response);

        $this->assertEquals('foo <?php echo $this->esi->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent());
    }

    public function testProcessEscapesPhpTags()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $response = new Response('foo <?php die("foo"); ?><%= "lala" %>');
        $esi->process($request, $response);

        $this->assertEquals('foo <?php echo "<?"; ?>php die("foo"); ?><?php echo "<%"; ?>= "lala" %>', $response->getContent());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testProcessWhenNoSrcInAnEsi()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $response = new Response('foo <esi:include />');
        $esi->process($request, $response);
    }

    public function testProcessRemoveSurrogateControlHeader()
    {
        $esi = new Esi();

        $request = Request::create('/');
        $response = new Response('foo <esi:include src="..." />');
        $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
        $esi->process($request, $response);
        $this->assertEquals('ESI', $response->headers->get('x-body-eval'));

        $response->headers->set('Surrogate-Control', 'no-store, content="ESI/1.0"');
        $esi->process($request, $response);
        $this->assertEquals('ESI', $response->headers->get('x-body-eval'));
        $this->assertEquals('no-store', $response->headers->get('surrogate-control'));

        $response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store');
        $esi->process($request, $response);
        $this->assertEquals('ESI', $response->headers->get('x-body-eval'));
        $this->assertEquals('no-store', $response->headers->get('surrogate-control'));
    }

    public function testHandle()
    {
        $esi = new Esi();
        $cache = $this->getCache(Request::create('/'), new Response('foo'));
        $this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true));
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testHandleWhenResponseIsNot200()
    {
        $esi = new Esi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/'), $response);
        $esi->handle($cache, '/', '/alt', false);
    }

    public function testHandleWhenResponseIsNot200AndErrorsAreIgnored()
    {
        $esi = new Esi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/'), $response);
        $this->assertEquals('', $esi->handle($cache, '/', '/alt', true));
    }

    public function testHandleWhenResponseIsNot200AndAltIsPresent()
    {
        $esi = new Esi();
        $response1 = new Response('foo');
        $response1->setStatusCode(404);
        $response2 = new Response('bar');
        $cache = $this->getCache(Request::create('/'), array($response1, $response2));
        $this->assertEquals('bar', $esi->handle($cache, '/', '/alt', false));
    }

    protected function getCache($request, $response)
    {
        $cache = $this->getMock('Symfony\Component\HttpKernel\HttpCache\HttpCache', array('getRequest', 'handle'), array(), '', false);
        $cache->expects($this->any())
              ->method('getRequest')
              ->will($this->returnValue($request))
        ;
        if (is_array($response)) {
            $cache->expects($this->any())
                  ->method('handle')
                  ->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response))
            ;
        } else {
            $cache->expects($this->any())
                  ->method('handle')
                  ->will($this->returnValue($response))
            ;
        }

        return $cache;
    }
}
PKK1[���JJRHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/TestMultipleHttpKernel.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\EventDispatcher\EventDispatcher;

class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInterface
{
    protected $bodies = array();
    protected $statuses = array();
    protected $headers = array();
    protected $call = false;
    protected $backendRequest;

    public function __construct($responses)
    {
        foreach ($responses as $response) {
            $this->bodies[]   = $response['body'];
            $this->statuses[] = $response['status'];
            $this->headers[]  = $response['headers'];
        }

        parent::__construct(new EventDispatcher(), $this);
    }

    public function getBackendRequest()
    {
        return $this->backendRequest;
    }

    public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false)
    {
        $this->backendRequest = $request;

        return parent::handle($request, $type, $catch);
    }

    public function getController(Request $request)
    {
        return array($this, 'callController');
    }

    public function getArguments(Request $request, $controller)
    {
        return array($request);
    }

    public function callController(Request $request)
    {
        $this->called = true;

        $response = new Response(array_shift($this->bodies), array_shift($this->statuses), array_shift($this->headers));

        return $response;
    }

    public function hasBeenCalled()
    {
        return $this->called;
    }

    public function reset()
    {
        $this->call = false;
    }
}
PKK1[�VPMHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTestCase.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpCache\Esi;
use Symfony\Component\HttpKernel\HttpCache\HttpCache;
use Symfony\Component\HttpKernel\HttpCache\Store;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class HttpCacheTestCase extends \PHPUnit_Framework_TestCase
{
    protected $kernel;
    protected $cache;
    protected $caches;
    protected $cacheConfig;
    protected $request;
    protected $response;
    protected $responses;
    protected $catch;
    protected $esi;

    protected function setUp()
    {
        $this->kernel = null;

        $this->cache = null;
        $this->esi = null;
        $this->caches = array();
        $this->cacheConfig = array();

        $this->request = null;
        $this->response = null;
        $this->responses = array();

        $this->catch = false;

        $this->clearDirectory(sys_get_temp_dir().'/http_cache');
    }

    protected function tearDown()
    {
        $this->kernel = null;
        $this->cache = null;
        $this->caches = null;
        $this->request = null;
        $this->response = null;
        $this->responses = null;
        $this->cacheConfig = null;
        $this->catch = null;
        $this->esi = null;

        $this->clearDirectory(sys_get_temp_dir().'/http_cache');
    }

    public function assertHttpKernelIsCalled()
    {
        $this->assertTrue($this->kernel->hasBeenCalled());
    }

    public function assertHttpKernelIsNotCalled()
    {
        $this->assertFalse($this->kernel->hasBeenCalled());
    }

    public function assertResponseOk()
    {
        $this->assertEquals(200, $this->response->getStatusCode());
    }

    public function assertTraceContains($trace)
    {
        $traces = $this->cache->getTraces();
        $traces = current($traces);

        $this->assertRegExp('/'.$trace.'/', implode(', ', $traces));
    }

    public function assertTraceNotContains($trace)
    {
        $traces = $this->cache->getTraces();
        $traces = current($traces);

        $this->assertNotRegExp('/'.$trace.'/', implode(', ', $traces));
    }

    public function assertExceptionsAreCaught()
    {
        $this->assertTrue($this->kernel->isCatchingExceptions());
    }

    public function assertExceptionsAreNotCaught()
    {
        $this->assertFalse($this->kernel->isCatchingExceptions());
    }

    public function request($method, $uri = '/', $server = array(), $cookies = array(), $esi = false, $headers = array())
    {
        if (null === $this->kernel) {
            throw new \LogicException('You must call setNextResponse() before calling request().');
        }

        $this->kernel->reset();

        $this->store = new Store(sys_get_temp_dir().'/http_cache');

        $this->cacheConfig['debug'] = true;

        $this->esi = $esi ? new Esi() : null;
        $this->cache = new HttpCache($this->kernel, $this->store, $this->esi, $this->cacheConfig);
        $this->request = Request::create($uri, $method, array(), $cookies, array(), $server);
        $this->request->headers->add($headers);

        $this->response = $this->cache->handle($this->request, HttpKernelInterface::MASTER_REQUEST, $this->catch);

        $this->responses[] = $this->response;
    }

    public function getMetaStorageValues()
    {
        $values = array();
        foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(sys_get_temp_dir().'/http_cache/md', \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
            $values[] = file_get_contents($file);
        }

        return $values;
    }

    // A basic response with 200 status code and a tiny body.
    public function setNextResponse($statusCode = 200, array $headers = array(), $body = 'Hello World', \Closure $customizer = null)
    {
        $this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer);
    }

    public function setNextResponses($responses)
    {
        $this->kernel = new TestMultipleHttpKernel($responses);
    }

    public function catchExceptions($catch = true)
    {
        $this->catch = $catch;
    }

    public static function clearDirectory($directory)
    {
        if (!is_dir($directory)) {
            return;
        }

        $fp = opendir($directory);
        while (false !== $file = readdir($fp)) {
            if (!in_array($file, array('.', '..'))) {
                if (is_link($directory.'/'.$file)) {
                    unlink($directory.'/'.$file);
                } elseif (is_dir($directory.'/'.$file)) {
                    self::clearDirectory($directory.'/'.$file);
                    rmdir($directory.'/'.$file);
                } else {
                    unlink($directory.'/'.$file);
                }
            }
        }

        closedir($fp);
    }
}
PKL1[����Z&Z&EHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\HttpCache;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpCache\Store;

class StoreTest extends \PHPUnit_Framework_TestCase
{
    protected $request;
    protected $response;
    protected $store;

    protected function setUp()
    {
        $this->request = Request::create('/');
        $this->response = new Response('hello world', 200, array());

        HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache');

        $this->store = new Store(sys_get_temp_dir().'/http_cache');
    }

    protected function tearDown()
    {
        $this->store = null;
        $this->request = null;
        $this->response = null;

        HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache');
    }

    public function testReadsAnEmptyArrayWithReadWhenNothingCachedAtKey()
    {
        $this->assertEmpty($this->getStoreMetadata('/nothing'));
    }

    public function testUnlockFileThatDoesExist()
    {
        $cacheKey = $this->storeSimpleEntry();
        $this->store->lock($this->request);

        $this->assertTrue($this->store->unlock($this->request));
    }

    public function testUnlockFileThatDoesNotExist()
    {
        $this->assertFalse($this->store->unlock($this->request));
    }

    public function testRemovesEntriesForKeyWithPurge()
    {
        $request = Request::create('/foo');
        $this->store->write($request, new Response('foo'));

        $metadata = $this->getStoreMetadata($request);
        $this->assertNotEmpty($metadata);

        $this->assertTrue($this->store->purge('/foo'));
        $this->assertEmpty($this->getStoreMetadata($request));

        // cached content should be kept after purging
        $path = $this->store->getPath($metadata[0][1]['x-content-digest'][0]);
        $this->assertTrue(is_file($path));

        $this->assertFalse($this->store->purge('/bar'));
    }

    public function testStoresACacheEntry()
    {
        $cacheKey = $this->storeSimpleEntry();

        $this->assertNotEmpty($this->getStoreMetadata($cacheKey));
    }

    public function testSetsTheXContentDigestResponseHeaderBeforeStoring()
    {
        $cacheKey = $this->storeSimpleEntry();
        $entries = $this->getStoreMetadata($cacheKey);
        list ($req, $res) = $entries[0];

        $this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]);
    }

    public function testFindsAStoredEntryWithLookup()
    {
        $this->storeSimpleEntry();
        $response = $this->store->lookup($this->request);

        $this->assertNotNull($response);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
    }

    public function testDoesNotFindAnEntryWithLookupWhenNoneExists()
    {
        $request = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));

        $this->assertNull($this->store->lookup($request));
    }

    public function testCanonizesUrlsForCacheKeys()
    {
        $this->storeSimpleEntry($path = '/test?x=y&p=q');
        $hitsReq = Request::create($path);
        $missReq = Request::create('/test?p=x');

        $this->assertNotNull($this->store->lookup($hitsReq));
        $this->assertNull($this->store->lookup($missReq));
    }

    public function testDoesNotFindAnEntryWithLookupWhenTheBodyDoesNotExist()
    {
        $this->storeSimpleEntry();
        $this->assertNotNull($this->response->headers->get('X-Content-Digest'));
        $path = $this->getStorePath($this->response->headers->get('X-Content-Digest'));
        @unlink($path);
        $this->assertNull($this->store->lookup($this->request));
    }

    public function testRestoresResponseHeadersProperlyWithLookup()
    {
        $this->storeSimpleEntry();
        $response = $this->store->lookup($this->request);

        $this->assertEquals($response->headers->all(), array_merge(array('content-length' => 4, 'x-body-file' => array($this->getStorePath($response->headers->get('X-Content-Digest')))), $this->response->headers->all()));
    }

    public function testRestoresResponseContentFromEntityStoreWithLookup()
    {
        $this->storeSimpleEntry();
        $response = $this->store->lookup($this->request);
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test')), $response->getContent());
    }

    public function testInvalidatesMetaAndEntityStoreEntriesWithInvalidate()
    {
        $this->storeSimpleEntry();
        $this->store->invalidate($this->request);
        $response = $this->store->lookup($this->request);
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response);
        $this->assertFalse($response->isFresh());
    }

    public function testSucceedsQuietlyWhenInvalidateCalledWithNoMatchingEntries()
    {
        $req = Request::create('/test');
        $this->store->invalidate($req);
        $this->assertNull($this->store->lookup($this->request));
    }

    public function testDoesNotReturnEntriesThatVaryWithLookup()
    {
        $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
        $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
        $res = new Response('test', 200, array('Vary' => 'Foo Bar'));
        $this->store->write($req1, $res);

        $this->assertNull($this->store->lookup($req2));
    }

    public function testStoresMultipleResponsesForEachVaryCombination()
    {
        $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
        $res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
        $key = $this->store->write($req1, $res1);

        $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
        $res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
        $this->store->write($req2, $res2);

        $req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Baz', 'HTTP_BAR' => 'Boom'));
        $res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
        $this->store->write($req3, $res3);

        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent());
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent());
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent());

        $this->assertCount(3, $this->getStoreMetadata($key));
    }

    public function testOverwritesNonVaryingResponseWithStore()
    {
        $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
        $res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar'));
        $key = $this->store->write($req1, $res1);
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent());

        $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam'));
        $res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar'));
        $this->store->write($req2, $res2);
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent());

        $req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
        $res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar'));
        $key = $this->store->write($req3, $res3);
        $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent());

        $this->assertCount(2, $this->getStoreMetadata($key));
    }

    public function testLocking()
    {
        $req = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar'));
        $this->assertTrue($this->store->lock($req));

        $path = $this->store->lock($req);
        $this->assertTrue($this->store->isLocked($req));

        $this->store->unlock($req);
        $this->assertFalse($this->store->isLocked($req));
    }

    protected function storeSimpleEntry($path = null, $headers = array())
    {
        if (null === $path) {
            $path = '/test';
        }

        $this->request = Request::create($path, 'get', array(), array(), array(), $headers);
        $this->response = new Response('test', 200, array('Cache-Control' => 'max-age=420'));

        return $this->store->write($this->request, $this->response);
    }

    protected function getStoreMetadata($key)
    {
        $r = new \ReflectionObject($this->store);
        $m = $r->getMethod('getMetadata');
        $m->setAccessible(true);

        if ($key instanceof Request) {
            $m1 = $r->getMethod('getCacheKey');
            $m1->setAccessible(true);
            $key = $m1->invoke($this->store, $key);
        }

        return $m->invoke($this->store, $key);
    }

    protected function getStorePath($key)
    {
        $r = new \ReflectionObject($this->store);
        $m = $r->getMethod('getPath');
        $m->setAccessible(true);

        return $m->invoke($this->store, $key);
    }
}
PKL1[�`1HHttpKernel/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Config;

use Symfony\Component\HttpKernel\Config\FileLocator;

class FileLocatorTest extends \PHPUnit_Framework_TestCase
{
    public function testLocate()
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
        $kernel
            ->expects($this->atLeastOnce())
            ->method('locateResource')
            ->with('@BundleName/some/path', null, true)
            ->will($this->returnValue('/bundle-name/some/path'));
        $locator = new FileLocator($kernel);
        $this->assertEquals('/bundle-name/some/path', $locator->locate('@BundleName/some/path'));

        $kernel
            ->expects($this->never())
            ->method('locateResource');
        $this->setExpectedException('LogicException');
        $locator->locate('/some/path');
    }

    public function testLocateWithGlobalResourcePath()
    {
        $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
        $kernel
            ->expects($this->atLeastOnce())
            ->method('locateResource')
            ->with('@BundleName/some/path', '/global/resource/path', false);

        $locator = new FileLocator($kernel, '/global/resource/path');
        $locator->locate('@BundleName/some/path', null, false);
    }
}
PKL1[K�w��CHttpKernel/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Bundle;

use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddConsoleCommandPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionAbsentBundle\ExtensionAbsentBundle;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand;
use Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\ExtensionPresentBundle;

class BundleTest extends \PHPUnit_Framework_TestCase
{
    public function testRegisterCommands()
    {
        $cmd = new FooCommand();
        $app = $this->getMock('Symfony\Component\Console\Application');
        $app->expects($this->once())->method('add')->with($this->equalTo($cmd));

        $bundle = new ExtensionPresentBundle();
        $bundle->registerCommands($app);

        $bundle2 = new ExtensionAbsentBundle();

        $this->assertNull($bundle2->registerCommands($app));
    }

    public function testRegisterCommandsIngoreCommandAsAService()
    {
        $container = new ContainerBuilder();
        $container->addCompilerPass(new AddConsoleCommandPass());
        $definition = new Definition('Symfony\Component\HttpKernel\Tests\Fixtures\ExtensionPresentBundle\Command\FooCommand');
        $definition->addTag('console.command');
        $container->setDefinition('my-command', $definition);
        $container->compile();

        $application = $this->getMock('Symfony\Component\Console\Application');
        // Never called, because it's the
        // Symfony\Bundle\FrameworkBundle\Console\Application that register
        // commands as a service
        $application->expects($this->never())->method('add');

        $bundle = new ExtensionPresentBundle();
        $bundle->setContainer($container);
        $bundle->registerCommands($application);
    }
}
PKL1[!�g���VHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MemcacheProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\MemcacheProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\MemcacheMock;

class MemcacheProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $storage;

    protected function setUp()
    {
        $memcacheMock = new MemcacheMock();
        $memcacheMock->addServer('127.0.0.1', 11211);

        self::$storage = new MemcacheProfilerStorage('memcache://127.0.0.1:11211', '', '', 86400);
        self::$storage->setMemcache($memcacheMock);

        if (self::$storage) {
            self::$storage->purge();
        }
    }

    protected function tearDown()
    {
        if (self::$storage) {
            self::$storage->purge();
            self::$storage = false;
        }
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }
}
PKL1[�[���WHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MemcachedProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\MemcachedProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\MemcachedMock;

class MemcachedProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $storage;

    protected function setUp()
    {
        $memcachedMock = new MemcachedMock();
        $memcachedMock->addServer('127.0.0.1', 11211);

        self::$storage = new MemcachedProfilerStorage('memcached://127.0.0.1:11211', '', '', 86400);
        self::$storage->setMemcached($memcachedMock);

        if (self::$storage) {
            self::$storage->purge();
        }
    }

    protected function tearDown()
    {
        if (self::$storage) {
            self::$storage->purge();
            self::$storage = false;
        }
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }
}
PKL1[T���
�
RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\FileProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profile;

class FileProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $tmpDir;
    protected static $storage;

    protected static function cleanDir()
    {
        $flags = \FilesystemIterator::SKIP_DOTS;
        $iterator = new \RecursiveDirectoryIterator(self::$tmpDir, $flags);
        $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);

        foreach ($iterator as $file) {
            if (is_file($file)) {
                unlink($file);
            }
        }
    }

    public static function setUpBeforeClass()
    {
        self::$tmpDir = sys_get_temp_dir().'/sf2_profiler_file_storage';
        if (is_dir(self::$tmpDir)) {
            self::cleanDir();
        }
        self::$storage = new FileProfilerStorage('file:'.self::$tmpDir);
    }

    public static function tearDownAfterClass()
    {
        self::cleanDir();
    }

    protected function setUp()
    {
        self::$storage->purge();
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }

    public function testMultiRowIndexFile()
    {
        $iteration = 3;
        for ($i = 0; $i < $iteration; $i++) {
            $profile = new Profile('token'.$i);
            $profile->setIp('127.0.0.'.$i);
            $profile->setUrl('http://foo.bar/'.$i);
            $storage = $this->getStorage();

            $storage->write($profile);
            $storage->write($profile);
            $storage->write($profile);
        }

        $handle = fopen(self::$tmpDir.'/index.csv', 'r');
        for ($i = 0; $i < $iteration; $i++) {
            $row = fgetcsv($handle);
            $this->assertEquals('token'.$i, $row[0]);
            $this->assertEquals('127.0.0.'.$i, $row[1]);
            $this->assertEquals('http://foo.bar/'.$i, $row[3]);
        }
        $this->assertFalse(fgetcsv($handle));
    }

    public function testReadLineFromFile()
    {
        $r = new \ReflectionMethod(self::$storage, 'readLineFromFile');

        $r->setAccessible(true);

        $h = tmpfile();

        fwrite($h, "line1\n\n\nline2\n");
        fseek($h, 0, SEEK_END);

        $this->assertEquals("line2", $r->invoke(self::$storage, $h));
        $this->assertEquals("line1", $r->invoke(self::$storage, $h));
    }
}
PKL1[�,���)�)VHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/AbstractProfilerStorageTest.phpnu�[���<?php
/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\Profile;

abstract class AbstractProfilerStorageTest extends \PHPUnit_Framework_TestCase
{
    public function testStore()
    {
        for ($i = 0; $i < 10; $i ++) {
            $profile = new Profile('token_'.$i);
            $profile->setIp('127.0.0.1');
            $profile->setUrl('http://foo.bar');
            $profile->setMethod('GET');
            $this->getStorage()->write($profile);
        }
        $this->assertCount(10, $this->getStorage()->find('127.0.0.1', 'http://foo.bar', 20, 'GET'), '->write() stores data in the storage');
    }

    public function testChildren()
    {
        $parentProfile = new Profile('token_parent');
        $parentProfile->setIp('127.0.0.1');
        $parentProfile->setUrl('http://foo.bar/parent');

        $childProfile = new Profile('token_child');
        $childProfile->setIp('127.0.0.1');
        $childProfile->setUrl('http://foo.bar/child');

        $parentProfile->addChild($childProfile);

        $this->getStorage()->write($parentProfile);
        $this->getStorage()->write($childProfile);

        // Load them from storage
        $parentProfile = $this->getStorage()->read('token_parent');
        $childProfile  = $this->getStorage()->read('token_child');

        // Check child has link to parent
        $this->assertNotNull($childProfile->getParent());
        $this->assertEquals($parentProfile->getToken(), $childProfile->getParentToken());

        // Check parent has child
        $children = $parentProfile->getChildren();
        $this->assertCount(1, $children);
        $this->assertEquals($childProfile->getToken(), $children[0]->getToken());
    }

    public function testStoreSpecialCharsInUrl()
    {
        // The storage accepts special characters in URLs (Even though URLs are not
        // supposed to contain them)
        $profile = new Profile('simple_quote');
        $profile->setUrl('http://foo.bar/\'');
        $this->getStorage()->write($profile);
        $this->assertTrue(false !== $this->getStorage()->read('simple_quote'), '->write() accepts single quotes in URL');

        $profile = new Profile('double_quote');
        $profile->setUrl('http://foo.bar/"');
        $this->getStorage()->write($profile);
        $this->assertTrue(false !== $this->getStorage()->read('double_quote'), '->write() accepts double quotes in URL');

        $profile = new Profile('backslash');
        $profile->setUrl('http://foo.bar/\\');
        $this->getStorage()->write($profile);
        $this->assertTrue(false !== $this->getStorage()->read('backslash'), '->write() accepts backslash in URL');

        $profile = new Profile('comma');
        $profile->setUrl('http://foo.bar/,');
        $this->getStorage()->write($profile);
        $this->assertTrue(false !== $this->getStorage()->read('comma'), '->write() accepts comma in URL');
    }

    public function testStoreDuplicateToken()
    {
        $profile = new Profile('token');
        $profile->setUrl('http://example.com/');

        $this->assertTrue($this->getStorage()->write($profile), '->write() returns true when the token is unique');

        $profile->setUrl('http://example.net/');

        $this->assertTrue($this->getStorage()->write($profile), '->write() returns true when the token is already present in the storage');
        $this->assertEquals('http://example.net/', $this->getStorage()->read('token')->getUrl(), '->write() overwrites the current profile data');

        $this->assertCount(1, $this->getStorage()->find('', '', 1000, ''), '->find() does not return the same profile twice');
    }

    public function testRetrieveByIp()
    {
        $profile = new Profile('token');
        $profile->setIp('127.0.0.1');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'), '->find() retrieve a record by IP');
        $this->assertCount(0, $this->getStorage()->find('127.0.%.1', '', 10, 'GET'), '->find() does not interpret a "%" as a wildcard in the IP');
        $this->assertCount(0, $this->getStorage()->find('127.0._.1', '', 10, 'GET'), '->find() does not interpret a "_" as a wildcard in the IP');
    }

    public function testRetrieveByUrl()
    {
        $profile = new Profile('simple_quote');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo.bar/\'');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $profile = new Profile('double_quote');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo.bar/"');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $profile = new Profile('backslash');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo\\bar/');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $profile = new Profile('percent');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo.bar/%');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $profile = new Profile('underscore');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo.bar/_');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $profile = new Profile('semicolon');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://foo.bar/;');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/\'', 10, 'GET'), '->find() accepts single quotes in URLs');
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/"', 10, 'GET'), '->find() accepts double quotes in URLs');
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo\\bar/', 10, 'GET'), '->find() accepts backslash in URLs');
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/;', 10, 'GET'), '->find() accepts semicolon in URLs');
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/%', 10, 'GET'), '->find() does not interpret a "%" as a wildcard in the URL');
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', 'http://foo.bar/_', 10, 'GET'), '->find() does not interpret a "_" as a wildcard in the URL');
    }

    public function testStoreTime()
    {
        $dt = new \DateTime('now');
        $start = $dt->getTimestamp();

        for ($i = 0; $i < 3; $i++) {
            $dt->modify('+1 minute');
            $profile = new Profile('time_'.$i);
            $profile->setIp('127.0.0.1');
            $profile->setUrl('http://foo.bar');
            $profile->setTime($dt->getTimestamp());
            $profile->setMethod('GET');
            $this->getStorage()->write($profile);
        }

        $records = $this->getStorage()->find('', '', 3, 'GET', $start, time() + 3 * 60);
        $this->assertCount(3, $records, '->find() returns all previously added records');
        $this->assertEquals($records[0]['token'], 'time_2', '->find() returns records ordered by time in descendant order');
        $this->assertEquals($records[1]['token'], 'time_1', '->find() returns records ordered by time in descendant order');
        $this->assertEquals($records[2]['token'], 'time_0', '->find() returns records ordered by time in descendant order');

        $records = $this->getStorage()->find('', '', 3, 'GET', $start, time() + 2 * 60);
        $this->assertCount(2, $records, '->find() should return only first two of the previously added records');
    }

    public function testRetrieveByEmptyUrlAndIp()
    {
        for ($i = 0; $i < 5; $i++) {
            $profile = new Profile('token_'.$i);
            $profile->setMethod('GET');
            $this->getStorage()->write($profile);
        }
        $this->assertCount(5, $this->getStorage()->find('', '', 10, 'GET'), '->find() returns all previously added records');
        $this->getStorage()->purge();
    }

    public function testRetrieveByMethodAndLimit()
    {
        foreach (array('POST', 'GET') as $method) {
            for ($i = 0; $i < 5; $i++) {
                $profile = new Profile('token_'.$i.$method);
                $profile->setMethod($method);
                $this->getStorage()->write($profile);
            }
        }

        $this->assertCount(5, $this->getStorage()->find('', '', 5, 'POST'));

        $this->getStorage()->purge();
    }

    public function testPurge()
    {
        $profile = new Profile('token1');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://example.com/');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $this->assertTrue(false !== $this->getStorage()->read('token1'));
        $this->assertCount(1, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'));

        $profile = new Profile('token2');
        $profile->setIp('127.0.0.1');
        $profile->setUrl('http://example.net/');
        $profile->setMethod('GET');
        $this->getStorage()->write($profile);

        $this->assertTrue(false !== $this->getStorage()->read('token2'));
        $this->assertCount(2, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'));

        $this->getStorage()->purge();

        $this->assertEmpty($this->getStorage()->read('token'), '->purge() removes all data stored by profiler');
        $this->assertCount(0, $this->getStorage()->find('127.0.0.1', '', 10, 'GET'), '->purge() removes all items from index');
    }

    public function testDuplicates()
    {
        for ($i = 1; $i <= 5; $i++) {
            $profile = new Profile('foo'.$i);
            $profile->setIp('127.0.0.1');
            $profile->setUrl('http://example.net/');
            $profile->setMethod('GET');

            ///three duplicates
            $this->getStorage()->write($profile);
            $this->getStorage()->write($profile);
            $this->getStorage()->write($profile);
        }
        $this->assertCount(3, $this->getStorage()->find('127.0.0.1', 'http://example.net/', 3, 'GET'), '->find() method returns incorrect number of entries');
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    abstract protected function getStorage();
}
PKL1[�.�\��MHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcachedMock.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler\Mock;

/**
 * MemcachedMock for simulating Memcached extension in tests.
 *
 * @author Andrej Hudec <pulzarraider@gmail.com>
 */
class MemcachedMock
{
    private $connected = false;
    private $storage = array();

    /**
     * Set a Memcached option
     *
     * @param integer $option
     * @param mixed   $value
     *
     * @return boolean
     */
    public function setOption($option, $value)
    {
        return true;
    }

    /**
     * Add a memcached server to connection pool
     *
     * @param string  $host
     * @param integer $port
     * @param integer $weight
     *
     * @return boolean
     */
    public function addServer($host, $port = 11211, $weight = 0)
    {
        if ('127.0.0.1' == $host && 11211 == $port) {
            $this->connected = true;

            return true;
        }

        return false;
    }

    /**
     * Add an item to the server only if such key doesn't exist at the server yet.
     *
     * @param string  $key
     * @param mixed   $value
     * @param integer $expiration
     *
     * @return boolean
     */
    public function add($key, $value, $expiration = 0)
    {
        if (!$this->connected) {
            return false;
        }

        if (!isset($this->storage[$key])) {
            $this->storeData($key, $value);

            return true;
        }

        return false;
    }

    /**
     * Store data at the server.
     *
     * @param string  $key
     * @param mixed   $value
     * @param integer $expiration
     *
     * @return boolean
     */
    public function set($key, $value, $expiration = null)
    {
        if (!$this->connected) {
            return false;
        }

        $this->storeData($key, $value);

        return true;
    }

    /**
     * Replace value of the existing item.
     *
     * @param string  $key
     * @param mixed   $value
     * @param integer $expiration
     *
     * @return boolean
     */
    public function replace($key, $value, $expiration = null)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            $this->storeData($key, $value);

            return true;
        }

        return false;
    }

    /**
     * Retrieve item from the server.
     *
     * @param string   $key
     * @param callable $cache_cb
     * @param float    $cas_token
     *
     * @return boolean
     */
    public function get($key, $cache_cb = null, &$cas_token = null)
    {
        if (!$this->connected) {
            return false;
        }

        return $this->getData($key);
    }

    /**
     * Append data to an existing item
     *
     * @param string $key
     * @param string $value
     *
     * @return boolean
     */
    public function append($key, $value)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            $this->storeData($key, $this->getData($key).$value);

            return true;
        }

        return false;
    }

    /**
     * Delete item from the server
     *
     * @param string $key
     *
     * @return boolean
     */
    public function delete($key)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            unset($this->storage[$key]);

            return true;
        }

        return false;
    }

    /**
     * Flush all existing items at the server
     *
     * @return boolean
     */
    public function flush()
    {
        if (!$this->connected) {
            return false;
        }

        $this->storage = array();

        return true;
    }

    private function getData($key)
    {
        if (isset($this->storage[$key])) {
            return unserialize($this->storage[$key]);
        }

        return false;
    }

    private function storeData($key, $value)
    {
        $this->storage[$key] = serialize($value);

        return true;
    }
}
PKL1[i�]��LHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcacheMock.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler\Mock;

/**
 * MemcacheMock for simulating Memcache extension in tests.
 *
 * @author Andrej Hudec <pulzarraider@gmail.com>
 */
class MemcacheMock
{
    private $connected = false;
    private $storage = array();

    /**
     * Open memcached server connection
     *
     * @param string  $host
     * @param integer $port
     * @param integer $timeout
     *
     * @return boolean
     */
    public function connect($host, $port = null, $timeout = null)
    {
        if ('127.0.0.1' == $host && 11211 == $port) {
            $this->connected = true;

            return true;
        }

        return false;
    }

    /**
     * Open memcached server persistent connection
     *
     * @param string  $host
     * @param integer $port
     * @param integer $timeout
     *
     * @return boolean
     */
    public function pconnect($host, $port = null, $timeout = null)
    {
        if ('127.0.0.1' == $host && 11211 == $port) {
            $this->connected = true;

            return true;
        }

        return false;
    }

    /**
     * Add a memcached server to connection pool
     *
     * @param string   $host
     * @param integer  $port
     * @param boolean  $persistent
     * @param integer  $weight
     * @param integer  $timeout
     * @param integer  $retry_interval
     * @param boolean  $status
     * @param callable $failure_callback
     * @param integer  $timeoutms
     *
     * @return boolean
     */
    public function addServer($host, $port = 11211, $persistent = null, $weight = null, $timeout = null, $retry_interval = null, $status = null, $failure_callback = null, $timeoutms = null)
    {
        if ('127.0.0.1' == $host && 11211 == $port) {
            $this->connected = true;

            return true;
        }

        return false;
    }

    /**
     * Add an item to the server only if such key doesn't exist at the server yet.
     *
     * @param string  $key
     * @param mixed   $var
     * @param integer $flag
     * @param integer $expire
     *
     * @return boolean
     */
    public function add($key, $var, $flag = null, $expire = null)
    {
        if (!$this->connected) {
            return false;
        }

        if (!isset($this->storage[$key])) {
            $this->storeData($key, $var);

            return true;
        }

        return false;
    }

    /**
     * Store data at the server.
     *
     * @param string  $key
     * @param string  $var
     * @param integer $flag
     * @param integer $expire
     *
     * @return boolean
     */
    public function set($key, $var, $flag = null, $expire = null)
    {
        if (!$this->connected) {
            return false;
        }

        $this->storeData($key, $var);

        return true;
    }

    /**
     * Replace value of the existing item.
     *
     * @param string  $key
     * @param mixed   $var
     * @param integer $flag
     * @param integer $expire
     *
     * @return boolean
     */
    public function replace($key, $var, $flag = null, $expire = null)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            $this->storeData($key, $var);

            return true;
        }

        return false;
    }

    /**
     * Retrieve item from the server.
     *
     * @param string|array  $key
     * @param integer|array $flags
     *
     * @return mixed
     */
    public function get($key, &$flags = null)
    {
        if (!$this->connected) {
            return false;
        }

        if (is_array($key)) {
            $result = array();
            foreach ($key as $k) {
                if (isset($this->storage[$k])) {
                    $result[] = $this->getData($k);
                }
            }

            return $result;
        }

        return $this->getData($key);
    }

    /**
     * Delete item from the server
     *
     * @param string $key
     *
     * @return boolean
     */
    public function delete($key)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            unset($this->storage[$key]);

            return true;
        }

        return false;
    }

    /**
     * Flush all existing items at the server
     *
     * @return boolean
     */
    public function flush()
    {
        if (!$this->connected) {
            return false;
        }

        $this->storage = array();

        return true;
    }

    /**
     * Close memcached server connection
     *
     * @return boolean
     */
    public function close()
    {
        $this->connected = false;

        return true;
    }

    private function getData($key)
    {
        if (isset($this->storage[$key])) {
            return unserialize($this->storage[$key]);
        }

        return false;
    }

    private function storeData($key, $value)
    {
        $this->storage[$key] = serialize($value);

        return true;
    }
}
PKL1[e��K

IHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler\Mock;

/**
 * RedisMock for simulating Redis extension in tests.
 *
 * @author Andrej Hudec <pulzarraider@gmail.com>
 */
class RedisMock
{
    private $connected = false;
    private $storage = array();

    /**
     * Add a server to connection pool
     *
     * @param string  $host
     * @param integer $port
     * @param float   $timeout
     *
     * @return boolean
     */
    public function connect($host, $port = 6379, $timeout = 0)
    {
        if ('127.0.0.1' == $host && 6379 == $port) {
            $this->connected = true;

            return true;
        }

        return false;
    }

    /**
     * Set client option.
     *
     * @param integer $name
     * @param integer $value
     *
     * @return boolean
     */
    public function setOption($name, $value)
    {
        if (!$this->connected) {
            return false;
        }

        return true;
    }

    /**
     * Verify if the specified key exists.
     *
     * @param string $key
     *
     * @return boolean
     */
    public function exists($key)
    {
        if (!$this->connected) {
            return false;
        }

        return isset($this->storage[$key]);
    }

    /**
     * Store data at the server with expiration time.
     *
     * @param string  $key
     * @param integer $ttl
     * @param mixed   $value
     *
     * @return boolean
     */
    public function setex($key, $ttl, $value)
    {
        if (!$this->connected) {
            return false;
        }

        $this->storeData($key, $value);

        return true;
    }

    /**
     * Sets an expiration time on an item.
     *
     * @param string  $key
     * @param integer $ttl
     *
     * @return boolean
     */
    public function setTimeout($key, $ttl)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            return true;
        }

        return false;
    }

    /**
     * Retrieve item from the server.
     *
     * @param string $key
     *
     * @return boolean
     */
    public function get($key)
    {
        if (!$this->connected) {
            return false;
        }

        return $this->getData($key);
    }

    /**
     * Append data to an existing item
     *
     * @param string $key
     * @param string $value
     *
     * @return integer Size of the value after the append.
     */
    public function append($key, $value)
    {
        if (!$this->connected) {
            return false;
        }

        if (isset($this->storage[$key])) {
            $this->storeData($key, $this->getData($key).$value);

            return strlen($this->storage[$key]);
        }

        return false;
    }

    /**
     * Remove specified keys.
     *
     * @param string|array $key
     *
     * @return integer
     */
    public function delete($key)
    {
        if (!$this->connected) {
            return false;
        }

        if (is_array($key)) {
            $result = 0;
            foreach ($key as $k) {
                if (isset($this->storage[$k])) {
                    unset($this->storage[$k]);
                    ++$result;
                }
            }

            return $result;
        }

        if (isset($this->storage[$key])) {
            unset($this->storage[$key]);

            return 1;
        }

        return 0;
    }

    /**
     * Flush all existing items from all databases at the server.
     *
     * @return boolean
     */
    public function flushAll()
    {
        if (!$this->connected) {
            return false;
        }

        $this->storage = array();

        return true;
    }

    /**
     * Close Redis server connection
     *
     * @return boolean
     */
    public function close()
    {
        $this->connected = false;

        return true;
    }

    private function getData($key)
    {
        if (isset($this->storage[$key])) {
            return unserialize($this->storage[$key]);
        }

        return false;
    }

    private function storeData($key, $value)
    {
        $this->storage[$key] = serialize($value);

        return true;
    }

    public function select($dbnum)
    {
        if (!$this->connected) {
            return false;
        }

        if (0 > $dbnum) {
            return false;
        }

        return true;
    }
}
PKL1[`ej��UHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MongoDbProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\MongoDbProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profile;
use Symfony\Component\HttpKernel\DataCollector\DataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DummyMongoDbProfilerStorage extends MongoDbProfilerStorage
{
    public function getMongo()
    {
        return parent::getMongo();
    }
}

class MongoDbProfilerStorageTestDataCollector extends DataCollector
{
    public function setData($data)
    {
        $this->data = $data;
    }

    public function getData()
    {
        return $this->data;
    }

    public function collect(Request $request, Response $response, \Exception $exception = null)
    {
    }

    public function getName()
    {
        return 'test_data_collector';
    }
}

class MongoDbProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $storage;

    public static function setUpBeforeClass()
    {
        if (extension_loaded('mongo')) {
            self::$storage = new DummyMongoDbProfilerStorage('mongodb://localhost/symfony_tests/profiler_data', '', '', 86400);
            try {
                self::$storage->getMongo();
            } catch (\MongoConnectionException $e) {
                self::$storage = null;
            }
        }
    }

    public static function tearDownAfterClass()
    {
        if (self::$storage) {
            self::$storage->purge();
            self::$storage = null;
        }
    }

    public function getDsns()
    {
        return array(
            array('mongodb://localhost/symfony_tests/profiler_data', array(
                'mongodb://localhost/symfony_tests',
                'symfony_tests',
                'profiler_data'
            )),
            array('mongodb://user:password@localhost/symfony_tests/profiler_data', array(
                'mongodb://user:password@localhost/symfony_tests',
                'symfony_tests',
                'profiler_data'
            )),
            array('mongodb://user:password@localhost/admin/symfony_tests/profiler_data', array(
                'mongodb://user:password@localhost/admin',
                'symfony_tests',
                'profiler_data'
            )),
            array('mongodb://user:password@localhost:27009,localhost:27010/?replicaSet=rs-name&authSource=admin/symfony_tests/profiler_data', array(
                'mongodb://user:password@localhost:27009,localhost:27010/?replicaSet=rs-name&authSource=admin',
                'symfony_tests',
                'profiler_data'
            ))
        );
    }

    public function testCleanup()
    {
        $dt = new \DateTime('-2 day');
        for ($i = 0; $i < 3; $i++) {
            $dt->modify('-1 day');
            $profile = new Profile('time_'.$i);
            $profile->setTime($dt->getTimestamp());
            $profile->setMethod('GET');
            self::$storage->write($profile);
        }
        $records = self::$storage->find('', '', 3, 'GET');
        $this->assertCount(1, $records, '->find() returns only one record');
        $this->assertEquals($records[0]['token'], 'time_2', '->find() returns the latest added record');
        self::$storage->purge();
    }

    /**
     * @dataProvider getDsns
     */
    public function testDsnParser($dsn, $expected)
    {
        $m = new \ReflectionMethod(self::$storage, 'parseDsn');
        $m->setAccessible(true);

        $this->assertEquals($expected, $m->invoke(self::$storage, $dsn));
    }

    public function testUtf8()
    {
        $profile = new Profile('utf8_test_profile');

        $data = 'HЁʃʃϿ, ϢorЃd!';
        $nonUtf8Data = mb_convert_encoding($data, 'UCS-2');

        $collector = new MongoDbProfilerStorageTestDataCollector();
        $collector->setData($nonUtf8Data);

        $profile->setCollectors(array($collector));

        self::$storage->write($profile);

        $readProfile = self::$storage->read('utf8_test_profile');
        $collectors = $readProfile->getCollectors();

        $this->assertCount(1, $collectors);
        $this->assertArrayHasKey('test_data_collector', $collectors);
        $this->assertEquals($nonUtf8Data, $collectors['test_data_collector']->getData(), 'Non-UTF8 data is properly encoded/decoded');
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }

    protected function setUp()
    {
        if (self::$storage) {
            self::$storage->purge();
        } else {
            $this->markTestSkipped('MongoDbProfilerStorageTest requires the mongo PHP extension and a MongoDB server on localhost');
        }
    }
}
PKL1[p3hNNTHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/SqliteProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\SqliteProfilerStorage;

class SqliteProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $dbFile;
    protected static $storage;

    public static function setUpBeforeClass()
    {
        self::$dbFile = tempnam(sys_get_temp_dir(), 'sf2_sqlite_storage');
        if (file_exists(self::$dbFile)) {
            @unlink(self::$dbFile);
        }
        self::$storage = new SqliteProfilerStorage('sqlite:'.self::$dbFile);
    }

    public static function tearDownAfterClass()
    {
        @unlink(self::$dbFile);
    }

    protected function setUp()
    {
        if (!class_exists('SQLite3') && (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers()))) {
            $this->markTestSkipped('This test requires SQLite support in your environment');
        }
        self::$storage->purge();
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }
}
PKL1[�FE��SHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/RedisProfilerStorageTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\Profiler\RedisProfilerStorage;
use Symfony\Component\HttpKernel\Tests\Profiler\Mock\RedisMock;

class RedisProfilerStorageTest extends AbstractProfilerStorageTest
{
    protected static $storage;

    protected function setUp()
    {
        $redisMock = new RedisMock();
        $redisMock->connect('127.0.0.1', 6379);

        self::$storage = new RedisProfilerStorage('redis://127.0.0.1:6379', '', '', 86400);
        self::$storage->setRedis($redisMock);

        if (self::$storage) {
            self::$storage->purge();
        }
    }

    protected function tearDown()
    {
        if (self::$storage) {
            self::$storage->purge();
            self::$storage = false;
        }
    }

    /**
     * @return \Symfony\Component\HttpKernel\Profiler\ProfilerStorageInterface
     */
    protected function getStorage()
    {
        return self::$storage;
    }
}
PKL1[�&2TTGHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/ProfilerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Profiler;

use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Profiler\SqliteProfilerStorage;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ProfilerTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        if (!class_exists('SQLite3') && (!class_exists('PDO') || !in_array('sqlite', \PDO::getAvailableDrivers()))) {
            $this->markTestSkipped('This test requires SQLite support in your environment');
        }

        $request = new Request();
        $request->query->set('foo', 'bar');
        $response = new Response();
        $collector = new RequestDataCollector();

        $tmp = tempnam(sys_get_temp_dir(), 'sf2_profiler');
        if (file_exists($tmp)) {
            @unlink($tmp);
        }
        $storage = new SqliteProfilerStorage('sqlite:'.$tmp);
        $storage->purge();

        $profiler = new Profiler($storage);
        $profiler->add($collector);
        $profile = $profiler->collect($request, $response);

        $profile = $profiler->loadProfile($profile->getToken());
        $this->assertEquals(array('foo' => 'bar'), $profiler->get('request')->getRequestQuery()->all());

        @unlink($tmp);
    }
}
PKL1[�Uu֝�?HttpKernel/Symfony/Component/HttpKernel/Tests/UriSignerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Symfony\Component\HttpKernel\UriSigner;

class UriSignerTest extends \PHPUnit_Framework_TestCase
{
    public function testSign()
    {
        $signer = new UriSigner('foobar');

        $this->assertContains('?_hash=', $signer->sign('http://example.com/foo'));
        $this->assertContains('&_hash=', $signer->sign('http://example.com/foo?foo=bar'));
    }

    public function testCheck()
    {
        $signer = new UriSigner('foobar');

        $this->assertFalse($signer->check('http://example.com/foo?_hash=foo'));
        $this->assertFalse($signer->check('http://example.com/foo?foo=bar&_hash=foo'));
        $this->assertFalse($signer->check('http://example.com/foo?foo=bar&_hash=foo&bar=foo'));

        $this->assertTrue($signer->check($signer->sign('http://example.com/foo')));
        $this->assertTrue($signer->check($signer->sign('http://example.com/foo?foo=bar')));
    }
}
PKL1[bҏ�^^WHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/MemoryDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\MemoryDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class MemoryDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        $collector = new MemoryDataCollector();
        $collector->collect(new Request(), new Response());

        $this->assertInternalType('integer', $collector->getMemory());
        $this->assertInternalType('integer', $collector->getMemoryLimit());
        $this->assertSame('memory', $collector->getName());
    }

    /** @dataProvider getBytesConversionTestData */
    public function testBytesConversion($limit, $bytes)
    {
        $collector = new MemoryDataCollector();
        $method = new \ReflectionMethod($collector, 'convertToBytes');
        $method->setAccessible(true);
        $this->assertEquals($bytes, $method->invoke($collector, $limit));
    }

    public function getBytesConversionTestData()
    {
        return array(
            array('2k', 2048),
            array('2 k', 2048),
            array('8m', 8 * 1024 * 1024),
            array('+2 k', 2048),
            array('+2???k', 2048),
            array('0x10', 16),
            array('0xf', 15),
            array('010', 8),
            array('+0x10 k', 16 * 1024),
            array('1g', 1024 * 1024 * 1024),
            array('1G', 1024 * 1024 * 1024),
            array('-1', -1),
            array('0', 0),
            array('2mk', 2048), // the unit must be the last char, so in this case 'k', not 'm'
        );
    }
}
PKL1[�C���UHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\TimeDataCollector;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class TimeDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        $c = new TimeDataCollector();

        $request = new Request();
        $request->server->set('REQUEST_TIME', 1);

        $c->collect($request, new Response());

        $this->assertEquals(1000, $c->getStartTime());

        $request->server->set('REQUEST_TIME_FLOAT', 2);

        $c->collect($request, new Response());

        $this->assertEquals(2000, $c->getStartTime());

        $request = new Request();
        $c->collect($request, new Response());
        $this->assertEquals(0, $c->getStartTime());

        $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
        $kernel->expects($this->once())->method('getStartTime')->will($this->returnValue(123456));

        $c = new TimeDataCollector($kernel);
        $request = new Request();
        $request->server->set('REQUEST_TIME', 1);

        $c->collect($request, new Response());
        $this->assertEquals(123456000, $c->getStartTime());
    }
}
PKL1[���	�	WHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\ConfigDataCollector;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ConfigDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        $kernel = new KernelForTest('test', true);
        $c = new ConfigDataCollector();
        $c->setKernel($kernel);
        $c->collect(new Request(), new Response());

        $this->assertSame('test',$c->getEnv());
        $this->assertTrue($c->isDebug());
        $this->assertSame('config',$c->getName());
        $this->assertSame('testkernel',$c->getAppName());
        $this->assertSame(PHP_VERSION,$c->getPhpVersion());
        $this->assertSame(Kernel::VERSION,$c->getSymfonyVersion());
        $this->assertNull($c->getToken());

        // if else clause because we don't know it
        if (extension_loaded('xdebug')) {
            $this->assertTrue($c->hasXdebug());
        } else {
            $this->assertFalse($c->hasXdebug());
        }

        // if else clause because we don't know it
        if (((extension_loaded('eaccelerator') && ini_get('eaccelerator.enable'))
                ||
                (extension_loaded('apc') && ini_get('apc.enabled'))
                ||
                (extension_loaded('Zend OPcache') && ini_get('opcache.enable'))
                ||
                (extension_loaded('xcache') && ini_get('xcache.cacher'))
                ||
                (extension_loaded('wincache') && ini_get('wincache.ocenabled')))) {
            $this->assertTrue($c->hasAccelerator());
        } else {
            $this->assertFalse($c->hasAccelerator());
        }
    }
}

class KernelForTest extends Kernel
{
    public function getName()
    {
        return 'testkernel';
    }

    public function registerBundles()
    {
    }

    public function init()
    {
    }

    public function getBundles()
    {
        return array();
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
    }
}
PKL1[�}#��ZHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/ExceptionDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\ExceptionDataCollector;
use Symfony\Component\HttpKernel\Exception\FlattenException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ExceptionDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    public function testCollect()
    {
        $e = new \Exception('foo',500);
        $c = new ExceptionDataCollector();
        $flattened = FlattenException::create($e);
        $trace = $flattened->getTrace();

        $this->assertFalse($c->hasException());

        $c->collect(new Request(), new Response(),$e);

        $this->assertTrue($c->hasException());
        $this->assertEquals($flattened,$c->getException());
        $this->assertSame('foo',$c->getMessage());
        $this->assertSame(500,$c->getCode());
        $this->assertSame('exception',$c->getName());
        $this->assertSame($trace,$c->getTrace());
    }

}
PKL1[�J�֌�XHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\EventDispatcher\EventDispatcher;

class RequestDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider provider
     */
    public function testCollect(Request $request, Response $response)
    {
        $c = new RequestDataCollector();

        $c->collect($request, $response);

        $this->assertSame('request', $c->getName());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag', $c->getRequestHeaders());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestServer());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestCookies());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestAttributes());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestRequest());
        $this->assertInstanceOf('Symfony\Component\HttpFoundation\ParameterBag', $c->getRequestQuery());
        $this->assertSame('html', $c->getFormat());
        $this->assertSame('foobar', $c->getRoute());
        $this->assertSame(array('name' => 'foo'), $c->getRouteParams());
        $this->assertSame(array(), $c->getSessionAttributes());
        $this->assertSame('en', $c->getLocale());

        $this->assertInstanceOf('Symfony\Component\HttpFoundation\HeaderBag', $c->getResponseHeaders());
        $this->assertSame('OK', $c->getStatusText());
        $this->assertSame(200, $c->getStatusCode());
        $this->assertSame('application/json', $c->getContentType());
    }

    /**
     * Test various types of controller callables.
     *
     * @dataProvider provider
     */
    public function testControllerInspection(Request $request, Response $response)
    {
        // make sure we always match the line number
        $r1 = new \ReflectionMethod($this, 'testControllerInspection');
        $r2 = new \ReflectionMethod($this, 'staticControllerMethod');
        // test name, callable, expected
        $controllerTests = array(
            array(
                '"Regular" callable',
                array($this, 'testControllerInspection'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'testControllerInspection',
                    'file' => __FILE__,
                    'line' => $r1->getStartLine()
                ),
            ),

            array(
                'Closure',
                function () { return 'foo'; },
                array(
                    'class' => __NAMESPACE__.'\{closure}',
                    'method' => null,
                    'file' => __FILE__,
                    'line' => __LINE__ - 5,
                ),
            ),

            array(
                'Static callback as string',
                'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
                'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest::staticControllerMethod',
            ),

            array(
                'Static callable with instance',
                array($this, 'staticControllerMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'staticControllerMethod',
                    'file' => __FILE__,
                    'line' => $r2->getStartLine()
                ),
            ),

            array(
                'Static callable with class name',
                array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'staticControllerMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'staticControllerMethod',
                    'file' => __FILE__,
                    'line' => $r2->getStartLine()
                ),
            ),

            array(
                'Callable with instance depending on __call()',
                array($this, 'magicMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'magicMethod',
                    'file' => 'n/a',
                    'line' => 'n/a'
                ),
            ),

            array(
                'Callable with class name depending on __callStatic()',
                array('Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest', 'magicMethod'),
                array(
                    'class' => 'Symfony\Component\HttpKernel\Tests\DataCollector\RequestDataCollectorTest',
                    'method' => 'magicMethod',
                    'file' => 'n/a',
                    'line' => 'n/a'
                ),
            ),
        );

        $c = new RequestDataCollector();

        foreach ($controllerTests as $controllerTest) {
            $this->injectController($c, $controllerTest[1], $request);
            $c->collect($request, $response);
            $this->assertSame($controllerTest[2], $c->getController(), sprintf('Testing: %s', $controllerTest[0]));
        }
    }

    public function provider()
    {
        if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
            return array(array(null, null));
        }

        $request = Request::create('http://test.com/foo?bar=baz');
        $request->attributes->set('foo', 'bar');
        $request->attributes->set('_route', 'foobar');
        $request->attributes->set('_route_params', array('name' => 'foo'));

        $response = new Response();
        $response->setStatusCode(200);
        $response->headers->set('Content-Type', 'application/json');
        $response->headers->setCookie(new Cookie('foo','bar',1,'/foo','localhost',true,true));
        $response->headers->setCookie(new Cookie('bar','foo',new \DateTime('@946684800')));
        $response->headers->setCookie(new Cookie('bazz','foo','2000-12-12'));

        return array(
            array($request, $response)
        );
    }

    /**
     * Inject the given controller callable into the data collector.
     */
    protected function injectController($collector, $controller, $request)
    {
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $httpKernel = new HttpKernel(new EventDispatcher(), $resolver);
        $event = new FilterControllerEvent($httpKernel, $controller, $request, HttpKernelInterface::MASTER_REQUEST);
        $collector->onKernelController($event);
    }

    /**
     * Dummy method used as controller callable
     */
    public static function staticControllerMethod()
    {
        throw new \LogicException('Unexpected method call');
    }

    /**
     * Magic method to allow non existing methods to be called and delegated.
     */
    public function __call($method, $args)
    {
        throw new \LogicException('Unexpected method call');
    }

    /**
     * Magic method to allow non existing methods to be called and delegated.
     */
    public static function __callStatic($method, $args)
    {
        throw new \LogicException('Unexpected method call');
    }

}
PKL1[���i	i	WHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DataCollector;

use Symfony\Component\HttpKernel\DataCollector\LoggerDataCollector;
use Symfony\Component\HttpKernel\Debug\ErrorHandler;

class LoggerDataCollectorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getCollectTestData
     */
    public function testCollect($nb, $logs, $expectedLogs, $expectedDeprecationCount)
    {
        $logger = $this->getMock('Symfony\Component\HttpKernel\Log\DebugLoggerInterface');
        $logger->expects($this->once())->method('countErrors')->will($this->returnValue($nb));
        $logger->expects($this->exactly(2))->method('getLogs')->will($this->returnValue($logs));

        $c = new LoggerDataCollector($logger);
        $c->lateCollect();

        $this->assertSame('logger', $c->getName());
        $this->assertSame($nb, $c->countErrors());
        $this->assertSame($expectedLogs ? $expectedLogs : $logs, $c->getLogs());
        $this->assertSame($expectedDeprecationCount, $c->countDeprecations());
    }

    public function getCollectTestData()
    {
        return array(
            array(
                1,
                array(array('message' => 'foo', 'context' => array())),
                null,
                0
            ),
            array(
                1,
                array(array('message' => 'foo', 'context' => array('foo' => fopen(__FILE__, 'r')))),
                array(array('message' => 'foo', 'context' => array('foo' => 'Resource(stream)'))),
                0
            ),
            array(
                1,
                array(array('message' => 'foo', 'context' => array('foo' => new \stdClass()))),
                array(array('message' => 'foo', 'context' => array('foo' => 'Object(stdClass)'))),
                0
            ),
            array(
                1,
                array(
                    array('message' => 'foo', 'context' => array('type' => ErrorHandler::TYPE_DEPRECATION)),
                    array('message' => 'foo2', 'context' => array('type' => ErrorHandler::TYPE_DEPRECATION))
                ),
                null,
                2
            ),
        );
    }
}
PKL1[g�]�>*>*@HttpKernel/Symfony/Component/HttpKernel/Tests/HttpKernelTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests;

use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventDispatcher;

class HttpKernelTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \RuntimeException
     */
    public function testHandleWhenControllerThrowsAnExceptionAndRawIsTrue()
    {
        $kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));

        $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testHandleWhenControllerThrowsAnExceptionAndRawIsFalseAndNoListenerIsRegistered()
    {
        $kernel = new HttpKernel(new EventDispatcher(), $this->getResolver(function () { throw new \RuntimeException(); }));

        $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false);
    }

    public function testHandleWhenControllerThrowsAnExceptionAndRawIsFalse()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
            $event->setResponse(new Response($event->getException()->getMessage()));
        });

        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException('foo'); }));
        $response = $kernel->handle(new Request());

        $this->assertEquals('500', $response->getStatusCode());
        $this->assertEquals('foo', $response->getContent());
    }

    public function testHandleExceptionWithARedirectionResponse()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
            $event->setResponse(new RedirectResponse('/login', 301));
        });

        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new AccessDeniedHttpException(); }));
        $response = $kernel->handle(new Request());

        $this->assertEquals('301', $response->getStatusCode());
        $this->assertEquals('/login', $response->headers->get('Location'));
    }

    public function testHandleHttpException()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) {
            $event->setResponse(new Response($event->getException()->getMessage()));
        });

        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new MethodNotAllowedHttpException(array('POST')); }));
        $response = $kernel->handle(new Request());

        $this->assertEquals('405', $response->getStatusCode());
        $this->assertEquals('POST', $response->headers->get('Allow'));
    }

    /**
     * @dataProvider getStatusCodes
     */
    public function testHandleWhenAnExceptionIsHandledWithASpecificStatusCode($responseStatusCode, $expectedStatusCode)
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::EXCEPTION, function ($event) use ($responseStatusCode, $expectedStatusCode) {
            $event->setResponse(new Response('', $responseStatusCode, array('X-Status-Code' => $expectedStatusCode)));
        });

        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { throw new \RuntimeException(); }));
        $response = $kernel->handle(new Request());

        $this->assertEquals($expectedStatusCode, $response->getStatusCode());
        $this->assertFalse($response->headers->has('X-Status-Code'));
    }

    public function getStatusCodes()
    {
        return array(
            array(200, 404),
            array(404, 200),
            array(301, 200),
            array(500, 200),
        );
    }

    public function testHandleWhenAListenerReturnsAResponse()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::REQUEST, function ($event) {
            $event->setResponse(new Response('hello'));
        });

        $kernel = new HttpKernel($dispatcher, $this->getResolver());

        $this->assertEquals('hello', $kernel->handle(new Request())->getContent());
    }

    /**
     * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
     */
    public function testHandleWhenNoControllerIsFound()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(false));

        $kernel->handle(new Request());
    }

    /**
     * @expectedException \LogicException
     */
    public function testHandleWhenTheControllerIsNotACallable()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver('foobar'));

        $kernel->handle(new Request());
    }

    public function testHandleWhenTheControllerIsAClosure()
    {
        $response = new Response('foo');
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () use ($response) { return $response; }));

        $this->assertSame($response, $kernel->handle(new Request()));
    }

    public function testHandleWhenTheControllerIsAnObjectWithInvoke()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(new Controller()));

        $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
    }

    public function testHandleWhenTheControllerIsAFunction()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver('Symfony\Component\HttpKernel\Tests\controller_func'));

        $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
    }

    public function testHandleWhenTheControllerIsAnArray()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(array(new Controller(), 'controller')));

        $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
    }

    public function testHandleWhenTheControllerIsAStaticArray()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(array('Symfony\Component\HttpKernel\Tests\Controller', 'staticcontroller')));

        $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request()));
    }

    /**
     * @expectedException \LogicException
     */
    public function testHandleWhenTheControllerDoesNotReturnAResponse()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));

        $kernel->handle(new Request());
    }

    public function testHandleWhenTheControllerDoesNotReturnAResponseButAViewIsRegistered()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::VIEW, function ($event) {
            $event->setResponse(new Response($event->getControllerResult()));
        });
        $kernel = new HttpKernel($dispatcher, $this->getResolver(function () { return 'foo'; }));

        $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
    }

    public function testHandleWithAResponseListener()
    {
        $dispatcher = new EventDispatcher();
        $dispatcher->addListener(KernelEvents::RESPONSE, function ($event) {
            $event->setResponse(new Response('foo'));
        });
        $kernel = new HttpKernel($dispatcher, $this->getResolver());

        $this->assertEquals('foo', $kernel->handle(new Request())->getContent());
    }

    public function testTerminate()
    {
        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver());
        $dispatcher->addListener(KernelEvents::TERMINATE, function ($event) use (&$called, &$capturedKernel, &$capturedRequest, &$capturedResponse) {
            $called = true;
            $capturedKernel = $event->getKernel();
            $capturedRequest = $event->getRequest();
            $capturedResponse = $event->getResponse();
        });

        $kernel->terminate($request = Request::create('/'), $response = new Response());
        $this->assertTrue($called);
        $this->assertEquals($kernel, $capturedKernel);
        $this->assertEquals($request, $capturedRequest);
        $this->assertEquals($response, $capturedResponse);
    }

    public function testVerifyRequestStackPushPopDuringHandle()
    {
        $request = new Request();

        $stack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('push', 'pop'));
        $stack->expects($this->at(0))->method('push')->with($this->equalTo($request));
        $stack->expects($this->at(1))->method('pop');

        $dispatcher = new EventDispatcher();
        $kernel = new HttpKernel($dispatcher, $this->getResolver(), $stack);

        $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST);
    }

    protected function getResolver($controller = null)
    {
        if (null === $controller) {
            $controller = function () { return new Response('Hello'); };
        }

        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $resolver->expects($this->any())
            ->method('getController')
            ->will($this->returnValue($controller));
        $resolver->expects($this->any())
            ->method('getArguments')
            ->will($this->returnValue(array()));

        return $resolver;
    }

    protected function assertResponseEquals(Response $expected, Response $actual)
    {
        $expected->setDate($actual->getDate());
        $this->assertEquals($expected, $actual);
    }
}

class Controller
{
    public function __invoke()
    {
        return new Response('foo');
    }

    public function controller()
    {
        return new Response('foo');
    }

    public static function staticController()
    {
        return new Response('foo');
    }
}

function controller_func()
{
    return new Response('foo');
}
PKL1[z*V%%SHttpKernel/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\Controller;

use Symfony\Component\HttpKernel\Controller\ControllerResolver;
use Symfony\Component\HttpKernel\Tests\Logger;
use Symfony\Component\HttpFoundation\Request;

class ControllerResolverTest extends \PHPUnit_Framework_TestCase
{
    public function testGetControllerWithoutControllerParameter()
    {
        $logger = $this->getMock('Psr\Log\LoggerInterface');
        $logger->expects($this->once())->method('warning')->with('Unable to look for the controller as the "_controller" parameter is missing');
        $resolver = new ControllerResolver($logger);

        $request = Request::create('/');
        $this->assertFalse($resolver->getController($request), '->getController() returns false when the request has no _controller attribute');
    }

    public function testGetControllerWithLambda()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', $lambda = function () {});
        $controller = $resolver->getController($request);
        $this->assertSame($lambda, $controller);
    }

    public function testGetControllerWithObjectAndInvokeMethod()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', $this);
        $controller = $resolver->getController($request);
        $this->assertSame($this, $controller);
    }

    public function testGetControllerWithObjectAndMethod()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', array($this, 'controllerMethod1'));
        $controller = $resolver->getController($request);
        $this->assertSame(array($this, 'controllerMethod1'), $controller);
    }

    public function testGetControllerWithClassAndMethod()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'));
        $controller = $resolver->getController($request);
        $this->assertSame(array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', 'controllerMethod4'), $controller);
    }

    public function testGetControllerWithObjectAndMethodAsString()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::controllerMethod1');
        $controller = $resolver->getController($request);
        $this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller[0], '->getController() returns a PHP callable');
    }

    public function testGetControllerWithClassAndInvokeMethod()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest');
        $controller = $resolver->getController($request);
        $this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller);
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testGetControllerOnObjectWithoutInvokeMethod()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', new \stdClass());
        $resolver->getController($request);
    }

    public function testGetControllerWithFunction()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function');
        $controller = $resolver->getController($request);
        $this->assertSame('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function', $controller);
    }

    /**
     * @dataProvider      getUndefinedControllers
     * @expectedException \InvalidArgumentException
     */
    public function testGetControllerOnNonUndefinedFunction($controller)
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $request->attributes->set('_controller', $controller);
        $resolver->getController($request);
    }

    public function getUndefinedControllers()
    {
        return array(
            array('foo'),
            array('foo::bar'),
            array('stdClass'),
            array('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest::bar'),
        );
    }

    public function testGetArguments()
    {
        $resolver = new ControllerResolver();

        $request = Request::create('/');
        $controller = array(new self(), 'testGetArguments');
        $this->assertEquals(array(), $resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $controller = array(new self(), 'controllerMethod1');
        $this->assertEquals(array('foo'), $resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $controller = array(new self(), 'controllerMethod2');
        $this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller), '->getArguments() uses default values if present');

        $request->attributes->set('bar', 'bar');
        $this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $controller = function ($foo) {};
        $this->assertEquals(array('foo'), $resolver->getArguments($request, $controller));

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $controller = function ($foo, $bar = 'bar') {};
        $this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $controller = new self();
        $this->assertEquals(array('foo', null), $resolver->getArguments($request, $controller));
        $request->attributes->set('bar', 'bar');
        $this->assertEquals(array('foo', 'bar'), $resolver->getArguments($request, $controller));

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $request->attributes->set('foobar', 'foobar');
        $controller = 'Symfony\Component\HttpKernel\Tests\Controller\some_controller_function';
        $this->assertEquals(array('foo', 'foobar'), $resolver->getArguments($request, $controller));

        $request = Request::create('/');
        $request->attributes->set('foo', 'foo');
        $request->attributes->set('foobar', 'foobar');
        $controller = array(new self(), 'controllerMethod3');

        if (version_compare(PHP_VERSION, '5.3.16', '==')) {
            $this->markTestSkipped('PHP 5.3.16 has a major bug in the Reflection sub-system');
        } else {
            try {
                $resolver->getArguments($request, $controller);
                $this->fail('->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
            } catch (\Exception $e) {
                $this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
            }
        }

        $request = Request::create('/');
        $controller = array(new self(), 'controllerMethod5');
        $this->assertEquals(array($request), $resolver->getArguments($request, $controller), '->getArguments() injects the request');
    }

    public function testCreateControllerCanReturnAnyCallable()
    {
        $mock = $this->getMock('Symfony\Component\HttpKernel\Controller\ControllerResolver', array('createController'));
        $mock->expects($this->once())->method('createController')->will($this->returnValue('Symfony\Component\HttpKernel\Tests\Controller\some_controller_function'));

        $request = Request::create('/');
        $request->attributes->set('_controller', 'foobar');
        $mock->getController($request);
    }

    public function __invoke($foo, $bar = null)
    {
    }

    public function controllerMethod1($foo)
    {
    }

    protected function controllerMethod2($foo, $bar = null)
    {
    }

    protected function controllerMethod3($foo, $bar = null, $foobar)
    {
    }

    protected static function controllerMethod4()
    {
    }

    protected function controllerMethod5(Request $request)
    {
    }
}

function some_controller_function($foo, $foobar)
{
}
PKL1[e�
֮�iHttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/MergeExtensionConfigurationPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\MergeExtensionConfigurationPass;

class MergeExtensionConfigurationPassTest extends \PHPUnit_Framework_TestCase
{
    public function testAutoloadMainExtension()
    {
        $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerBuilder');
        $params = $this->getMock('Symfony\\Component\\DependencyInjection\\ParameterBag\\ParameterBag');

        $container->expects($this->at(0))
            ->method('getExtensionConfig')
            ->with('loaded')
            ->will($this->returnValue(array(array())));
        $container->expects($this->at(1))
            ->method('getExtensionConfig')
            ->with('notloaded')
            ->will($this->returnValue(array()));
        $container->expects($this->once())
            ->method('loadFromExtension')
            ->with('notloaded', array());

        $container->expects($this->any())
            ->method('getParameterBag')
            ->will($this->returnValue($params));
        $params->expects($this->any())
            ->method('all')
            ->will($this->returnValue(array()));
        $container->expects($this->any())
            ->method('getDefinitions')
            ->will($this->returnValue(array()));
        $container->expects($this->any())
            ->method('getAliases')
            ->will($this->returnValue(array()));
        $container->expects($this->any())
            ->method('getExtensions')
            ->will($this->returnValue(array()));

        $configPass = new MergeExtensionConfigurationPass(array('loaded', 'notloaded'));
        $configPass->process($container);
    }
}
PKL1[V���^^_HttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterListenersPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\DependencyInjection\RegisterListenersPass;

class RegisterListenersPassTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Tests that event subscribers not implementing EventSubscriberInterface
     * trigger an exception.
     *
     * @expectedException \InvalidArgumentException
     */
    public function testEventSubscriberWithoutInterface()
    {
        // one service, not implementing any interface
        $services = array(
            'my_event_subscriber' => array(0 => array()),
        );

        $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
        $definition->expects($this->atLeastOnce())
            ->method('isPublic')
            ->will($this->returnValue(true));
        $definition->expects($this->atLeastOnce())
            ->method('getClass')
            ->will($this->returnValue('stdClass'));

        $builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $builder->expects($this->any())
            ->method('hasDefinition')
            ->will($this->returnValue(true));

        // We don't test kernel.event_listener here
        $builder->expects($this->atLeastOnce())
            ->method('findTaggedServiceIds')
            ->will($this->onConsecutiveCalls(array(), $services));

        $builder->expects($this->atLeastOnce())
            ->method('getDefinition')
            ->will($this->returnValue($definition));

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($builder);
    }

    public function testValidEventSubscriber()
    {
        $services = array(
            'my_event_subscriber' => array(0 => array()),
        );

        $definition = $this->getMock('Symfony\Component\DependencyInjection\Definition');
        $definition->expects($this->atLeastOnce())
            ->method('isPublic')
            ->will($this->returnValue(true));
        $definition->expects($this->atLeastOnce())
            ->method('getClass')
            ->will($this->returnValue('Symfony\Component\HttpKernel\Tests\DependencyInjection\SubscriberService'));

        $builder = $this->getMock('Symfony\Component\DependencyInjection\ContainerBuilder');
        $builder->expects($this->any())
            ->method('hasDefinition')
            ->will($this->returnValue(true));

        // We don't test kernel.event_listener here
        $builder->expects($this->atLeastOnce())
            ->method('findTaggedServiceIds')
            ->will($this->onConsecutiveCalls(array(), $services));

        $builder->expects($this->atLeastOnce())
            ->method('getDefinition')
            ->will($this->returnValue($definition));

        $builder->expects($this->atLeastOnce())
            ->method('findDefinition')
            ->will($this->returnValue($definition));

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($builder);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must be public as event listeners are lazy-loaded.
     */
    public function testPrivateEventListener()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_listener', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must be public as event subscribers are lazy-loaded.
     */
    public function testPrivateEventSubscriber()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setPublic(false)->addTag('kernel.event_subscriber', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage The service "foo" must not be abstract as event listeners are lazy-loaded.
     */
    public function testAbstractEventListener()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', array());
        $container->register('event_dispatcher', 'stdClass');

        $registerListenersPass = new RegisterListenersPass();
        $registerListenersPass->process($container);
    }
}

class SubscriberService implements \Symfony\Component\EventDispatcher\EventSubscriberInterface
{
    public static function getSubscribedEvents() {}
}
PKL1[�C�hhbHttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\HttpKernel\Tests\DependencyInjection;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcher;

class ContainerAwareHttpKernelTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getProviderTypes
     */
    public function testHandle($type)
    {
        $request = new Request();
        $expected = new Response();
        $controller = function () use ($expected) {
            return $expected;
        };

        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $this
            ->expectsEnterScopeOnce($container)
            ->expectsLeaveScopeOnce($container)
            ->expectsSetRequestWithAt($container, $request, 3)
            ->expectsSetRequestWithAt($container, null, 4)
        ;

        $dispatcher = new EventDispatcher();
        $resolver = $this->getResolverMockFor($controller, $request);
        $stack = new RequestStack();
        $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack);

        $actual = $kernel->handle($request, $type);

        $this->assertSame($expected, $actual, '->handle() returns the response');
    }

    /**
     * @dataProvider getProviderTypes
     */
    public function testVerifyRequestStackPushPopDuringHandle($type)
    {
        $request = new Request();
        $expected = new Response();
        $controller = function () use ($expected) {
            return $expected;
        };

        $stack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack', array('push', 'pop'));
        $stack->expects($this->at(0))->method('push')->with($this->equalTo($request));
        $stack->expects($this->at(1))->method('pop');

        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $dispatcher = new EventDispatcher();
        $resolver = $this->getResolverMockFor($controller, $request);
        $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack);

        $kernel->handle($request, $type);
    }

    /**
     * @dataProvider getProviderTypes
     */
    public function testHandleRestoresThePreviousRequestOnException($type)
    {
        $request = new Request();
        $expected = new \Exception();
        $controller = function () use ($expected) {
            throw $expected;
        };

        $container = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $this
            ->expectsEnterScopeOnce($container)
            ->expectsLeaveScopeOnce($container)
            ->expectsSetRequestWithAt($container, $request, 3)
            ->expectsSetRequestWithAt($container, null, 4)
        ;

        $dispatcher = new EventDispatcher();
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $resolver = $this->getResolverMockFor($controller, $request);
        $stack = new RequestStack();
        $kernel = new ContainerAwareHttpKernel($dispatcher, $container, $resolver, $stack);

        try {
            $kernel->handle($request, $type);
            $this->fail('->handle() suppresses the controller exception');
        } catch (\PHPUnit_Framework_Exception $exception) {
            throw $exception;
        } catch (\Exception $actual) {
            $this->assertSame($expected, $actual, '->handle() throws the controller exception');
        }
    }

    public function getProviderTypes()
    {
        return array(
            array(HttpKernelInterface::MASTER_REQUEST),
            array(HttpKernelInterface::SUB_REQUEST),
        );
    }

    private function getResolverMockFor($controller, $request)
    {
        $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface');
        $resolver->expects($this->once())
            ->method('getController')
            ->with($request)
            ->will($this->returnValue($controller));
        $resolver->expects($this->once())
            ->method('getArguments')
            ->with($request, $controller)
            ->will($this->returnValue(array()));

        return $resolver;
    }

    private function expectsSetRequestWithAt($container, $with, $at)
    {
        $container
            ->expects($this->at($at))
            ->method('set')
            ->with($this->equalTo('request'), $this->equalTo($with), $this->equalTo('request'))
        ;

        return $this;
    }

    private function expectsEnterScopeOnce($container)
    {
        $container
            ->expects($this->once())
            ->method('enterScope')
            ->with($this->equalTo('request'))
        ;

        return $this;
    }

    private function expectsLeaveScopeOnce($container)
    {
        $container
            ->expects($this->once())
            ->method('leaveScope')
            ->with($this->equalTo('request'))
        ;

        return $this;
    }
}
PKL1[��x998HttpKernel/Symfony/Component/HttpKernel/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony HttpKernel Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKL1[;�{��"Mail_Mime/tests/test_Bug_GH19.phptnu�[���--TEST--
Bug GH-19  Test boundary value with different headers()/get() call order
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

// Test get() before headers()

$mime = new Mail_mime("\r\n");
$mime->setHTMLBody('html');
$mime->setTXTBody('text');

$body = $mime->get();
$hdrs = $mime->headers(array(
        'From'    => 'test@domain.tld',
        'Subject' => 'Subject',
        'To'      => 'to@domain.tld'
));

preg_match('/boundary="([^"]+)/', $hdrs['Content-Type'], $matches);
$boundary = $matches[1];

echo substr_count($body, "--$boundary") . "\n";

// Test headers() before get()

$mime = new Mail_mime("\r\n");
$mime->setHTMLBody('html');
$mime->setTXTBody('text');

$hdrs = $mime->headers(array(
        'From'    => 'test@domain.tld',
        'Subject' => 'Subject',
        'To'      => 'to@domain.tld'
));
$body = $mime->get();

preg_match('/boundary="([^"]+)/', $hdrs['Content-Type'], $matches);
$boundary = $matches[1];

echo substr_count($body, "--$boundary");
--EXPECT--
3
3
PKL1[�E�oo#Mail_Mime/tests/test_Bug_13962.phptnu�[���--TEST--
Bug #13962  Multiple header support
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$mime = new Mail_mime();

$mime->setFrom('user@from.example.com');
$r = $mime->txtHeaders(array('Received' => array('Received 1', 'Received 2')));

print_r($r); 
?>
--EXPECT--
Received: Received 1
Received: Received 2
MIME-Version: 1.0
From: user@from.example.com
PKL1[Ԣ��``#Mail_Mime/tests/test_Bug_21255.phptnu�[���--TEST--
Bug #21255  Boundary gets added twice
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$mime = new Mail_mime("\r\n");
$mime->setHTMLBody('html');
$mime->setTXTBody('text');
$mime->setContentType('multipart/alternative', array('boundary' => 'something'));

$msg = $mime->getMessage();

echo substr_count($msg, 'boundary=');

?>
--EXPECT--
1
PKL1[i;���$Mail_Mime/tests/test_Bug_7561_1.phptnu�[���--TEST--
Bug #7561   Mail_mimePart::quotedPrintableEncode() misbehavior with mbstring overload
--INI--
mbstring.language=Neutral
mbstring.func_overload=6
mbstring.internal_encoding=UTF-8
mbstring.http_output=UTF-8
--SKIPIF--
<?php
include "PEAR.php";
if (!extension_loaded('mbstring')){
    if (!PEAR::loadExtension('mbstring')){
        print('SKIP could not load mbstring module');
    }
}
--FILE--
<?php
include("Mail/mimePart.php");
// string is UTF-8 encoded
$input = "Micha\xC3\xABl \xC3\x89ric St\xC3\xA9phane";
$rv = Mail_mimePart::quotedPrintableEncode($input, 76, "\n");
echo $rv, "\n";
--EXPECT--
Micha=C3=ABl =C3=89ric St=C3=A9phane
PKL1[e;�I#Mail_Mime/tests/test_Bug_21205.phptnu�[���--TEST--
Bug #21205  Handling ISO-2022-JP headers
--SKIPIF--
<?php
include "PEAR.php";
if (!extension_loaded('mbstring')) {
    if (!PEAR::loadExtension('mbstring')) {
        print('SKIP could not load mbstring module');
    }
}
--FILE--
<?php
require_once('Mail/mimePart.php');
$tests = array(
    '□京都府□',
    '∠∠∠∠',
);
$addr = ' <aaa@bbb.ccc>';
$charset = 'ISO-2022-JP';
$encoding = 'base64';
foreach ($tests as $test) {
    $test = mb_convert_encoding($test, $charset, 'UTF-8');
    print Mail_mimePart::encodeHeader("subject", $test,       $charset, $encoding) . PHP_EOL;
    print Mail_mimePart::encodeHeader("to",      $test.$addr, $charset, $encoding) . PHP_EOL;
    $test = '"' . $test . '"';
    print Mail_mimePart::encodeHeader("subject", $test,       $charset, $encoding) . PHP_EOL;
    print Mail_mimePart::encodeHeader("to",      $test.$addr, $charset, $encoding) . PHP_EOL;
}
?>
--EXPECT--
=?ISO-2022-JP?B?GyRCIiI1fkVUSVwiIhsoQg==?=
=?ISO-2022-JP?B?GyRCIiI1fkVUSVwiIhsoQg==?= <aaa@bbb.ccc>
=?ISO-2022-JP?B?GyRCIiI1fkVUSVwiIhsoQg==?=
=?ISO-2022-JP?B?GyRCIiI1fkVUSVwiIhsoQg==?= <aaa@bbb.ccc>
=?ISO-2022-JP?B?GyRCIlwiXCJcIlwbKEI=?=
=?ISO-2022-JP?B?GyRCIlwiXCJcIlwbKEI=?= <aaa@bbb.ccc>
=?ISO-2022-JP?B?GyRCIlwiXCJcIlwbKEI=?=
=?ISO-2022-JP?B?GyRCIlwiXCJcIlwbKEI=?= <aaa@bbb.ccc>
PKL1[Y�����"Mail_Mime/tests/test_Bug_GH26.phptnu�[���--TEST--
Bug GH-26  Backward slash is getting added in headers
--SKIPIF--
--FILE--
<?php

require_once('Mail/mime.php');

$mail_mime = new Mail_mime("\n");

$from = '"George B@@Z"<george@cort.org.au>';
$to = <<<EOT
"austin test"<austinn@cort.org>,<reno@cort.org>,t@mail.com
EOT;
$subject = "Test mime";
$mailbody = "hello world";

$mail_mime->setTxtBody($mailbody);
$mail_mime->setHTMLBody($mailbody);
$mail_mime->setSubject($subject);
$mail_mime->setFrom($from);

$body = $mail_mime->get();

$extra_headers = array();
$extra_headers["To"] = $to;

$arr_hdrs = $mail_mime->headers($extra_headers);

echo $arr_hdrs['From'] . "\n" . $arr_hdrs['To'];

--EXPECT--
"George B@@Z" <george@cort.org.au>
"austin test" <austinn@cort.org>, <reno@cort.org>, t@mail.comPKL1[��RoUU#Mail_Mime/tests/test_Bug_20226.phptnu�[���--TEST--
Bug #20226  Mail_mimePart::encodeHeader() and ISO-2022-JP encoding
--SKIPIF--
--FILE--
<?php
include("Mail/mimePart.php");

$subject = base64_decode("GyRCJT8lJCVIJWsbKEI=");
$mime    = new Mail_mimePart();

echo $mime->encodeHeader('subject', $subject, 'ISO-2022-JP', 'base64');
?>
--EXPECT--
=?ISO-2022-JP?B?GyRCJT8lJCVIJWsbKEI=?=
PKM1[g��+��#Mail_Mime/tests/test_Bug_13444.phptnu�[���--TEST--
Bug #9725   multipart/related & alternative wrong order
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$mime = new Mail_mime();
$mime->setTXTBody("test");
$mime->setHTMLBody("test");
$mime->addHTMLImage("test", 'application/octet-stream', '', false);
$body = $mime->get();
$head = $mime->headers();
$headCT = $head['Content-Type'];
$headCT = explode(";", $headCT);
$headCT = $headCT[0];

$ct = preg_match_all('|Content-Type: ([^;\r\n]+)|', $body, $matches);
print($headCT);
print("\n");
foreach ($matches[1] as $match){
    print($match);
    print("\n");
}
--EXPECT--
multipart/alternative
text/plain
multipart/related
text/html
application/octet-stream
PKM1[%��BB"Mail_Mime/tests/test_Bug_GH16.phptnu�[���--TEST--
Bug GH-16  Test methods that write to a file
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$mime = new Mail_mime("\r\n");
$mime->setHTMLBody('html');
$mime->setTXTBody('text');
$mime->setContentType('multipart/alternative', array('boundary' => 'something'));

$temp_filename = dirname(__FILE__) . "/output1.tmp";
touch($temp_filename);
$msg = $mime->saveMessageBody($temp_filename);
echo file_get_contents($temp_filename);

$temp_filename = dirname(__FILE__) . "/output2.tmp";
touch($temp_filename);
$msg = $mime->saveMessage($temp_filename);
echo file_get_contents($temp_filename);

$temp_filename = dirname(__FILE__) . "/output3.tmp";
$mimePart = new Mail_mimePart('abc', array(
        'content_type' => 'text/plain',
        'encoding'     => 'quoted-printable',
));
$mimePart->encodeToFile($temp_filename);
echo file_get_contents($temp_filename);

?>
--CLEAN--
<?php
    for ($i = 1; $i < 4; $i++) {
        @unlink(dirname(__FILE__) . "/output{$i}.tmp");
    }
?>
--EXPECT--
--something
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=ISO-8859-1

text
--something
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=ISO-8859-1

html
--something--
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="something"

--something
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=ISO-8859-1

text
--something
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=ISO-8859-1

html
--something--
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain

abc
PKM1[�-7c77$Mail_Mime/tests/test_Bug_3513_2.phptnu�[���--TEST--
Bug #3513   Support of RFC2231 in header fields. (UTF-8)
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$test = "Süper gröse tolle tolle grüße.txt";
$Mime = new Mail_Mime();
$Mime->addAttachment('testfile',"text/plain", $test, FALSE, 'base64', 'attachment', 'UTF-8', 'de');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match_all('/filename([^\s]+)/i', $content, $matches)) {
    echo implode("\n", $matches[1]);
}

--EXPECT--
*0*=UTF-8'de'S%C3%BCper%20gr%C3%B6se%20tolle%20tolle%20gr%C3%BC;
*1*=%C3%9Fe.txt;
PKM1[�(V,��#Mail_Mime/tests/test_Bug_12411.phptnu�[���--TEST--
Bug #12411  RFC2047 encoded attachment filenames
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";
$Mime = new Mail_mime();

// some text with polish Unicode letter at the beginning
$filename = base64_decode("xZtjaWVtYQ==");
$Mime->addAttachment('testfile', "text/plain", $filename, FALSE,
    'base64', 'attachment', 'ISO-8859-1', 'pl', '',
    'quoted-printable', 'base64');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match_all('/(name|filename)=([^\s]+)/i', $content, $matches)) {
    echo implode("\n", $matches[2]);
}

?>
--EXPECT--
"=?ISO-8859-1?Q?=C5=9Bciema?="
"=?ISO-8859-1?B?xZtjaWVtYQ==?=";
PKM1[��qS��%Mail_Mime/tests/test_Bug_10999_1.phptnu�[���--TEST--
Bug #10999  Bad Content-ID(cid) format
--SKIPIF--
--FILE--
<?php
$from='user@from.example.com';

require_once('Mail/mime.php');

$mime=new Mail_mime();

$body='<img src="test.gif"/>';

$mime->setHTMLBody($body);
$mime->setFrom($from);
$mime->addHTMLImage('','image/gif', 'test.gif', false);
$msg=$mime->get();

$header = preg_match('|Content-ID: <[0-9a-fA-F]+@from.example.com>|', $msg);
if (!$header){
    print("FAIL:\n");
    print($msg);
}else{
    print("OK");
}
--EXPECT--
OK
PKM1[29r���"Mail_Mime/tests/encoding_case.phptnu�[���--TEST--
Bug #2364   Tabs in Mail_mimePart::quotedPrintableEncode()
--SKIPIF--
--FILE--
<?php
$test = "Here's\t\na tab\n";
require_once('Mail/mimePart.php');
print Mail_mimePart::quotedPrintableEncode($test, 7);
?>
--EXPECT--
Here's=
=09
a tab
PKM1[M�-\��#Mail_Mime/tests/test_Bug_17175.phptnu�[���--TEST--
Bug #17175  Content-Description support+ecoding
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$Mime = new Mail_Mime();
$Mime->setTXTBody('Test message.');
$Mime->addAttachment('test file contents', "text/plain",
    'test.txt', FALSE, 'base64', NULL, 'UTF-8', NULL, NULL, NULL, NULL,
    'desc');
$Mime->addAttachment('test file contents', "text/plain",
    'test2.txt', FALSE, 'base64', NULL, 'UTF-8', NULL, NULL, NULL, NULL,
    'test unicode żąśź');

$body = $Mime->getMessage();
preg_match_all('/Content-Description: (.*)/', $body, $matches);
foreach ($matches[1] as $value)
    echo $value."\n";
?>
--EXPECT--
desc
=?UTF-8?Q?test_unicode_=C5=BC=C4=85=C5=9B=C5=BA?=
PKM1[ّB�
�
%Mail_Mime/tests/qp_encoding_test.phptnu�[���--TEST--
qp comprehensive test
--SKIPIF--
--FILE--
<?php
error_reporting(E_ALL); // ignore E_STRICT

include("Mail/mimePart.php");

/**
 * Convenience function to make qp encoded output easier to verify
 *
 * @param string $text Input text to be encoded and printed
 * @param int $begin Start character to visibly print from
 * @param int $end Stop character to visibly print to
 * @param bool $special_chars Convert character such as linebreaks
 *     etc. to visible replacements.
 * @param int $break Line length before soft break
 *
 */
function debug_print($text, $begin=False, $end=False, $special_chars=True, $break=76) {
    $begin = $begin ? $begin : strlen($text);
    $end = $end ? $end : strlen($text);

    for ($i=$begin; $i <= $end; $i++) {
        $input = substr($text, 0, $i);
        $output = Mail_mimePart::quotedPrintableEncode($input, $break);

        if ($special_chars) {
            $input_vis = str_replace("\t", '\t', str_replace("\n", '\n', str_replace("\r", '\r', $input)));
        } else {
            $input_vis = $input;
        }
        printf("input: %02d: %s\n", strlen($input), $input_vis);

        $lines = explode("\r\n", $output);
        for($j=0; $j < count($lines); $j++) {
            $line = $lines[$j];
            if ($j + 1 < count($lines) && $special_chars) {
                $line_vis = str_replace("\t", '\t', $line).'\r\n';
            } else {
                $line_vis = $line;
            }
            printf("output:%02d: %s\n", strlen($line), $line_vis);
        }
        print("---\n");
    }
}

// Test linebreaks on regular long lines
$text = '12345678901234567890123456789012345678901234567890123456789012345678901234567890';
debug_print($text, 74);

// Test linebreaks on long line with dot at end.
$text = '123456789.12';
debug_print($text, 10, False, False, 10);

$text = "\tHere's\t\na tab.\n";
debug_print($text, False, False, True, 8);

--EXPECT--
input: 74: 12345678901234567890123456789012345678901234567890123456789012345678901234
output:74: 12345678901234567890123456789012345678901234567890123456789012345678901234
---
input: 75: 123456789012345678901234567890123456789012345678901234567890123456789012345
output:75: 123456789012345678901234567890123456789012345678901234567890123456789012345
---
input: 76: 1234567890123456789012345678901234567890123456789012345678901234567890123456
output:76: 1234567890123456789012345678901234567890123456789012345678901234567890123456
---
input: 77: 12345678901234567890123456789012345678901234567890123456789012345678901234567
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:02: 67
---
input: 78: 123456789012345678901234567890123456789012345678901234567890123456789012345678
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:03: 678
---
input: 79: 1234567890123456789012345678901234567890123456789012345678901234567890123456789
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:04: 6789
---
input: 80: 12345678901234567890123456789012345678901234567890123456789012345678901234567890
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:05: 67890
---
input: 10: 123456789.
output:10: 123456789.
---
input: 11: 123456789.1
output:10: 123456789=
output:04: =2E1
---
input: 12: 123456789.12
output:10: 123456789=
output:05: =2E12
---
input: 16: \tHere's\t\na tab.\n
output:08: \tHere's=\r\n
output:03: =09\r\n
output:06: a tab.\r\n
output:00: 
---
PKM1[)#��pp#Mail_Mime/tests/test_Bug_18772.phptnu�[���--TEST--
Bug #18772  Text/calendar message
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$mime = new Mail_mime;
$mime->setSubject('test');

// A message with text/calendar only
$mime->setCalendarBody('VCALENDAR');

echo $mime->getMessage();
echo "\n---\n";

// A message with alternative text
$mime->setTXTBody('vcalendar');
$msg = $mime->getMessage();

echo preg_replace('/=_[0-9a-z]+/', '*', $msg);
--EXPECT--
MIME-Version: 1.0
Subject: test
Content-Type: text/calendar; charset=UTF-8; method=request
Content-Transfer-Encoding: quoted-printable

VCALENDAR
---
MIME-Version: 1.0
Subject: test
Content-Type: multipart/alternative;
 boundary="*"

--*
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=ISO-8859-1

vcalendar
--*
Content-Transfer-Encoding: quoted-printable
Content-Type: text/calendar; method=request; charset=UTF-8

VCALENDAR
--*--
PKM1[2!�B��'Mail_Mime/tests/test_linebreak_dot.phptnu�[���--TEST--
Test for correct "." encoding when doing linebreaks
--SKIPIF--
--FILE--
<?php
error_reporting(E_ALL); // ignore E_STRICT
include("Mail/mime.php");
$text     = '0123456789012345678901234567890123456789012345678901234567890123456789012...6';
$params   = Array(
    'content_type' => 'text/plain',
    'encoding'     => 'quoted-printable',
);

for ($i=74; $i <= strlen($text); $i++) {
    $input = substr($text, 0, $i);
    $mimePart = new Mail_mimePart($input, $params);
    $encoded  =  $mimePart->encode();
    $output = $encoded['body'];
    printf("input: %02d: %s\n", strlen($input), $input);

    $lines = explode("\r\n", $output);
    for($j=0; $j < count($lines); $j++) {
        $line = $lines[$j];
        if ($j + 1 < count($lines)) {
            $line_vis = $line.'\r\n';
        } else {
            $line_vis = $line;
        }
        printf("output:%02d: %s\n", strlen($line), $line_vis);
    }

    print("---\n");

}
--EXPECT--
input: 74: 0123456789012345678901234567890123456789012345678901234567890123456789012.
output:74: 0123456789012345678901234567890123456789012345678901234567890123456789012.
---
input: 75: 0123456789012345678901234567890123456789012345678901234567890123456789012..
output:75: 0123456789012345678901234567890123456789012345678901234567890123456789012..
---
input: 76: 0123456789012345678901234567890123456789012345678901234567890123456789012...
output:76: 0123456789012345678901234567890123456789012345678901234567890123456789012...
---
input: 77: 0123456789012345678901234567890123456789012345678901234567890123456789012...6
output:76: 0123456789012345678901234567890123456789012345678901234567890123456789012..=\r\n
output:04: =2E6
---
PKM1[B&���#Mail_Mime/tests/test_Bug_12466.phptnu�[���--TEST--
Bug #12466  Content-Transfer-Encoding checking
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$params = array(
    'text_encoding' => '7bit',
    'html_encoding' => '7bit',
);
$mime = new Mail_mime($params);
$mime->setTXTBody("ż");
$mime->setHTMLBody("z");
$body = $mime->getMessage();

preg_match_all('/Content-Transfer-Encoding: (.*)/', $body, $m);
echo trim($m[1][0])."\n".trim($m[1][1]);

?>
--EXPECT--
quoted-printable
7bit
PKM1[�M�U..#Mail_Mime/tests/test_Bug_20273.phptnu�[���--TEST--
Bug #20273  Mail_mimePart::encodeHeader() and TAB character
--SKIPIF--
--FILE--
<?php
include("Mail/mimePart.php");

$refs = "<test@domain.tld>\t<test2@domain.tld>";
$mime = new Mail_mimePart();
echo $mime->encodeHeader('References', $refs);
?>
--EXPECT--
<test@domain.tld> <test2@domain.tld>
PKM1[[��b��.Mail_Mime/tests/content_transfer_encoding.phptnu�[���--TEST--
Test empty Content-Transfer-Encoding on multipart messages
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";
$mime = new Mail_mime("\r\n");
$mime->setParam('text_encoding', 'quoted-printable');
$mime->setParam('html_encoding', 'quoted-printable');
$mime->setParam('head_encoding', 'quoted-printable');

// This specific order used to set Content-Transfer-Encoding: quoted-printable
// which is invalid according to RFC 2045 on multipart messages
$mime->setTXTBody('text');
$mime->headers(array('From' => 'from@domain.tld'));
$mime->addAttachment('file.pdf', 'application/pdf', 'file.pdf', false, 'base64', 'inline');
echo $mime->txtHeaders();
list ($header, $body) = explode("\r\n\r\n", $mime->getMessage());
echo $header;
?>
--EXPECTF--
MIME-Version: 1.0
From: from@domain.tld
Content-Type: multipart/mixed;
 boundary="=_%x"
MIME-Version: 1.0
From: from@domain.tld
Content-Type: multipart/mixed;
 boundary="=_%x"
PKM1[�k�0#Mail_Mime/tests/test_Bug_20564.phptnu�[���--TEST--
Bug #20564  Unsetting headers
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$mime = new Mail_mime;
$mime->setSubject('test');

$headers = $mime->headers(array('Subject' => null), true);
echo array_key_exists('Subject', $headers) ? '1' : '0';
--EXPECT--
0PKM1[�a�[��#Mail_Mime/tests/class-filename.phptnu�[���--TEST--
Test class filename (bug #24)
--SKIPIF--
<?php
echo "skip This will be broken until Mail_Mime2";
?>
--FILE--
<?php
@include('Mail/Mime.php');
echo class_exists('Mail_Mime') ? 'Include OK' : 'Include failed';
?>
--EXPECT--
Include OK
PKM1[���o		#Mail_Mime/tests/test_Bug_14529.phptnu�[���--TEST--
Bug #14529  basename() workaround
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$Mime = new Mail_mime();
// some text with polish Unicode letter at the beginning
$filename = base64_decode("xZtjaWVtYQ==");
$Mime->addAttachment('testfile', "text/plain", $filename, FALSE, 'base64', 'attachment', 'ISO-8859-1');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match('/filename([^\s]+)/i', $content, $matches)) {
    echo $matches[1];
}
?>
--EXPECT--
*=ISO-8859-1''%C5%9Bciema;
PKM1[Cz2�}}#Mail_Mime/tests/test_Bug_12165.phptnu�[���--TEST--
Bug #12165  Dot at the end of the line disappeared
--SKIPIF--
--FILE--
<?php
include ("Mail/mime.php");
$string='http://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com';
$mime = new Mail_mime();
$mime->setHTMLBody($string);
print_r($mime->get());
    
--EXPECT--
http://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=
=2Ecom
PKM1[Ya�k!!3Mail_Mime/tests/sleep_wakeup_EOL-bug3488-part1.phptnu�[���--TEST--
Bug #3488   Sleep/Wakeup EOL Consistency - Part 1
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');
$mm = new Mail_mime("\n");
$mm->setHTMLBody('<html></html>');
$mm->setTxtBody('Blah blah');

if (version_compare(phpversion(), "5.0.0", '<')) {
    $mmCopy = $mm;
} else {
    $mmCopy = clone($mm);
}

$mm->get();
$x = $mm->headers();

$smm = serialize(array('mm' => $mmCopy, 'header' => $x['Content-Type']));
$fp = fopen('sleep_wakeup_data', 'w');
fwrite($fp, $smm);
fclose($fp);

echo "Data written";
?>
--EXPECT--
Data written
PKM1[@�/�NN#Mail_Mime/tests/test_Bug_21206.phptnu�[���--TEST--
Bug #21206  Handling quoted strings
--SKIPIF--
--FILE--
<?php
require_once('Mail/mimePart.php');
class X extends Mail_mimePart {
    public static function explodeQuotedString($delimiter, $string) {
        return Mail_mimePart::explodeQuotedString($delimiter, $string);
    }
}

$tests = array(
    '"a" <a@a.a>, b <b@b.b>',
    '"c\\\\" <c@c.c>, d <d@d.d>',
);
foreach ($tests as $test) {
    $addrs = X::explodeQuotedString('[\t,]', $test);
    foreach ($addrs as $addr) {
        print trim($addr) . PHP_EOL;
    }
}
?>
--EXPECT--
"a" <a@a.a>
b <b@b.b>
"c\\" <c@c.c>
d <d@d.d>
PKM1[�8��$Mail_Mime/tests/test_Bug_3513_1.phptnu�[���--TEST--
Bug #3513   Support of RFC2231 in header fields. (ISO-8859-1)
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$test = "F��b�r.txt";
$Mime = new Mail_Mime();
$Mime->addAttachment('testfile',"text/plain", $test, FALSE, 'base64', 'attachment', 'ISO-8859-1');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match('/filename([^\s]+)/i', $content, $matches)) {
    echo $matches[1];
}

--EXPECT--
*=ISO-8859-1''F%F3%F3b%E6r.txt;
PKM1[5����#Mail_Mime/tests/test_Bug_21098.phptnu�[���--TEST--
Bug #21098  Handling of empty plain text parts
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$mime = new Mail_mime();
$mime->setTxtBody('');
$mime->setHTMLBody('<html></html>');

$headers1 = $mime->txtHeaders();
$body     = $mime->get();
$headers2 = $mime->txtHeaders();
print strpos($headers1, 'text/html') && strpos($headers2, 'text/html') ? 'OK' : 'NOT OK';
--EXPECT--
OK
PKM1[���v��$Mail_Mime/tests/test_Bug_8541_1.phptnu�[���--TEST--
Bug #8541   mimePart.php line delimiter is \r
--SKIPIF--
--FILE--
<?php
$mime = file_get_contents('Mail/mime.php', 1);
$mimePart = file_get_contents('Mail/mimePart.php', 1);
if (strpos($mime, "\r")){
    print("\\r found in mime.php\n");
}elseif (strpos($mime, "\t")){
    print("\\t found in mime.php\n");
}elseif (strpos($mimePart, "\r")){
    print("\\r found in mimePart.php\n");
}elseif (strpos($mimePart, "\t")){
    print("\\t found in mimePart.php\n");
}
print('OK');
--EXPECT--
OK
PKM1[Ui�E!E!-Mail_Mime/tests/headers_without_mbstring.phptnu�[���--TEST--
Multi-test for headers encoding using base64 and quoted-printable
--SKIPIF--
<?php
if (function_exists('mb_substr') && function_exists('mb_strlen')) {
    die("skip mbstring functions found!");
}
?>
--FILE--
<?php
include("Mail/mime.php");
$mime = new Mail_mime();

$headers = array(
array('From', '<adresse@adresse.de>'),
array('From', 'adresse@adresse.de'),
array('From', 'Frank Do <adresse@adresse.de>'),
array('To', 'Frank Do <adresse@adresse.de>, James Clark <james@domain.com>'),
array('From', '"Frank Do" <adresse@adresse.de>'),
array('Cc', '"Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>'),
array('Cc', ' <adresse@adresse.de>, "Kuśmiderski Jan Krzysztof Janusz Długa nazwa" <cris@domain.com>'),
array('From', '"adresse@adresse.de" <addresse@adresse>'),
array('From', 'adresse@adresse.de <addresse@adresse>'),
array('From', '"German Umlauts öäü" <adresse@adresse.de>'),
array('Subject', 'German Umlauts öäü <adresse@adresse.de>'),
array('Subject', 'Short ASCII subject'),
array('Subject', 'Long ASCII subject - multiline space separated words - too long for one line'),
array('Subject', 'Short Unicode ż subject'),
array('Subject', 'Long Unicode subject - zażółć gęślą jaźń - too long for one line'),
array('References', '<hglvja$jg7$1@nemesis.news.neostrada.pl>  <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>'),
array('To', '"Frank Do" <adresse@adresse.de>,, "James Clark" <james@domain.com>'),
array('To', '"Frank \\" \\\\Do" <adresse@adresse.de>'),
array('To', 'Frank " \\Do <adresse@adresse.de>'),
array('Subject', "A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test"),
array('Subject', "TEST Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir!!!?"),
array('Subject', "Update: Microsoft Windows-Tool zum Entfernen bösartiger Software 3.6"),
array('From', "test@nàme <user@domain.com>"),
array('From', "Test <\"test test\"@domain.com>"),
array('From', "\"test test\"@domain.com"),
array('From', "<\"test test\"@domain.com>"),
array('From', "Doe<test@domain.com>"),
array('From', "\"John Doe\"<test@domain.com>"),
array('Mail-Reply-To', 'adresse@adresse.de <addresse@adresse>'),
array('Mail-Reply-To', '"öäü" <adresse@adresse.de>'),
);

$i = 1;
foreach ($headers as $header) {
    $hdr = $mime->encodeHeader($header[0], $header[1], 'UTF-8', 'base64');
    printf("[%02d] %s: %s\n", $i, $header[0], $hdr);
    $hdr = $mime->encodeHeader($header[0], $header[1], 'UTF-8', 'quoted-printable');
    printf("[%02d] %s: %s\n", $i, $header[0], $hdr);
    $i++;
}
?>
--EXPECT--
[01] From: <adresse@adresse.de>
[01] From: <adresse@adresse.de>
[02] From: adresse@adresse.de
[02] From: adresse@adresse.de
[03] From: Frank Do <adresse@adresse.de>
[03] From: Frank Do <adresse@adresse.de>
[04] To: Frank Do <adresse@adresse.de>, James Clark <james@domain.com>
[04] To: Frank Do <adresse@adresse.de>, James Clark <james@domain.com>
[05] From: "Frank Do" <adresse@adresse.de>
[05] From: "Frank Do" <adresse@adresse.de>
[06] Cc: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[06] Cc: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[07] Cc: <adresse@adresse.de>, =?UTF-8?B?S3XFm21pZGVyc2tpIEphbiBLcnp5c3p0b2Yg?=
 =?UTF-8?B?SmFudXN6IETFgnVnYSBuYXp3YQ==?= <cris@domain.com>
[07] Cc: <adresse@adresse.de>,
 =?UTF-8?Q?Ku=C5=9Bmiderski_Jan_Krzysztof_Janusz_D?=
 =?UTF-8?Q?=C5=82uga_nazwa?= <cris@domain.com>
[08] From: "adresse@adresse.de" <addresse@adresse>
[08] From: "adresse@adresse.de" <addresse@adresse>
[09] From: "adresse@adresse.de" <addresse@adresse>
[09] From: "adresse@adresse.de" <addresse@adresse>
[10] From: =?UTF-8?B?R2VybWFuIFVtbGF1dHMgw7bDpMO8?= <adresse@adresse.de>
[10] From: =?UTF-8?Q?German_Umlauts_=C3=B6=C3=A4=C3=BC?= <adresse@adresse.de>
[11] Subject: =?UTF-8?B?R2VybWFuIFVtbGF1dHMgw7bDpMO8IDxhZHJlc3NlQGFkcmVzc2Uu?=
 =?UTF-8?B?ZGU+?=
[11] Subject: =?UTF-8?Q?German_Umlauts_=C3=B6=C3=A4=C3=BC_=3Cadresse=40adresse?=
 =?UTF-8?Q?=2Ede=3E?=
[12] Subject: Short ASCII subject
[12] Subject: Short ASCII subject
[13] Subject: Long ASCII subject - multiline space separated words - too long for
 one line
[13] Subject: Long ASCII subject - multiline space separated words - too long for
 one line
[14] Subject: =?UTF-8?B?U2hvcnQgVW5pY29kZSDFvCBzdWJqZWN0?=
[14] Subject: =?UTF-8?Q?Short_Unicode_=C5=BC_subject?=
[15] Subject: =?UTF-8?B?TG9uZyBVbmljb2RlIHN1YmplY3QgLSB6YcW8w7PFgsSHIGfEmcWb?=
 =?UTF-8?B?bMSFIGphxbrFhCAtIHRvbyBsb25nIGZvciBvbmUgbGluZQ==?=
[15] Subject: =?UTF-8?Q?Long_Unicode_subject_-_za=C5=BC=C3=B3=C5=82=C4=87_g=C4?=
 =?UTF-8?Q?=99=C5=9Bl=C4=85_ja=C5=BA=C5=84_-_too_long_for_one_line?=
[16] References: <hglvja$jg7$1@nemesis.news.neostrada.pl>
 <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>
[16] References: <hglvja$jg7$1@nemesis.news.neostrada.pl>
 <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>
[17] To: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[17] To: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[18] To: "Frank \" \\Do" <adresse@adresse.de>
[18] To: "Frank \" \\Do" <adresse@adresse.de>
[19] To: "Frank \" \\Do" <adresse@adresse.de>
[19] To: "Frank \" \\Do" <adresse@adresse.de>
[20] Subject: A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test
[20] Subject: A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test
[21] Subject: =?UTF-8?B?VEVTVCBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1p?=
 =?UTF-8?B?ciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIg?=
 =?UTF-8?B?Z3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRv?=
 =?UTF-8?B?bGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zD?=
 =?UTF-8?B?n2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1p?=
 =?UTF-8?B?ciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIg?=
 =?UTF-8?B?Z3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRv?=
 =?UTF-8?B?bGxlIGdyw7zDn2Ugdm9uIG1pciEhIT8=?=
[21] Subject: =?UTF-8?Q?TEST_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir?=
 =?UTF-8?Q?_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_g?=
 =?UTF-8?Q?r=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tol?=
 =?UTF-8?Q?le_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC?=
 =?UTF-8?Q?=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_m?=
 =?UTF-8?Q?ir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper?=
 =?UTF-8?Q?_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_t?=
 =?UTF-8?Q?olle_gr=C3=BC=C3=9Fe_von_mir!!!=3F?=
[22] Subject: =?UTF-8?B?VXBkYXRlOiBNaWNyb3NvZnQgV2luZG93cy1Ub29sIHp1bSBFbnRm?=
 =?UTF-8?B?ZXJuZW4gYsO2c2FydGlnZXIgU29mdHdhcmUgMy42?=
[22] Subject: =?UTF-8?Q?Update=3A_Microsoft_Windows-Tool_zum_Entfernen_b=C3=B6sa?=
 =?UTF-8?Q?rtiger_Software_3=2E6?=
[23] From: =?UTF-8?B?dGVzdEBuw6BtZQ==?= <user@domain.com>
[23] From: =?UTF-8?Q?test=40n=C3=A0me?= <user@domain.com>
[24] From: Test <"test test"@domain.com>
[24] From: Test <"test test"@domain.com>
[25] From: "test test"@domain.com
[25] From: "test test"@domain.com
[26] From: <"test test"@domain.com>
[26] From: <"test test"@domain.com>
[27] From: Doe <test@domain.com>
[27] From: Doe <test@domain.com>
[28] From: "John Doe" <test@domain.com>
[28] From: "John Doe" <test@domain.com>
[29] Mail-Reply-To: "adresse@adresse.de" <addresse@adresse>
[29] Mail-Reply-To: "adresse@adresse.de" <addresse@adresse>
[30] Mail-Reply-To: =?UTF-8?B?w7bDpMO8?= <adresse@adresse.de>
[30] Mail-Reply-To: =?UTF-8?Q?=C3=B6=C3=A4=C3=BC?= <adresse@adresse.de>
PKM1[��#Mail_Mime/tests/test_Bug_21027.phptnu�[���--TEST--
Bug #21027  Calendar support along with attachments and html images
--SKIPIF--
--FILE--
<?php
require_once('Mail/mime.php');

$txtBody = 'Hi, this is Plain Text Body.';
$htmlBody = '<div>This is HTML body.</div>';
$icsText = 'BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//icalcreator//NONSGML iCalcreator 2.22//
METHOD:REQUEST
BEGIN:VEVENT
UID:77@localhost
DTSTAMP:20160208T170811Z
ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=
 TRUE;CN=Jacob Alvarez:MAILTO:fake1@mailinator.com
CREATED:20160208T170810Z
DTSTART:20160215T180000Z
DTEND:20160215T190000Z
ORGANIZER;CN=-:MAILTO:fake2@mailinator.com
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Prueba 69
TRANSP:OPAQUE
URL:http://localhost/event/77
END:VEVENT
END:VCALENDAR';

function printPartsStartAndEnd($body) {
    $matches  = array();
    preg_match_all('/--(=_[a-z0-9]+)--|Content-Type: ([^;\r\n]+)/', $body, $matches);
    $tab = "    ";
    foreach ($matches[0] as $match){
        if (strpos($match, '--') === false) {
            printf("%s%s\n", $tab, $match);
            if (stripos($match, "multipart")) {
                $tab .= "    ";
            }
        } else {
            $tab = substr($tab, 0, -4);
            printf("%sEnd part\n", $tab);
        }
    }
}

function printHeaderContentType($headers) {
    $headerContentType = array();
    preg_match('/([^;\r\n]+)/', $headers['Content-Type'], $headerContentType);
    printf("Content-Type: %s\n", $headerContentType[0]);
}

print "TEST: text\n";
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: html\n";
$mime = new Mail_mime();
$mime->setHTMLBody($htmlBody);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: attachments\n";
$mime = new Mail_mime();
$mime->addAttachment($icsText, 'application/ics', 'invite.ics', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: text + attachments\n";
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->addAttachment($icsText, 'application/ics', 'invite.ics', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: html + attachments\n";
$mime = new Mail_mime();
$mime->setHTMLBody($htmlBody);
$mime->addAttachment($icsText, 'application/ics', 'invite.ics', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: html + inline images\n";
$mime = new Mail_mime();
$mime->setHTMLBody($htmlBody);
$mime->addHTMLImage("aaaaaaaaaa", 'image/gif', 'image.gif', false, 'contentid');
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print("TEST: txt, html and attachment\n");
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->setHTMLBody($htmlBody);
$mime->addAttachment("test", 'application/octet-stream', 'attachment', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: calendar\n";
$mime = new Mail_mime();
$mime->setCalendarBody($icsText);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: txt + calendar\n";
$mime->setTXTBody($txtBody);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: txt, html, calendar\n";
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->setHTMLBody($htmlBody);
$mime->setCalendarBody($icsText);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: txt, html + html images, and calendar\n";
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->setHTMLBody($htmlBody);
$mime->addHTMLImage('testimage', 'image/gif', "bus.gif", false);
$mime->setCalendarBody($icsText);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print("TEST: txt, html, calendar and attachment\n");
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->setHTMLBody($htmlBody);
$mime->setCalendarBody($icsText);
$mime->addAttachment("test", 'application/octet-stream', 'attachment', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");

print "TEST: txt, html + html images, calendar, and attachment\n";
$mime = new Mail_mime();
$mime->setTXTBody($txtBody);
$mime->setHTMLBody($htmlBody);
$mime->addHTMLImage('testimage', 'image/gif', "bus.gif", false);
$mime->setCalendarBody($icsText);
$mime->addAttachment($icsText, 'application/ics', 'invite.ics', false);
$headers = $mime->headers();
$body = $mime->get();
printHeaderContentType($headers);
printPartsStartAndEnd($body);
print("\n");
?>
--EXPECT--
TEST: text
Content-Type: text/plain

TEST: html
Content-Type: text/html

TEST: attachments
Content-Type: multipart/mixed
    Content-Type: application/ics
End part

TEST: text + attachments
Content-Type: multipart/mixed
    Content-Type: text/plain
    Content-Type: application/ics
End part

TEST: html + attachments
Content-Type: multipart/mixed
    Content-Type: text/html
    Content-Type: application/ics
End part

TEST: html + inline images
Content-Type: multipart/related
    Content-Type: text/html
    Content-Type: image/gif
End part

TEST: txt, html and attachment
Content-Type: multipart/mixed
    Content-Type: multipart/alternative
        Content-Type: text/plain
        Content-Type: text/html
    End part
    Content-Type: application/octet-stream
End part

TEST: calendar
Content-Type: text/calendar

TEST: txt + calendar
Content-Type: multipart/alternative
    Content-Type: text/plain
    Content-Type: text/calendar
End part

TEST: txt, html, calendar
Content-Type: multipart/alternative
    Content-Type: text/plain
    Content-Type: text/html
    Content-Type: text/calendar
End part

TEST: txt, html + html images, and calendar
Content-Type: multipart/alternative
    Content-Type: text/plain
    Content-Type: multipart/related
        Content-Type: text/html
        Content-Type: image/gif
    End part
    Content-Type: text/calendar
End part

TEST: txt, html, calendar and attachment
Content-Type: multipart/mixed
    Content-Type: multipart/alternative
        Content-Type: text/plain
        Content-Type: text/html
        Content-Type: text/calendar
    End part
    Content-Type: application/octet-stream
End part

TEST: txt, html + html images, calendar, and attachment
Content-Type: multipart/mixed
    Content-Type: multipart/alternative
        Content-Type: text/plain
        Content-Type: multipart/related
            Content-Type: text/html
            Content-Type: image/gif
        End part
        Content-Type: text/calendar
    End part
    Content-Type: application/ics
End part
PKM1[`�~@%Mail_Mime/tests/test_Bug_12385_1.phptnu�[���--TEST--
Bug #12385  Bad regex when replacing css style attachments
--SKIPIF--
--FILE--
<?php
$from='user@from.example.com';

require_once('Mail/mime.php');

$mime=new Mail_mime();

$body="<style>
className {
    background-image: url('test.gif');
}
</script>
";

$mime->setHTMLBody($body);
$mime->setFrom($from);
$mime->addHTMLImage('','image/gif', 'test.gif', false);
$msg = $mime->get();

$cidtag = preg_match("|url\('cid:[^']*'\);|", $msg);
if (!$cidtag){
    print("FAIL:\n");
    print($msg);
}else{
    print("OK");
}
--EXPECT--
OK
PKM1[�zŬ�#Mail_Mime/tests/test_Bug_11731.phptnu�[���--TEST--
Bug #11731  Full stops after soft line breaks are not encoded
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");
// Second full stop will be at the start of the second line after quoted-printable
// encoding (full stop '=2E' + 72 characters + line-continuation '=' = 76)
$text     = '.123456789012345678901234567890123456789012345678901234567890123456789012.3456';
$params   = Array(
    'content_type' => 'text/plain',
    'encoding'     => 'quoted-printable',
);    
$mimePart = new Mail_mimePart($text, $params);
$encoded  =  $mimePart->encode();
echo $encoded['body'];
    
--EXPECT--
=2E123456789012345678901234567890123456789012345678901234567890123456789012=
=2E3456
PKM1[X��b��#Mail_Mime/tests/test_Bug_14779.phptnu�[���--TEST--
Bug #14779  Proper header-body separator for empty attachment
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$m = new Mail_mime();
$m->addAttachment('', "text/plain", 'file.txt', FALSE, 'base64', 'attachment');
$result = $m->get();

if (preg_match('/(Content.*)--=.*/s', $result, $matches)) {
    print_r($matches[1]."END");
}

?>
--EXPECT--
Content-Transfer-Encoding: base64
Content-Type: text/plain;
 name=file.txt
Content-Disposition: attachment;
 filename=file.txt


END
PKM1[�I�zz#Mail_Mime/tests/test_Bug_20563.phptnu�[���--TEST--
Bug #20563  isMultipart() method tests
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$mime = new Mail_mime;

echo ($mime->isMultipart() ? 'TRUE' : 'FALSE') . "\n";

$mime->setTXTBody('test');

echo ($mime->isMultipart() ? 'TRUE' : 'FALSE') . "\n";

$mime->setHTMLBody('test');

echo ($mime->isMultipart() ? 'TRUE' : 'FALSE') . "\n";

--EXPECT--
FALSE
FALSE
TRUE
PKM1[ZX�Hww$Mail_Mime/tests/test_Bug_3513_3.phptnu�[���--TEST--
Bug #3513   Support of RFC2231 in header fields. (ISO-2022-JP)
--SKIPIF--
--FILE--
<?php
mb_internal_encoding('ISO-2022-JP');
$testEncoded="GyRCRnxLXDhsGyhCLnR4dA==";
$test = base64_decode($testEncoded); // Japanese filename in ISO-2022-JP charset.
require_once('Mail/mime.php');

$Mime = new Mail_Mime();
$Mime->addAttachment('testfile',"text/plain", $test, FALSE, 'base64', 'attachment', 'iso-2022-jp', '');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match('/filename([^\s]+)/i', $content, $matches)) {
    echo $matches[1];
}
?>
--EXPECT--
*=iso-2022-jp''%1B$BF|K%5C8l%1B%28B.txt;

PKM1[������#Mail_Mime/tests/test_Bug_15320.phptnu�[���--TEST--
Bug #15320  Charset parameter in Content-Type of mail parts
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";

$Mime = new Mail_mime();
$Mime->addAttachment('testfile', "text/plain", 'file.txt', FALSE, 'base64', 'attachment', 'ISO-8859-1');

$content = $Mime->get();
//$content = str_replace("\n", '', $content);

if (preg_match('/Content-type:([^\n]+)/i', $content, $matches)) {
    echo $matches[1];
}

?>
--EXPECT--
text/plain; charset=ISO-8859-1;

PKM1[�-b2#Mail_Mime/tests/test_Bug_13032.phptnu�[���--TEST--
Bug #13032  Proper (different) boundary for nested parts
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";
$mime = new Mail_mime("\r\n");
$mime->setHTMLBody('html');
$mime->setTXTBody('text');
$mime->addAttachment('file.pdf', 'application/pdf', 'file.pdf', false, 'base64', 'inline');
$msg = $mime->getMessage();

if (preg_match_all('/boundary="([^"]+)"/', $msg, $matches)) {
    if (count($matches) == 2 && count($matches[1]) == 2 &&
        $matches[1][0] != $matches[1][1]) {
            print('OK');
    }
}
?>
--EXPECT--
OK
PKM1[%+2PP#Mail_Mime/tests/test_Bug_18083.phptnu�[���--TEST--
Bug #18083  Separate charset for attachment's content and headers
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";
$Mime = new Mail_mime();

$Mime->addAttachment('testfile', "text/plain",
    base64_decode("xZtjaWVtYQ=="), FALSE,
    'base64', 'attachment', 'ISO-8859-1', 'pl', '',
    'quoted-printable', 'base64', '', 'UTF-8');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match_all('/(name|filename)=([^\s]+)/i', $content, $matches)) {
    echo implode("\n", $matches[2]);
}
?>
--EXPECT--
"=?UTF-8?Q?=C5=9Bciema?="
"=?UTF-8?B?xZtjaWVtYQ==?=";
PKM1[Qi�"--#Mail_Mime/tests/test_Bug_11381.phptnu�[���--TEST--
Bug #11381  Domain name is attached to content-id, trailing greater-than sign is not removed
--SKIPIF--
--FILE--
<?php
$from='Test User <user@from.example.com>';

require_once('Mail/mime.php');

$mime=new Mail_mime();

$body='<img src="test.gif"/>';

$mime->setHTMLBody($body);
$mime->setFrom($from);
$mime->addHTMLImage('','image/gif', 'test.gif', false);
$msg=$mime->get();

$header = preg_match('|Content-ID: <[0-9a-fA-F]+@from.example.com>|', $msg);
if (!$header){
    print("FAIL:\n");
    print($msg);
}else{
    print("OK");
}
--EXPECT--
OK
PKM1[�X�###Mail_Mime/tests/test_Bug_19497.phptnu�[���--TEST--
Bug #19497  Attachment filenames with a slash character
--SKIPIF--
--FILE--
<?php
include "Mail/mime.php";
$Mime = new Mail_mime();

$filename = "test/file.txt";
$Mime->addAttachment('testfile', "text/plain", $filename, FALSE,
    'base64', 'attachment', 'ISO-8859-1', '', '', 'quoted-printable', 'base64');

$content = $Mime->get();
$content = str_replace("\n", '', $content);

if (preg_match_all('/(name|filename)=([^\s]+)/i', $content, $matches)) {
    echo implode("\n", $matches[2]);
}
?>
--EXPECT--
"test/file.txt"
"test/file.txt";
PKM1[�'�''$Mail_Mime/tests/test_Bug_8386_1.phptnu�[���--TEST--
Bug #8386   HTML body not correctly encoded if attachments present
--SKIPIF--
--FILE--
<?php
$eol = "\n#";
include("Mail/mime.php");
$encoder = new Mail_mime(array('eol'=>$eol));
$encoder->setTXTBody('test');
$encoder->setHTMLBody('<b>test</b>');
$encoder->addAttachment('Just a test', 'application/octet-stream', 'test.txt', false);
$body = $encoder->get();
if (strpos($body, '--' . $eol . '--=')){
    print("FAILED\n");
    print("Single delimiter() between 2 parts found.\n");
    print($body);
}else{
    print("OK");
}
?>
--EXPECT--
OK
PKM1[��1d��#Mail_Mime/tests/test_Bug_17025.phptnu�[���--TEST--
Bug #16539  Headers longer than 998 characters
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$headers['From'] = 'aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffffgggggggggghhhhhhhhhh';
# over than 76 chars
$mime = new Mail_mime();
$hdrs = $mime->headers($headers);
print_r($hdrs['From']); 
?>
--EXPECT--
aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeeeffffffffffgggggggggghhhhhhhhhh
PKM1[e�@Q__#Mail_Mime/tests/test_Bug_14780.phptnu�[���--TEST--
Bug #14780  Invalid Content-Type when headers() is called before get()
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");

$mime = new Mail_mime();
$mime->setTXTBody("test");
$mime->setHTMLBody("test");

$head1 = $mime->headers();
$body = $mime->get();
$head2 = $mime->headers();

if ($head1 === $head2) {
    echo "OK";
}

?>
--EXPECT--
OK
PKM1[�
Ǟ		-Mail_Mime/tests/test_linebreak_larger_76.phptnu�[���--TEST--
Test for correct linebreaks for lines _longer_ than 76 chars.
--SKIPIF--
--FILE--
<?php
error_reporting(E_ALL); // ignore E_STRICT

include("Mail/mime.php");
$text     = '12345678901234567890123456789012345678901234567890123456789012345678901234567890';
$params   = Array(
    'content_type' => 'text/plain',
    'encoding'     => 'quoted-printable',
);

for ($i=74; $i <= strlen($text); $i++) {
    $input = substr($text, 0, $i);
    $mimePart = new Mail_mimePart($input, $params);
    $encoded  =  $mimePart->encode();
    $output = $encoded['body'];
    printf("input: %02d: %s\n", strlen($input), $input);

    $lines = explode("\r\n", $output);
    for($j=0; $j < count($lines); $j++) {
        $line = $lines[$j];
        if ($j + 1 < count($lines)) {
            $line_vis = $line.'\r\n';
        } else {
            $line_vis = $line;
        }
        printf("output:%02d: %s\n", strlen($line), $line_vis);
    }
    print("---\n");
}
--EXPECT--
input: 74: 12345678901234567890123456789012345678901234567890123456789012345678901234
output:74: 12345678901234567890123456789012345678901234567890123456789012345678901234
---
input: 75: 123456789012345678901234567890123456789012345678901234567890123456789012345
output:75: 123456789012345678901234567890123456789012345678901234567890123456789012345
---
input: 76: 1234567890123456789012345678901234567890123456789012345678901234567890123456
output:76: 1234567890123456789012345678901234567890123456789012345678901234567890123456
---
input: 77: 12345678901234567890123456789012345678901234567890123456789012345678901234567
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:02: 67
---
input: 78: 123456789012345678901234567890123456789012345678901234567890123456789012345678
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:03: 678
---
input: 79: 1234567890123456789012345678901234567890123456789012345678901234567890123456789
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:04: 6789
---
input: 80: 12345678901234567890123456789012345678901234567890123456789012345678901234567890
output:76: 123456789012345678901234567890123456789012345678901234567890123456789012345=\r\n
output:05: 67890
---
PKM1[ܶg�hh$Mail_Mime/tests/test_Bug_9722_1.phptnu�[���--TEST--
Bug #9722   quotedPrintableEncode does not encode dot at start of line on Windows platform
--SKIPIF--
--FILE--
<?php
include("Mail/mimePart.php");
$text = "This
is a
test
...
    It is 
//really fun//
to make :(";

print_r(Mail_mimePart::quotedPrintableEncode($text, 76, "\n"));

--EXPECT--
This
is a
test
=2E..
    It is=20
//really fun//
to make :(
PKN1[�YcLYY#Mail_Mime/tests/test_Bug_16539.phptnu�[���--TEST--
Bug #16539  Headers longer than 998 characters
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");
$mime = new Mail_mime();

$headers = array(
'To' => 'jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com',
'Subject' => 'jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com',
);

echo $mime->txtHeaders($headers, true, true);
?>
--EXPECT--
MIME-Version: 1.0
To: jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com, jskibbie@schawk.com,
 jskibbie@schawk.com, jskibbie@schawk.com
Subject: jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.co
 m,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com,jskibbie@schawk.com
PKN1[��((%Mail_Mime/tests/test_Bug_10596_1.phptnu�[���--TEST--
Bug #10596  Incorrect handling of text and html '0' bodies
--SKIPIF--
--FILE--
<?php
include("Mail/mime.php");
$mime = new Mail_mime();
$mime->setTxtBody('0');
$mime->setHTMLBody('0');
$body = $mime->get();
if ($body){
    print("OK");
}else{
    print("NO BODY FOUND");
}
--EXPECT--
OK
PKN1[9��::%Mail_Mime/tests/test_Bug_10816_1.phptnu�[���--TEST--
Bug #10816  Unwanted linebreak at the end of output
--SKIPIF--
--FILE--
<?php
$eol = "#";
include("Mail/mime.php");
$encoder = new Mail_mime(array('eol'=>$eol));
$encoder->setTXTBody('test');
$encoder->setHTMLBody('<b>test</b>');
$encoder->addAttachment('Just a test', 'application/octet-stream', 'test.txt', false);
$body = $encoder->get();
$taillength = -1 * strlen($eol) * 2;
if (substr($body, $taillength) == ($eol.$eol)){
    print("FAILED\n");
    print("Body:\n");
    print("..." . substr($body, -10) . "\n");
}else{
    print("OK\n");
}
--EXPECT--
OK

PKN1[��᠗"�"*Mail_Mime/tests/headers_with_mbstring.phptnu�[���--TEST--
Multi-test for headers encoding using base64 and quoted-printable
--SKIPIF--
<?php
if (!function_exists('mb_substr') || !function_exists('mb_strlen')) {
    die "skip mbstring functions not found!";
}
?>
--FILE--
<?php
include("Mail/mime.php");
$mime = new Mail_mime();

$headers = array(
array('From', '<adresse@adresse.de>'),
array('From', 'adresse@adresse.de'),
array('From', 'Frank Do <adresse@adresse.de>'),
array('To', 'Frank Do <adresse@adresse.de>, James Clark <james@domain.com>'),
array('From', '"Frank Do" <adresse@adresse.de>'),
array('Cc', '"Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>'),
array('Cc', ' <adresse@adresse.de>, "Kuśmiderski Jan Krzysztof Janusz Długa nazwa" <cris@domain.com>'),
array('From', '"adresse@adresse.de" <addresse@adresse>'),
array('From', 'adresse@adresse.de <addresse@adresse>'),
array('From', '"German Umlauts öäü" <adresse@adresse.de>'),
array('Subject', 'German Umlauts öäü <adresse@adresse.de>'),
array('Subject', 'Short ASCII subject'),
array('Subject', 'Long ASCII subject - multiline space separated words - too long for one line'),
array('Subject', 'Short Unicode ż subject'),
array('Subject', 'Long Unicode subject - zażółć gęślą jaźń - too long for one line'),
array('References', '<hglvja$jg7$1@nemesis.news.neostrada.pl>  <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>'),
array('To', '"Frank Do" <adresse@adresse.de>,, "James Clark" <james@domain.com>'),
array('To', '"Frank \\" \\\\Do" <adresse@adresse.de>'),
array('To', 'Frank " \\Do <adresse@adresse.de>'),
array('Subject', "A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test"),
array('Subject', "TEST Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir Süper gröse tolle grüße von mir!!!?"),
array('Subject', "Update: Microsoft Windows-Tool zum Entfernen bösartiger Software 3.6"),
array('From', "test@nàme <user@domain.com>"),
array('From', "Test <\"test test\"@domain.com>"),
array('From', "\"test test\"@domain.com"),
array('From', "<\"test test\"@domain.com>"),
array('From', "Doe<test@domain.com>"),
array('From', "\"John Doe\"<test@domain.com>"),
array('Mail-Reply-To', 'adresse@adresse.de <addresse@adresse>'),
array('Mail-Reply-To', '"öäü" <adresse@adresse.de>'),
array('Subject', mb_convert_encoding('㈱山﨑工業', 'ISO-2022-JP-MS', 'UTF-8'), 'ISO-2022-JP'),
);

$i = 1;
foreach ($headers as $header) {
    $charset = isset($header[2]) ? $header[2] : 'UTF-8';
    $hdr = $mime->encodeHeader($header[0], $header[1], $charset, 'base64');
    printf("[%02d] %s: %s\n", $i, $header[0], $hdr);
    $hdr = $mime->encodeHeader($header[0], $header[1], $charset, 'quoted-printable');
    printf("[%02d] %s: %s\n", $i, $header[0], $hdr);
    $i++;
}
?>
--EXPECT--
[01] From: <adresse@adresse.de>
[01] From: <adresse@adresse.de>
[02] From: adresse@adresse.de
[02] From: adresse@adresse.de
[03] From: Frank Do <adresse@adresse.de>
[03] From: Frank Do <adresse@adresse.de>
[04] To: Frank Do <adresse@adresse.de>, James Clark <james@domain.com>
[04] To: Frank Do <adresse@adresse.de>, James Clark <james@domain.com>
[05] From: "Frank Do" <adresse@adresse.de>
[05] From: "Frank Do" <adresse@adresse.de>
[06] Cc: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[06] Cc: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[07] Cc: <adresse@adresse.de>, =?UTF-8?B?S3XFm21pZGVyc2tpIEphbiBLcnp5c3p0b2Yg?=
 =?UTF-8?B?SmFudXN6IETFgnVnYSBuYXp3YQ==?= <cris@domain.com>
[07] Cc: <adresse@adresse.de>, =?UTF-8?Q?Ku=C5=9Bmiderski_Jan_Krzysztof_Janusz?=
 =?UTF-8?Q?_D=C5=82uga_nazwa?= <cris@domain.com>
[08] From: "adresse@adresse.de" <addresse@adresse>
[08] From: "adresse@adresse.de" <addresse@adresse>
[09] From: "adresse@adresse.de" <addresse@adresse>
[09] From: "adresse@adresse.de" <addresse@adresse>
[10] From: =?UTF-8?B?R2VybWFuIFVtbGF1dHMgw7bDpMO8?= <adresse@adresse.de>
[10] From: =?UTF-8?Q?German_Umlauts_=C3=B6=C3=A4=C3=BC?= <adresse@adresse.de>
[11] Subject: =?UTF-8?B?R2VybWFuIFVtbGF1dHMgw7bDpMO8IDxhZHJlc3NlQGFkcmVzc2Uu?=
 =?UTF-8?B?ZGU+?=
[11] Subject: =?UTF-8?Q?German_Umlauts_=C3=B6=C3=A4=C3=BC_=3Cadresse=40adresse?=
 =?UTF-8?Q?=2Ede=3E?=
[12] Subject: Short ASCII subject
[12] Subject: Short ASCII subject
[13] Subject: Long ASCII subject - multiline space separated words - too long for
 one line
[13] Subject: Long ASCII subject - multiline space separated words - too long for
 one line
[14] Subject: =?UTF-8?B?U2hvcnQgVW5pY29kZSDFvCBzdWJqZWN0?=
[14] Subject: =?UTF-8?Q?Short_Unicode_=C5=BC_subject?=
[15] Subject: =?UTF-8?B?TG9uZyBVbmljb2RlIHN1YmplY3QgLSB6YcW8w7PFgsSHIGfEmcWb?=
 =?UTF-8?B?bMSFIGphxbrFhCAtIHRvbyBsb25nIGZvciBvbmUgbGluZQ==?=
[15] Subject: =?UTF-8?Q?Long_Unicode_subject_-_za=C5=BC=C3=B3=C5=82=C4=87_g?=
 =?UTF-8?Q?=C4=99=C5=9Bl=C4=85_ja=C5=BA=C5=84_-_too_long_for_one_line?=
[16] References: <hglvja$jg7$1@nemesis.news.neostrada.pl>
 <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>
[16] References: <hglvja$jg7$1@nemesis.news.neostrada.pl>
 <4b2e87ac$1@news.home.net.pl> <hgm5b1$3a7$1@atlantis.news.neostrada.pl>
[17] To: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[17] To: "Frank Do" <adresse@adresse.de>, "James Clark" <james@domain.com>
[18] To: "Frank \" \\Do" <adresse@adresse.de>
[18] To: "Frank \" \\Do" <adresse@adresse.de>
[19] To: "Frank \" \\Do" <adresse@adresse.de>
[19] To: "Frank \" \\Do" <adresse@adresse.de>
[20] Subject: A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test
[20] Subject: A REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY
 REALLY REALLY REALLY REALLY REALLY REALLY REALLY REALLY /REALLY/ LONG test
[21] Subject: =?UTF-8?B?VEVTVCBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1p?=
 =?UTF-8?B?ciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIg?=
 =?UTF-8?B?Z3LDtnNlIHRvbGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRv?=
 =?UTF-8?B?bGxlIGdyw7zDn2Ugdm9uIG1pciBTw7xwZXIgZ3LDtnNlIHRvbGxlIGdyw7w=?=
 =?UTF-8?B?w59lIHZvbiBtaXIgU8O8cGVyIGdyw7ZzZSB0b2xsZSBncsO8w59lIHZvbiBt?=
 =?UTF-8?B?aXIgU8O8cGVyIGdyw7ZzZSB0b2xsZSBncsO8w59lIHZvbiBtaXIgU8O8cGVy?=
 =?UTF-8?B?IGdyw7ZzZSB0b2xsZSBncsO8w59lIHZvbiBtaXIgU8O8cGVyIGdyw7ZzZSB0?=
 =?UTF-8?B?b2xsZSBncsO8w59lIHZvbiBtaXIhISE/?=
[21] Subject: =?UTF-8?Q?TEST_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_m?=
 =?UTF-8?Q?ir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCp?=
 =?UTF-8?Q?er_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6?=
 =?UTF-8?Q?se_tolle_gr=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tolle_gr?=
 =?UTF-8?Q?=C3=BC=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC?=
 =?UTF-8?Q?=C3=9Fe_von_mir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von?=
 =?UTF-8?Q?_mir_S=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir_S?=
 =?UTF-8?Q?=C3=BCper_gr=C3=B6se_tolle_gr=C3=BC=C3=9Fe_von_mir!!!=3F?=
[22] Subject: =?UTF-8?B?VXBkYXRlOiBNaWNyb3NvZnQgV2luZG93cy1Ub29sIHp1bSBFbnRm?=
 =?UTF-8?B?ZXJuZW4gYsO2c2FydGlnZXIgU29mdHdhcmUgMy42?=
[22] Subject: =?UTF-8?Q?Update=3A_Microsoft_Windows-Tool_zum_Entfernen_b=C3=B6?=
 =?UTF-8?Q?sartiger_Software_3=2E6?=
[23] From: =?UTF-8?B?dGVzdEBuw6BtZQ==?= <user@domain.com>
[23] From: =?UTF-8?Q?test=40n=C3=A0me?= <user@domain.com>
[24] From: Test <"test test"@domain.com>
[24] From: Test <"test test"@domain.com>
[25] From: "test test"@domain.com
[25] From: "test test"@domain.com
[26] From: <"test test"@domain.com>
[26] From: <"test test"@domain.com>
[27] From: Doe <test@domain.com>
[27] From: Doe <test@domain.com>
[28] From: "John Doe" <test@domain.com>
[28] From: "John Doe" <test@domain.com>
[29] Mail-Reply-To: "adresse@adresse.de" <addresse@adresse>
[29] Mail-Reply-To: "adresse@adresse.de" <addresse@adresse>
[30] Mail-Reply-To: =?UTF-8?B?w7bDpMO8?= <adresse@adresse.de>
[30] Mail-Reply-To: =?UTF-8?Q?=C3=B6=C3=A4=C3=BC?= <adresse@adresse.de>
[31] Subject: =?ISO-2022-JP?B?GyRCLWo7M3l1OSk2SBsoQg==?=
[31] Subject: =?ISO-2022-JP?Q?=24B-j=28B=24B=3B3=28B=24Byu=28B?=
 =?ISO-2022-JP?Q?=24B9=29=28B=24B6H=28B?=
PKN1[���|JJ3Mail_Mime/tests/sleep_wakeup_EOL-bug3488-part2.phptnu�[���--TEST--
Bug #3488   Sleep/Wakeup EOL Consistency - Part 2
--SKIPIF--
if (!is_readable('sleep_wakeup_data')) {
    echo "skip No data. Part 1 must run first.\n";
}
--FILE--
<?php
require_once('Mail/mime.php');
$filename = 'sleep_wakeup_data';
$fp = fopen($filename, 'r');
$smm = fread($fp, filesize($filename));
fclose($fp);
@unlink($filename);

$mmData = unserialize($smm);
$mmData['mm']->get();
$x = $mmData['mm']->headers();

list($h1) = explode("\n", $mmData['header']);
list($h2) = explode("\n", $x['Content-Type']);

echo ($h1 == $h2) ? "Match" : "No Match";

?>
--EXPECT--
Match
PKN1[�{�	�	%File_MARC/tests/marc_xml_rsinger.phptnu�[���--TEST--
marc_xml_rsinger2: iterate and pretty print a non-compliant MARC record (uppercase subfield codes)
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'bad_example.xml');

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01850    a2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
005     20050204111518.0
020    _a9515008808
       _cFIM 72:00
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 0  _aDet osynliga barnet och andra bert̃telser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
841    _5Li
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5SEE
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5L
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5NB
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5Q
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5S
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
852    _5NB
       _bNB
       _cNB98:12
       _hplikt
       _jR, 980520
852    _5Li
       _bLi
       _cCNB
       _hh,u
852    _5SEE
       _bSEE
852    _5Q
       _bQ
       _j98947
852    _5L
       _bL
       _c0100
       _h98/
       _j3043 H
852    _5S
       _bS
       _hSv97
       _j7235
900 1s _aYanson, Tobe,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonov,̀ Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansone, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonova, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
976  2 _aHcd,u
       _bSkn̲litteratur
PKN1[a!���File_MARC/tests/namespace.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XML Spy v4.3 U (http://www.xmlspy.com) by Morgan Cundiff (Library of Congress) -->
<marc:collection xmlns:marc="http://www.loc.gov/MARC21/slim" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">
	<marc:record>
		<marc:leader>00925njm  22002777a 4500</marc:leader>
		<marc:controlfield tag="001">5637241</marc:controlfield>
		<marc:controlfield tag="003">DLC</marc:controlfield>
		<marc:controlfield tag="005">19920826084036.0</marc:controlfield>
		<marc:controlfield tag="007">sdubumennmplu</marc:controlfield>
		<marc:controlfield tag="008">910926s1957    nyuuun              eng  </marc:controlfield>
		<marc:datafield tag="010" ind1=" " ind2=" ">
			<marc:subfield code="a">   91758335 </marc:subfield>
		</marc:datafield>
		<marc:datafield tag="028" ind1="0" ind2="0">
			<marc:subfield code="a">1259</marc:subfield>
			<marc:subfield code="b">Atlantic</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="040" ind1=" " ind2=" ">
			<marc:subfield code="a">DLC</marc:subfield>
			<marc:subfield code="c">DLC</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="050" ind1="0" ind2="0">
			<marc:subfield code="a">Atlantic 1259</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="245" ind1="0" ind2="4">
			<marc:subfield code="a">The Great Ray Charles</marc:subfield>
			<marc:subfield code="h">[sound recording].</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="260" ind1=" " ind2=" ">
			<marc:subfield code="a">New York, N.Y. :</marc:subfield>
			<marc:subfield code="b">Atlantic,</marc:subfield>
			<marc:subfield code="c">[1957?]</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="300" ind1=" " ind2=" ">
			<marc:subfield code="a">1 sound disc :</marc:subfield>
			<marc:subfield code="b">analog, 33 1/3 rpm ;</marc:subfield>
			<marc:subfield code="c">12 in.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="511" ind1="0" ind2=" ">
			<marc:subfield code="a">Ray Charles, piano &amp; celeste.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="505" ind1="0" ind2=" ">
			<marc:subfield code="a">The Ray -- My melancholy baby -- Black coffee -- There's no you -- Doodlin' -- Sweet sixteen bars -- I surrender dear -- Undecided.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="500" ind1=" " ind2=" ">
			<marc:subfield code="a">Brief record.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="650" ind1=" " ind2="0">
			<marc:subfield code="a">Jazz</marc:subfield>
			<marc:subfield code="y">1951-1960.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="650" ind1=" " ind2="0">
			<marc:subfield code="a">Piano with jazz ensemble.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="700" ind1="1" ind2=" ">
			<marc:subfield code="a">Charles, Ray,</marc:subfield>
			<marc:subfield code="d">1930-</marc:subfield>
			<marc:subfield code="4">prf</marc:subfield>
		</marc:datafield>
	</marc:record>
	<marc:record>
		<marc:leader>01832cmma 2200349 a 4500</marc:leader>
		<marc:controlfield tag="001">12149120</marc:controlfield>
		<marc:controlfield tag="005">20001005175443.0</marc:controlfield>
		<marc:controlfield tag="007">cr |||</marc:controlfield>
		<marc:controlfield tag="008">000407m19949999dcu    g   m        eng d</marc:controlfield>
		<marc:datafield tag="906" ind1=" " ind2=" ">
			<marc:subfield code="a">0</marc:subfield>
			<marc:subfield code="b">ibc</marc:subfield>
			<marc:subfield code="c">copycat</marc:subfield>
			<marc:subfield code="d">1</marc:subfield>
			<marc:subfield code="e">ncip</marc:subfield>
			<marc:subfield code="f">20</marc:subfield>
			<marc:subfield code="g">y-gencompf</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="925" ind1="0" ind2=" ">
			<marc:subfield code="a">undetermined</marc:subfield>
			<marc:subfield code="x">web preservation project (wpp)</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="955" ind1=" " ind2=" ">
			<marc:subfield code="a">vb07 (stars done) 08-19-00 to HLCD lk00; AA3s lk29 received for subject Aug 25, 2000; to DEWEY 08-25-00; aa11 08-28-00</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="010" ind1=" " ind2=" ">
			<marc:subfield code="a">   00530046 </marc:subfield>
		</marc:datafield>
		<marc:datafield tag="035" ind1=" " ind2=" ">
			<marc:subfield code="a">(OCoLC)ocm44279786</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="040" ind1=" " ind2=" ">
			<marc:subfield code="a">IEU</marc:subfield>
			<marc:subfield code="c">IEU</marc:subfield>
			<marc:subfield code="d">N@F</marc:subfield>
			<marc:subfield code="d">DLC</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="042" ind1=" " ind2=" ">
			<marc:subfield code="a">lccopycat</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="043" ind1=" " ind2=" ">
			<marc:subfield code="a">n-us-dc</marc:subfield>
			<marc:subfield code="a">n-us---</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="050" ind1="0" ind2="0">
			<marc:subfield code="a">F204.W5</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="082" ind1="1" ind2="0">
			<marc:subfield code="a">975.3</marc:subfield>
			<marc:subfield code="2">13</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="245" ind1="0" ind2="4">
			<marc:subfield code="a">The White House</marc:subfield>
			<marc:subfield code="h">[computer file].</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="256" ind1=" " ind2=" ">
			<marc:subfield code="a">Computer data.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="260" ind1=" " ind2=" ">
			<marc:subfield code="a">Washington, D.C. :</marc:subfield>
			<marc:subfield code="b">White House Web Team,</marc:subfield>
			<marc:subfield code="c">1994-</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="538" ind1=" " ind2=" ">
			<marc:subfield code="a">Mode of access: Internet.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="500" ind1=" " ind2=" ">
			<marc:subfield code="a">Title from home page as viewed on Aug. 19, 2000.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="520" ind1="8" ind2=" ">
			<marc:subfield code="a">Features the White House. Highlights the Executive Office of the President, which includes senior policy advisors and offices responsible for the President's correspondence and communications, the Office of the Vice President, and the Office of the First Lady. Posts contact information via mailing address, telephone and fax numbers, and e-mail. Contains the Interactive Citizens' Handbook with information on health, travel and tourism, education and training, and housing. Provides a tour and the history of the White House. Links to White House for Kids.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="610" ind1="2" ind2="0">
			<marc:subfield code="a">White House (Washington, D.C.)</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="610" ind1="1" ind2="0">
			<marc:subfield code="a">United States.</marc:subfield>
			<marc:subfield code="b">Executive Office of the President.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="610" ind1="1" ind2="0">
			<marc:subfield code="a">United States.</marc:subfield>
			<marc:subfield code="b">Office of the Vice President.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="610" ind1="1" ind2="0">
			<marc:subfield code="a">United States.</marc:subfield>
			<marc:subfield code="b">Office of the First Lady.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="710" ind1="2" ind2=" ">
			<marc:subfield code="a">White House Web Team.</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="856" ind1="4" ind2="0">
			<marc:subfield code="u">http://www.whitehouse.gov</marc:subfield>
		</marc:datafield>
		<marc:datafield tag="856" ind1="4" ind2="0">
			<marc:subfield code="u">http://lcweb.loc.gov/staff/wpp/whitehouse.html</marc:subfield>
			<marc:subfield code="z">Web site archive</marc:subfield>
		</marc:datafield>
	</marc:record>
</marc:collection>PKN1[44�-��#File_MARC/tests/marc_field_003.phptnu�[���--TEST--
marc_field_003: Add subfields to an existing field
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// create a field
$field = new File_MARC_Data_Field('100', $subfields, '0');

// create some new subfields
$subfield1 = new File_MARC_Subfield('g', 'a little');
$subfield2 = new File_MARC_Subfield('k', 'a bit more');
$subfield3 = new File_MARC_Subfield('t', 'a lot');
$subfield4 = new File_MARC_Subfield('0', 'first post');

// append a new subfield to the existing set of subfields
// expected order: a-z-g
$field->appendSubfield($subfield1);

// insert a new subfield after the first subfield with code 'z'
// expected order: a-z-k-g
$sf = $field->getSubfields('z');
// we might get an array back; in this case, we want the first subfield
if (is_array($sf)) {
  $field->insertSubfield($subfield2, $sf[0]);
}
else {
  $field->insertSubfield($subfield2, $sf);
}

// insert a new subfield prior to the first subfield with code 'z'
// expected order: a-t-z-k-g
$sf = $field->getSubfields('z');
// we might get an array back; in this case, we want the first subfield
if (is_array($sf)) {
  $field->insertSubfield($subfield3, $sf[0], true);
}
else {
  $field->insertSubfield($subfield3, $sf, true);
}

// insert a new subfield at the very start of the field
$field->prependSubfield($subfield4);

// let's see the results
print $field;
print "\n";

?>
--EXPECT--
100 0  _0first post
       _anothing
       _ta lot
       _zeverything
       _ka bit more
       _ga little
PKN1[�c����#File_MARC/tests/marc_xml_16642.phptnu�[���--TEST--
marc_xml_16642: Fix bug 16642: ensure tag and subfield values are returned as strings
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
// Retrieve a set of MARC records from a file
$marc_file = new File_MARCXML($dir . '/' . 'onerecord.xml');
// Iterate through the retrieved records
while ($record = $marc_file->next()) {
   foreach ($record->getFields() as $tag => $subfields) {
       // Skip everything except for 650 fields
       if ($tag == '650') {
           print "Subject:";
           foreach ($subfields->getSubfields() as $code => $value) {
               print " $value";
           }
           print "\n";
       }
   }
}
?>
--EXPECT--
Subject: [a]: Arithmetic [x]: Juvenile poetry.
Subject: [a]: Children's poetry, American.
Subject: [a]: Arithmetic [x]: Poetry.
Subject: [a]: American poetry.
Subject: [a]: Visual perception.
PKN1[�è{{File_MARC/tests/marc_020.phptnu�[���--TEST--
marc_020: Test MARC binary output
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Get ourselves a MARC record
$marc_file = new File_MARC($dir . '/' . 'example.mrc');
$marc_record = $marc_file->next();

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// create a data field
$data_field = new File_MARC_Data_Field('100', $subfields, '0');

// append the data field
$marc_record->appendField($data_field);

// create a control field
$ctrl_field = new File_MARC_Control_Field('001', '01234567890');

// prepend the control field
$marc_record->prependField($ctrl_field);

// reproduce test case reported by Mark Jordan
$subfields_966_2[] = new File_MARC_Subfield('l', 'web');
$subfields_966_2[] = new File_MARC_Subfield('r', '0');
$subfields_966_2[] = new File_MARC_Subfield('s', 'b');
$subfields_966_2[] = new File_MARC_Subfield('i', '49');
$subfields_966_2[] = new File_MARC_Subfield('c', '1');
$field_966_2 = new File_MARC_Data_Field('966', $subfields_966_2, null, null);
$marc_record->appendField($field_966_2);

// let's see the results
print convert_uuencode($marc_record->toRaw());

?>
--EXPECT--
M,#$Y-#,@("`@(#(R,#`U-3,@("`T-3`P,#`Q,#`Q,C`P,#`P,#`Q,#`Q,3`P
M,#$R,#`S,#`P-S`P,#(S,#`X,#`S.3`P,#,P,#(P,#`R-C`P,#8Y,#,U,#`Q
M-3`P,#DU,#0P,#`P-S`P,3$P,#0R,#`Q,C`P,3$W,#@T,#`Q.#`P,3(Y,#@T
M,#`Q.#`P,30W,#@T,#`R,3`P,38U,#@T,#`R,C`P,3@V,3`P,#`S,#`P,C`X
M,C0U,#`V,C`P,C,X,C4P,#`Q,S`P,S`P,C8P,#`U.#`P,S$S,S`P,#`S,S`P
M,S<Q-#0P,#`S-S`P-#`T-3`P,#`R,S`P-#0Q-3DY,#`Q,#`P-#8T-S0P,#`R
M-#`P-#<T-S<U,#`S-#`P-#DX.#0Q,#`T.#`P-3,R.#0Q,#`T.3`P-3@P.#0Q
M,#`T-S`P-C(Y.#0Q,#`T.#`P-C<V.#0Q,#`T-S`P-S(T.#0Q,#`T-S`P-S<Q
M.#4R,#`S.#`P.#$X.#4R,#`R,3`P.#4V.#4R,#`Q,S`P.#<W.#4R,#`Q-C`P
M.#DP.#4R,#`R.#`P.3`V.#4R,#`R,3`P.3,T.3`P,#`U-C`P.34U.3`P,#`V
M,#`Q,#$Q.3`P,#`U-S`Q,#<Q.3`P,#`U-C`Q,3(X.3`P,#`U-S`Q,3@T.3`P
M,#`V,#`Q,C0Q.3<V,#`R-C`Q,S`Q,#`U,#`Q-S`Q,S(W,3`P,#`R-#`Q,S0T
M.38V,#`R,3`Q,S8X'C`Q,C,T-38W.#DP'C`P,#`P,#`P-#0>14U)3$1!'CDX
M,#$R,',Q.3DX("`@(&9I("`@("!J("`@("`@,#`P(#`@<W=E'B`@'V$Y-3$U
M,#`X.#`X'V-&24T@-S(Z,#`>("`?.3DU,34P,#@X,#@>("`?84Y"'B`@'SE.
M0A\Y4T5%'B`@'V%(8V0L=1\R:W-S8B\V'B`@'S5.0A]A=4AC'S)K<W-B'B`@
M'S53144?84AC9A\R:W-S8B\V'B`@'S51'V%(8V0L=68?,FMS<V(O-AXQ(!]A
M2F%N<W-O;BP@5&]V92P?9#$Y,30M,C`P,1XP-!]A1&5T(&]S>6YL:6=A(&)A
M<FYE="!O8V@@86YD<F$@8F5RY'1T96QS97(@+Q]C5&]V92!*86YS<V]N'B`@
M'V$W+B!U<'!L+AX@(!]A2&5L<VEN9V9O<G,@.A]B4V-H:6QD="P?8S$Y.3@@
M.Q]E*$9A;'5N(#H?9E-C86YD8F]O:RD>("`?83$V-BP@6S1=(',N(#H?8FEL
M;"X@.Q]C,C$@8VT>(#`?84UU;6EN+6)I8FQI;W1E:V5T+!]X.3DM,#8Y.#DS
M,2TY'B`@'V%/<FEG:6YA;'5P<&PN(#$Y-C(>("`?84QI.B!3'C0@'V%$970@
M;W-Y;FQI9V$@8F%R;F5T'C$@'WHY-3$M-3`M,#,X-2TW'W<Y-3$U,#`S.#4W
M'SDP-QX@(!\U3&D?87AA'V(P,C`Q,#@P=2`@("`P("`@-#`P,'5U("`@?#`P
M,#`P,!]E,1X@(!\U4T5%'V%X81]B,#(P,3`X,'4@("`@,"`@(#0P,#!U=2`@
M('PP,#`P,#`?93$>("`?-4P?87AA'V(P,C`Q,#@P=2`@("`P("`@-#`P,'5U
M("`@?#`P,#`P,!]E,1X@(!\U3D(?87AA'V(P,C`Q,#@P=2`@("`P("`@-#`P
M,'5U("`@?#`P,#`P,!]E,1X@(!\U41]A>&$?8C`R,#$P.#!U("`@(#`@("`T
M,#`P=74@("!\,#`P,#`P'V4Q'B`@'S53'V%X81]B,#(P,3`X,'4@("`@,"`@
M(#0P,#!U=2`@('PP,#`P,#`?93$>("`?-4Y"'V).0A]C3D(Y.#HQ,A]H<&QI
M:W0?:E(L(#DX,#4R,!X@(!\U3&D?8DQI'V-#3D(?:&@L=1X@(!\U4T5%'V)3
M144>("`?-5$?8E$?:CDX.30W'B`@'S5,'V),'V,P,3`P'V@Y."\?:C,P-#,@
M2!X@(!\U4Q]B4Q]H4W8Y-Q]J-S(S-1XQ<Q]A66%N<V]N+"!4;V)E+!]D,3DQ
M-"TR,#`Q'W5*86YS<V]N+"!4;W9E+!]D,3DQ-"TR,#`Q'C%S'V%*86YS<V]N
M;W;A+"!4;W9E+!]D,3DQ-"TR,#`Q'W5*86YS<V]N+"!4;W9E+!]D,3DQ-"TR
M,#`Q'C%S'V%*86YS;VYE+"!4=79E+!]D,3DQ-"TR,#`Q'W5*86YS<V]N+"!4
M;W9E+!]D,3DQ-"TR,#`Q'C%S'V%*86YS;VXL(%1U=F4L'V0Q.3$T+3(P,#$?
M=4IA;G-S;VXL(%1O=F4L'V0Q.3$T+3(P,#$>,7,?84IA;G-S;VXL(%1U=F4L
M'V0Q.3$T+3(P,#$?=4IA;G-S;VXL(%1O=F4L'V0Q.3$T+3(P,#$>,7,?84IA
M;G-S;VYO=F$L(%1O=F4L'V0Q.3$T+3(P,#$?=4IA;G-S;VXL(%1O=F4L'V0Q
M.3$T+3(P,#$>(#(?84AC9"QU'V)3:_9N;&ET=&5R871U<AXR,#`U,#(P-#$Q
M,34Q."XP'C`@'V%N;W1H:6YG'WIE=F5R>71H:6YG'B`@'VQW96(?<C`?<V(?
(:30Y'V,Q'AT`
`
PKN1[Ҕ��	�	File_MARC/tests/marc_16783.phptnu�[���--TEST--
marc_16783: iterate and pretty print a non-compliant MARC record (tag = '30-')
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'bad_example.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01853    a2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
020    _a9515008808
       _cFIM 72:00
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra bert̃telser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
841    _5Li
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5SEE
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5L
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5NB
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5Q
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5S
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
852    _5NB
       _bNB
       _cNB98:12
       _hplikt
       _jR, 980520
852    _5Li
       _bLi
       _cCNB
       _hh,u
852    _5SEE
       _bSEE
852    _5Q
       _bQ
       _j98947
852    _5L
       _bL
       _c0100
       _h98/
       _j3043 H
852    _5S
       _bS
       _hSv97
       _j7235
900 1s _aYanson, Tobe,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonov,̀ Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansone, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonova, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
976  2 _aHcd,u
       _bSkn̲litteratur
005     20050204111518.0
PKN1[F�-//#File_MARC/tests/marc_field_002.phptnu�[���--TEST--
marc_field_002: Create fields with invalid indicators
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// test constructor
try {
    $field = new File_MARC_Data_Field('100', $subfields, '$@');
}
catch (Exception $e) {
    print "Error: {$e->getMessage()}\n";
}
--EXPECT--
Error: Illegal indicator "$@" in field "100" forced to blank
PKN1[��	\��"File_MARC/tests/marc_lint_001.phptnu�[���--TEST--
marc_lint_001: Full test of Lint suite
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
<?php include('tests/skipif_noispn.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_lint = new File_MARC_Lint();

print "Test records in camel.mrc\n";
$marc_file = new File_MARC($dir . '/' . 'camel.mrc');
while ($marc_record = $marc_file->next()) {
  $warnings = $marc_lint->checkRecord($marc_record);
  foreach ($warnings as $warning) {
    print $warning . "\n";
  }
}

print "\nTest from a constructed record\n";
$rec = new File_MARC_Record();
$rec->setLeader("00000nam  22002538a 4500");
$rec->appendField(
    new File_MARC_Data_Field(
        '041',
        array(
            new File_MARC_Subfield('a', 'end'),
            new File_MARC_Subfield('a', 'fren')
        ),
        "0", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '043',
        array(
            new File_MARC_Subfield('a', 'n-us-pn')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '082',
        array(
            new File_MARC_Subfield('a', '005.13/3'),
            // typo 'R' for 'W' and missing 'b' subfield
            new File_MARC_Subfield('R', 'all'),
            new File_MARC_Subfield('2', '21')
        ),
        "0", "4"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '082',
        array(
            new File_MARC_Subfield('a', '005.13'),
            new File_MARC_Subfield('b', 'Wall'),
            new File_MARC_Subfield('2', '14')
        ),
        "1", "4"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '100',
        array(
            new File_MARC_Subfield('a', 'Wall, Larry')
        ),
        "1", "4"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '110',
        array(
            new File_MARC_Subfield('a', "O'Reilly & Associates.")
        ),
        "1", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '245',
        array(
            new File_MARC_Subfield('a', 'Programming Perl / '),
            new File_MARC_Subfield('a', 'Big Book of Perl /'),
            new File_MARC_Subfield('c', 'Larry Wall, Tom Christiansen & Jon Orwant.')
        ),
        "9", "0"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '250',
        array(
            new File_MARC_Subfield('a', '3rd ed.')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '250',
        array(
            new File_MARC_Subfield('a', '3rd ed.')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '260',
        array(
            new File_MARC_Subfield('a', 'Cambridge, Mass. : '),
            new File_MARC_Subfield('b', "O'Reilly, "),
            new File_MARC_Subfield('r', '2000.')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '590',
        array(
            new File_MARC_Subfield('a', 'Personally signed by Larry.')
        ),
        "4", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '650',
        array(
            new File_MARC_Subfield('a', 'Perl (Computer program language)'),
            new File_MARC_Subfield('0', '(DLC)sh 95010633')
        ),
        "", "0"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '856',
        array(
            new File_MARC_Subfield('u', 'http://www.perl.com/')
        ),
        "4", "3"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '886',
        array(
            new File_MARC_Subfield('4', 'Some foreign thing'),
            new File_MARC_Subfield('q', 'Another foreign thing')
        ),
        "0", ""
    )
);
$warnings = $marc_lint->checkRecord($rec);
foreach ($warnings as $warning) {
  print $warning . "\n";
}

?>
--EXPECT--
Test records in camel.mrc
100: Indicator 1 must be 0, 1 or 3 but it's "2"
007: Subfields are not allowed in fields lower than 010

Test from a constructed record
1XX: Only one 1XX tag is allowed, but I found 2 of them.
041: Subfield _a, end (end), is not valid.
041: Subfield _a must be evenly divisible by 3 or exactly three characters if ind2 is not 7, (fren).
043: Subfield _a, n-us-pn, is not valid.
082: Subfield _R is not allowed.
100: Indicator 2 must be blank but it's "4"
245: Indicator 1 must be 0 or 1 but it's "9"
245: Subfield _a is not repeatable.
260: Subfield _r is not allowed.
856: Indicator 2 must be blank, 0, 1, 2 or 8 but it's "3"
PKN1[rP��!File_MARC/tests/marc_xml_004.phptnu�[���--TEST--
marc_xml_004: test conversion to XML of subfields that need to be escaped
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'xmlescape.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toXML();
  print "\n";
}
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record>
  <leader>00727nam  2200205 a 4500</leader>
  <controlfield tag="001">03-0016458</controlfield>
  <controlfield tag="005">19971103184734.0</controlfield>
  <controlfield tag="008">970701s1997    oru          u000 0 eng u</controlfield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(Sirsi) a351664</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">ML270.2</subfield>
   <subfield code="b">.A6 1997</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Anthony, James R.</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="0">
   <subfield code="a">French baroque music from Beaujoyeulx to Rameau</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
   <subfield code="a">Rev. and expanded ed.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">Portland, OR :</subfield>
   <subfield code="b">Amadeus Press,</subfield>
   <subfield code="c">1997.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">586 p. :</subfield>
   <subfield code="b">music</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Music</subfield>
   <subfield code="&lt;">France</subfield>
   <subfield code="y">16th century</subfield>
   <subfield code="x">History and criticism.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Music</subfield>
   <subfield code="z">France</subfield>
   <subfield code="y">17th century</subfield>
   <subfield code="x">History and criticism.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Music</subfield>
   <subfield code="z">France</subfield>
   <subfield code="y">18th century</subfield>
   <subfield code="x">History and criticism.</subfield>
  </datafield>
  <datafield tag="949" ind1=" " ind2=" ">
   <subfield code="a">ML 270.2 A6 1997</subfield>
   <subfield code="w">LC</subfield>
   <subfield code="i">30007006841505</subfield>
   <subfield code="r">Y</subfield>
   <subfield code="t">BOOKS</subfield>
   <subfield code="l">HUNT-CIRC</subfield>
   <subfield code="m">HUNTINGTON</subfield>
  </datafield>
  <datafield tag="596" ind1=" " ind2=" ">
   <subfield code="a">1</subfield>
  </datafield>
 </record>
</collection>
PKN1[�0�S��&File_MARC/tests/marc_subfield_001.phptnu�[���--TEST--
marc_subfield_001: Exercise basic methods for File_MARC_Subfield class
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// test constructor
$subfield = new File_MARC_Subfield('a', 'wasssup');

// test get methods
print "Code: " . $subfield->getCode() . "\n";
print "Data: " . $subfield->getData() . "\n";

// test __toString implementation
print $subfield;
print "\n";

// test raw output implementation
print $subfield->toRaw() . "\n";

// test isEmpty()
if ($subfield->isEmpty()) {
    print "Subfield is empty\n";
}
else {
    print "Subfield is not empty\n";
}
?>
--EXPECT--
Code: a
Data: wasssup
[a]: wasssup
awasssup
Subfield is not empty
PKN1[x;��##File_MARC/tests/marc_006.phptnu�[���--TEST--
marc_006: test read.php
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php

$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Read MARC records from a stream (a file, in this case)
$marc_source = new File_MARC($dir . '/' . 'example.mrc');

// Retrieve the first MARC record from the source
$marc_record = $marc_source->next();

// Retrieve a personal name field from the record
$names = $marc_record->getFields('100');
foreach ($names as $name_field) {
    // Now print the $a subfield
    switch ($name_field->getIndicator(1)) {
    case 0:
	print "Forename: ";
	break;

    case 1:
	print "Surname: ";
	break;

    case 2:
	print "Family name: ";
	break;
    }
    $name = $name_field->getSubfields('a');
    if (count($name) == 1) {
	print $name[0]->getData() . "\n";
    }
    else {
	print "Error -- \$a subfield appears more than once in this field!";
    }
}

// Retrieve all series statement fields
// Series statement fields start with a 4 (PCRE)
$subjects = $marc_record->getFields('^4', true);

// Iterate through all of the returned series statement fields
foreach ($subjects as $field) {
    // print with File_MARC_Field_Data's magic __toString() method
    print $field;
}

?>
--EXPECT--
Surname: Jansson, Tove,
440  0 _aMumin-biblioteket,
       _x99-0698931-9
PKN1[}&�
GG"File_MARC/tests/marc_lint_004.phptnu�[���--TEST--
marc_lint_004: Tests check_245() called separately
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
<?php include('tests/skipif_noispn.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Create test harness to allow direct calls to check methods:
class File_MARC_Lint_Test_Harness extends File_MARC_Lint
{
    public function check245($field)
    {
        return parent::check245($field);
    }

    // override warn method to echo instead of store in object:
    protected function warn($msg)
    {
        echo $msg . "\n";
    }
}

$marc_lint = new File_MARC_Lint_Test_Harness();

$testData = array(
    array(245, '0', '0', 'a', 'Subfield a.'),
    array(245, '0', '0', 'b', 'no subfield a.'),
    array(245, '0', '0', 'a', 'No period at end'),
    array(245, '0', '0', 'a', 'Other punctuation not followed by period!'),
    array(245, '0', '0', 'a', 'Other punctuation not followed by period?'),
    array(245, '0', '0', 'a', 'Precedes sub c', 'c', 'not preceded by space-slash.'),
    array(245, '0', '0', 'a', 'Precedes sub c/', 'c', 'not preceded by space-slash.'),
    array(245, '0', '0', 'a', 'Precedes sub c /', 'c', 'initials in sub c B. B.'),
    array(245, '0', '0', 'a', 'Precedes sub c /', 'c', 'initials in sub c B.B. (no warning).'),
    array(245, '0', '0', 'a', 'Precedes sub b', 'b', 'not preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b=', 'b', 'not preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b:', 'b', 'not preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b;', 'b', 'not preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b =', 'b', 'preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b :', 'b', 'preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub b ;', 'b', 'preceded by proper punctuation.'),
    array(245, '0', '0', 'a', 'Precedes sub h ', 'h', '[videorecording].'),
    array(245, '0', '0', 'a', 'Precedes sub h-- ', 'h', '[videorecording] :', 'b', 'with elipses dash before h.'),
    array(245, '0', '0', 'a', 'Precedes sub h-- ', 'h', 'videorecording :', 'b', 'without brackets around GMD.'),
    array(245, '0', '0', 'a', 'Precedes sub n.', 'n', 'Number 1.'),
    array(245, '0', '0', 'a', 'Precedes sub n', 'n', 'Number 2.'),
    array(245, '0', '0', 'a', 'Precedes sub n.', 'n', 'Number 3.', 'p', 'Sub n has period not comma.'),
    array(245, '0', '0', 'a', 'Precedes sub n.', 'n', 'Number 3,', 'p', 'Sub n has comma.'),
    array(245, '0', '0', 'a', 'Precedes sub p.', 'p', 'Sub a has period.'),
    array(245, '0', '0', 'a', 'Precedes sub p', 'p', 'Sub a has no period.'),
    array(245, '0', 'a', 'a', 'Invalid filing indicator.'),
    array(245, '0', '0', 'a', 'The article.'),
    array(245, '0', '4', 'a', 'The article.'),
    array(245, '0', '2', 'a', 'An article.'),
    array(245, '0', '0', 'a', "L'article."),
    array(245, '0', '2', 'a', 'A la mode.'),
    array(245, '0', '5', 'a', 'The "quoted article".'),
    array(245, '0', '5', 'a', 'The (parenthetical article).'),
    array(245, '0', '6', 'a', '(The) article in parentheses).'),
    array(245, '0', '9', 'a', "\"(The)\" 'article' in quotes and parentheses)."),
    array(245, '0', '5', 'a', '[The supplied title].')
);

foreach ($testData as $current) {
    $subfields = array();
    for ($i = 3; $i < count($current); $i+=2) {
        $subfields[] = new File_MARC_Subfield($current[$i], $current[$i+1]);
    }

    $field = new File_MARC_Data_Field(
        $current[0], $subfields, $current[1], $current[2]
    );
    $marc_lint->check245($field);
}

?>
--EXPECT--
245: Must have a subfield _a.
245: First subfield must be _a, but it is _b
245: Must end with . (period).
245: MARC21 allows ? or ! as final punctuation but LCRI 1.0C, Nov. 2003 (LCPS 1.7.1 for RDA records), requires period.
245: MARC21 allows ? or ! as final punctuation but LCRI 1.0C, Nov. 2003 (LCPS 1.7.1 for RDA records), requires period.
245: Subfield _c must be preceded by /
245: Subfield _c must be preceded by /
245: Subfield _c initials should not have a space.
245: Subfield _b should be preceded by space-colon, space-semicolon, or space-equals sign.
245: Subfield _b should be preceded by space-colon, space-semicolon, or space-equals sign.
245: Subfield _b should be preceded by space-colon, space-semicolon, or space-equals sign.
245: Subfield _b should be preceded by space-colon, space-semicolon, or space-equals sign.
245: Subfield _h should not be preceded by space.
245: Subfield _h must have matching square brackets, videorecording :.
245: Subfield _n must be preceded by . (period).
245: Subfield _p must be preceded by , (comma) when it follows subfield _n.
245: Subfield _p must be preceded by . (period) when it follows a subfield other than _n.
245: Non-filing indicator is non-numeric
245: First word, the, may be an article, check 2nd indicator (0).
245: First word, an, may be an article, check 2nd indicator (2).
245: First word, l, may be an article, check 2nd indicator (0).
245: First word, a, does not appear to be an article, check 2nd indicator (2).
PKN1[�cܯ�!File_MARC/tests/marc_xml_006.phptnu�[���--TEST--
marc_xml_006: test getFields() in XML
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php

$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Read MARC records from a stream (a file, in this case)
$marc_source = new File_MARCXML($dir . '/' . 'sandburg.xml');

// Retrieve the first MARC record from the source
$marc_record = $marc_source->next();

// Retrieve a personal name field from the record
$names = $marc_record->getFields('100');
foreach ($names as $name_field) {
    // Now print the $a subfield
    switch ($name_field->getIndicator(1)) {
    case 0:
	print "Forename: ";
	break;

    case 1:
	print "Surname: ";
	break;

    case 2:
	print "Family name: ";
	break;
    }
    $name = $name_field->getSubfields('a');
    if (count($name) == 1) {
	print $name[0]->getData() . "\n";
    }
    else {
	print "Error -- \$a subfield appears more than once in this field!";
    }
}

// Retrieve all subject and genre fields
// Series statement fields start with a 6 (PCRE)
$subjects = $marc_record->getFields('^6', true);

// Iterate through all of the returned subject fields
foreach ($subjects as $field) {
    // print with File_MARC_Field_Data's magic __toString() method
    print "$field\n";
}

?>
--EXPECT--
Surname: Sandburg, Carl,
650  0 _aArithmetic
       _xJuvenile poetry.
650  0 _aChildren's poetry, American.
650  1 _aArithmetic
       _xPoetry.
650  1 _aAmerican poetry.
650  1 _aVisual perception.
PKN1[���
��#File_MARC/tests/marc_field_005.phptnu�[���--TEST--
marc_field_005: Test method getContents
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// create a field
$field = new File_MARC_Data_Field('100', $subfields, '0');

// create some new subfields
$subfield1 = new File_MARC_Subfield('g', 'a little');

// test the fieldpost corner case by inserting prior to the first subfield
$sf = $field->getSubfields('a');
// we might get an array back; in this case, we want the first subfield
if (is_array($sf)) {
  $field->insertSubfield($subfield1, $sf[0], true);
}
else {
  $field->insertSubfield($subfield1, $sf, true);
}

// let's see the results
print $field->getContents();
print "\n";
print $field->getContents('###');
print "\n";

?>
--EXPECT--
a littlenothingeverything
a little###nothing###everything
PKN1[��%HhhFile_MARC/tests/marc_003.phptnu�[���--TEST--
marc_003: getFields() with various regular expressions
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

print "Test with a simple string\n";
while ($marc_record = $marc_file->next()) {
  print "\nNext record:\n";
  $fields = $marc_record->getFields('650');
  foreach ($fields as $field) {
    print $field;
    print "\n";
  }
}

print "\nTest with regular expression\n";
$marc_file = new File_MARC($dir . '/' . 'music.mrc');
while ($marc_record = $marc_file->next()) {
  print "\nNext record:\n";
  $fields = $marc_record->getFields('00\d', true);
  foreach ($fields as $field) {
    print $field;
    print "\n";
  }
}

?>
--EXPECT--
Test with a simple string

Next record:
650  0 _aJazz.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.

Next record:
650  0 _aJazz
       _y1971-1980.

Next record:
650  0 _aJazz.

Test with regular expression

Next record:
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   

Next record:
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d

Next record:
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
PKN1[(���NNFile_MARC/tests/camel.mrcnu�[���00755cam  22002414a 4500001001300000003000600013005001700019008004100036010001700077020004300094040001800137042000800155050002600163082001700189100003100206245005400237260004200291300007200333500003300405650003700438630002500475630001300500fol05731351 IMchF20000613133448.0000107s2000    nyua          001 0 eng    a   00020737   a0471383147 (paper/cd-rom : alk. paper)  aDLCcDLCdDLC  apcc00aQA76.73.P22bM33 200000a005.13/32211 aMartinsson, Tobias,d1976-10aActivePerl with ASP and ADO /cTobias Martinsson.  aNew York :bJohn Wiley & Sons,c2000.  axxi, 289 p. :bill. ;c23 cm. +e1 computer  laser disc (4 3/4 in.)  a"Wiley Computer Publishing." 0aPerl (Computer program language)00aActive server pages.00aActiveX.00647pam  2200241 a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001800109042000800127050002600135082001500161100002600176245006700202260003800269263000900307300001100316650003700327650002500364700001600389fol05754809 IMchF20000601115601.0000203s2000    mau           001 0 eng    a   00022023   a1565926994  aDLCcDLCdDLC  apcc00aQA76.73.P22bD47 200000a005.742211 aDescartes, Alligator.10aProgramming the Perl DBI /cAlligator Descartes and Tim Bunce.  aCmabridge, MA :bO'Reilly,c2000.  a1111  ap. cm. 0aPerl (Computer program language) 0aDatabase management.1 aBunce, Tim.00605cam  22002054a 4500001001300000003000600013005001700019008004100036010001700077040001800094042000800112050002700120082001700147100002100164245005500185260004500240300002600285504005100311650003700362fol05843555 IMchF20000525142739.0000318s1999    cau      b    001 0 eng    a   00501349   aDLCcDLCdDLC  apcc00aQA76.73.P22bB763 199900a005.13/32211 aBrown, Martin C.10aPerl :bprogrammer's reference /cMartin C. Brown.  aBerkeley :bOsborne/McGraw-Hill,cc1999.  axix, 380 p. ;c22 cm.  aIncludes bibliographical references and index. 0aPerl (Computer program language)00579cam  22002054a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001800109042000800127050002700135082001700162100002100179245005500200260004500255300003600300650003700336fol05843579 IMchF20000525142716.0000318s1999    caua          001 0 eng    a   00502116   a0072120002  aDLCcDLCdDLC  apcc00aQA76.73.P22bB762 199900a005.13/32211 aBrown, Martin C.10aPerl :bthe complete reference /cMartin C. Brown.  aBerkeley :bOsborne/McGraw-Hill,cc1999.  axxxv, 1179 p. :bill. ;c24 cm. 0aPerl (Computer program language)00801nam  22002778a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001300109042000800122050002600130082001800156100002000174245008800194250003200282260004100314263000900355300001100364650003700375650003600412650002600448700002500474700002400499fol05848297 IMchF20000524125727.0000518s2000    mau           001 0 eng    a   00041664   a1565924193  aDLCcDLC  apcc00aQA76.73.P22bG84 200000a005.2/7622211 aGuelich, Scott.10aCGI programming with Perl /cScott Guelich, Shishir Gundavaram & Gunther Birznieks.  a2nd ed., expanded & updated  aCambridge, Mass. :bO'Reilly,c2000.  a0006  ap. cm. 0aPerl (Computer program language) 0aCGI (Computer network protocol) 0aInternet programming.1 aGundavaram, Shishir.1 aBirznieks, Gunther.00665nam  22002298a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001300109042000800122050002700130082001700157111005200174245008600226250001200312260004100324263000900365300001100374650005000385fol05865950 IMchF20000615103017.0000612s2000    mau           100 0 eng    a   00055759   a0596000138  aDLCcDLC  apcc00aQA76.73.P22bP475 200000a005.13/32212 aPerl Conference 4.0d(2000 :cMonterey, Calif.)10aProceedings of the Perl Conference 4.0 :bJuly 17-20, 2000, Monterey, California.  a1st ed.  aCambridge, Mass. :bO'Reilly,c2000.  a0006  ap. cm. 0aPerl (Computer program language)vCongresses.00579nam  22002178a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001300109042000800122050002600130082001700156100002800173245006200201260004100263263000900304300001100313650003700324fol05865956 IMchF20000615102948.0000612s2000    mau           000 0 eng    a   00055770   a1565926099  aDLCcDLC  apcc00aQA76.73.P22bB43 200000a005.13/32211 aBlank-Edelman, David N.10aPerl for system administration /cDavid N. Blank-Edelman.  aCambridge, Mass. :bO'Reilly,c2000.  a0006  ap. cm. 0aPerl (Computer program language)00661nam  22002538a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001300109042000800122050002600130082001700156100001700173245006700190250001200257260004100269263000900310300001100319650003700330700002300367700001700390fol05865967 IMchF20000615102611.0000614s2000    mau           000 0 eng    a   00055799   a0596000278  aDLCcDLC  apcc00aQA76.73.P22bW35 200000a005.13/32211 aWall, Larry.10aProgramming Perl /cLarry Wall, Tom Christiansen & Jon Orwant.  a3rd ed.  aCambridge, Mass. :bO'Reilly,c2000.  a0007  ap. cm. 0aPerl (Computer program language)1 aChristiansen, Tom.1 aOrwant, Jon.00603cam  22002054a 4500001001300000003000600013005001700019008004100036010001700077020001500094040001800109042000800127050002600135082001700161100003200178245006000210260005700270300003300327650003700360fol05872355 IMchF20000706095105.0000315s1999    njua          001 0 eng    a   00500678   a013020868X  aDLCcDLCdDLC  apcc00aQA76.73.P22bL69 199900a005.13/32211 aLowe, Vincentq(Vincent D.)10aPerl programmer's interactive workbook /cVincent Lowe.  aUpper Saddle River, NJ :bPrentice Hall PTP,cc1999.  axx, 633 p. :bill. ;c23 cm. 0aPerl (Computer program language)00696nam  22002538a 4500001001300000003000600013005001700019008004100036010001700077020002800094040001300122042000800135050002600143082001700169100002600186245004400212260005100256263000900307300001100316500002000327650003700347650001700384650004100401fol05882032 IMchF20000707091904.0000630s2000    cau           001 0 eng    a   00058174   a0764547291 (alk. paper)  aDLCcDLC  apcc00aQA76.73.P22bF64 200000a005.13/32212 aFoster-Johnson, Eric.10aCross-platform Perl /cEric F. Johnson.  aFoster City, CA :bIDG Books Worldwide,c2000.  a0009  ap. cm.  aIncludes index. 0aPerl (Computer program language) 0aWeb servers. 0aCross-platform software development.00399ngm  2200121 a 4500001001300000003000700013007002800020008004100048245005600089260003800145300006000183538003400243ttt05000099 TEST  avbfc dcebfaghhoiu050224s2005    ilu999            vleng d00aTest subfields in control fieldsh[videorecording].  aOregon, Ill. :bB. Baldus,c2005.  a1 videocassette (ca. 1000 min.) :bsd., col. ;c1/2 in.  aVHS format, SP playback mode.PKN1[�p�޸�File_MARC/tests/marc_007.phptnu�[���--TEST--
marc_007: Use key=>value iteration for tags and codes
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

if ($marc_record = $marc_file->next()) {
    foreach ($marc_record->getFields() as $tag=>$value) {
        print "$tag: ";
	    if ($value instanceof File_MARC_Control_Field) {
                print $value->getData();
            }
	    else {
                foreach ($value->getSubfields() as $code=>$subdata) {
                    print "_$code";
                }
            }
        print "\n";
    }
}
?>
--EXPECT--
001: 0000000044
003: EMILDA
008: 980120s1998    fi     j      000 0 swe
020: _a_c
035: _9
040: _a
042: _9_9
084: _a_2
084: _5_a_2
084: _5_a_2
084: _5_a_2
100: _a_d
245: _a_c
250: _a
260: _a_b_c_e_f
300: _a_b_c
440: _a_x
500: _a
599: _a
740: _a
775: _z_w_9
841: _5_a_b_e
841: _5_a_b_e
841: _5_a_b_e
841: _5_a_b_e
841: _5_a_b_e
841: _5_a_b_e
852: _5_b_c_h_j
852: _5_b_c_h
852: _5_b
852: _5_b_j
852: _5_b_c_h_j
852: _5_b_h_j
900: _a_d_u_d
900: _a_d_u_d
900: _a_d_u_d
900: _a_d_u_d
900: _a_d_u_d
900: _a_d_u_d
976: _a_b
005: 20050204111518.0
PKN1[����1�1!File_MARC/tests/marc_xml_008.phptnu�[���--TEST--
marc_xml_008: generate a single collection of MARCXML records from a MARCXML record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$records = new File_MARCXML($dir . '/' . 'music.xml');

// Add the XML header and opening <collection> element
$records->toXMLHeader();

// Iterate through the retrieved records
while ($record = $records->next()) {

    // Change each 852 $c to "Audio-Visual"
    $holdings = $record->getFields('852');
    foreach ($holdings as $holding) {

        // Get the $c subfields from this field
        $formats = $holding->getSubfields('c');
        foreach ($formats as $format) {
            if ($format->getData('AV')) {
                $format->setData('Audio-Visual');
            }
        }
    }

    // Generate the XML output for this record
    print $record->toXML('UTF-8', true, false);
}
// Add the </collection> closing element and dump the XMLWriter contents
print $records->toXMLFooter();
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01145ncm a2200277 i 4500</leader>
  <controlfield tag="001">000073594</controlfield>
  <controlfield tag="004">AAJ5802</controlfield>
  <controlfield tag="005">20030415102100.0</controlfield>
  <controlfield tag="008">801107s1977    nyujza                   </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   77771106 </subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(CaOTUIC)15460184</subfield>
  </datafield>
  <datafield tag="035" ind1="9" ind2=" ">
   <subfield code="a">AAJ5802</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">LC</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">M1366</subfield>
   <subfield code="b">.M62</subfield>
   <subfield code="d">M1527.2</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="4">
   <subfield code="a">The Modern Jazz Quartet :</subfield>
   <subfield code="b">The legendary profile. --</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">New York :</subfield>
   <subfield code="b">M.J.Q. Music,</subfield>
   <subfield code="c">c1977.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">score (72 p.) ;</subfield>
   <subfield code="c">31 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">For piano, vibraphone, drums, and double bass.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">Lewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B́Ư.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Motion picture music</subfield>
   <subfield code="v">Excerpts</subfield>
   <subfield code="v">Scores.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Lewis, John,</subfield>
   <subfield code="d">1920-</subfield>
   <subfield code="t">Selections.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Martyrs.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Legendary profile.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
   <subfield code="a">The legendary profile.</subfield>
  </datafield>
  <datafield tag="852" ind1="0" ind2="0">
   <subfield code="b">MUSIC</subfield>
   <subfield code="c">Audio-Visual</subfield>
   <subfield code="k">folio</subfield>
   <subfield code="h">M1366</subfield>
   <subfield code="i">M62</subfield>
   <subfield code="9">1</subfield>
   <subfield code="4">Marvin Duchow Music</subfield>
   <subfield code="5"></subfield>
  </datafield>
 </record>
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01293cjm a2200289 a 4500</leader>
  <controlfield tag="001">001878039</controlfield>
  <controlfield tag="005">20050110174900.0</controlfield>
  <controlfield tag="007">sd fungnn|||e|</controlfield>
  <controlfield tag="008">940202r19931981nyujzn   i              d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
   <subfield code="a">7464573372</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="2">
   <subfield code="a">JK 57337</subfield>
   <subfield code="b">Red Baron</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(OCoLC)29737267</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">SVP</subfield>
   <subfield code="c">SVP</subfield>
   <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Desmond, Paul,</subfield>
   <subfield code="d">1924-</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
   <subfield code="a">Paul Desmond &amp; the Modern Jazz Quartet</subfield>
   <subfield code="h">[sound recording]</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">New York, N.Y. :</subfield>
   <subfield code="b">Red Baron :</subfield>
   <subfield code="b">Manufactured by Sony Music Entertainment,</subfield>
   <subfield code="c">p1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 sound disc (39 min.) :</subfield>
   <subfield code="b">digital ;</subfield>
   <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
   <subfield code="a">Paul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">All arrangements by John Lewis.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
   <subfield code="a">Recorded live on December 25, 1971 at Town Hall, NYC.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Originally released in 1981 by Finesse as LP FW 27487.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Program notes by Irving Townsend, June 1981, on container insert.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">Greensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz</subfield>
   <subfield code="y">1971-1980.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Lewis, John,</subfield>
   <subfield code="d">1920-</subfield>
  </datafield>
  <datafield tag="710" ind1="2" ind2=" ">
   <subfield code="a">Modern Jazz Quartet.</subfield>
  </datafield>
  <datafield tag="740" ind1="0" ind2=" ">
   <subfield code="a">Paul Desmond and the Modern Jazz Quartet.</subfield>
  </datafield>
 </record>
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01829cjm a2200385 a 4500</leader>
  <controlfield tag="001">001964482</controlfield>
  <controlfield tag="005">20060626132700.0</controlfield>
  <controlfield tag="007">sd fzngnn|m|e|</controlfield>
  <controlfield tag="008">871211p19871957nyujzn                  d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
   <subfield code="a">4228332902</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="1">
   <subfield code="a">833 290-2</subfield>
   <subfield code="b">Verve</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">19571027</subfield>
   <subfield code="b">6299</subfield>
   <subfield code="c">D56</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">196112--</subfield>
   <subfield code="b">3804</subfield>
   <subfield code="c">N4</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">19571019</subfield>
   <subfield code="b">4104</subfield>
   <subfield code="c">C6</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">197107--</subfield>
   <subfield code="b">6299</subfield>
   <subfield code="c">V7</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(OCoLC)17222092</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">CPL</subfield>
   <subfield code="c">CPL</subfield>
   <subfield code="d">OCL</subfield>
   <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="048" ind1=" " ind2=" ">
   <subfield code="a">pz01</subfield>
   <subfield code="a">ka01</subfield>
   <subfield code="a">sd01</subfield>
   <subfield code="a">pd01</subfield>
  </datafield>
  <datafield tag="110" ind1="2" ind2=" ">
   <subfield code="a">Modern Jazz Quartet.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="4">
   <subfield code="a">The Modern Jazz Quartet plus</subfield>
   <subfield code="h">[sound recording].</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">[New York] :</subfield>
   <subfield code="b">Verve,</subfield>
   <subfield code="c">p1987.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 sound disc :</subfield>
   <subfield code="b">digital ;</subfield>
   <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="440" ind1=" " ind2="0">
   <subfield code="a">Compact jazz</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
   <subfield code="a">Modern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
   <subfield code="a">Recorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Compact disc.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Analog recording.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">The golden striker (4:08) -- On Green Dolphin Street (7:28) -- D &amp; E (4:55) -- I'll remember April (4:51) -- Cort©·ge (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Peterson, Oscar,</subfield>
   <subfield code="d">1925-</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Brown, Ray,</subfield>
   <subfield code="d">1926-2002.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Thigpen, Ed.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Hayes, Louis,</subfield>
   <subfield code="d">1937-</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="852" ind1="8" ind2="0">
   <subfield code="b">MUSIC</subfield>
   <subfield code="c">Audio-Visual</subfield>
   <subfield code="h">CD 1131</subfield>
   <subfield code="4">Marvin Duchow Music</subfield>
   <subfield code="5">Audio-Visual</subfield>
  </datafield>
 </record>
</collection>
PKN1[)�]�
�
File_MARC/tests/marc_005.phptnu�[���--TEST--
marc_005: Ensure a duplicated record is a deep copy; test deleteFields()
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

$marc_record = $marc_file->next();
$copy_record = $marc_record;
$duplicate_record = clone $marc_record;

$num_deleted1 = $marc_record->deleteFields('020');
print "Deleted $num_deleted1 fields from the original record.\n";

$num_deleted2 = $copy_record->deleteFields('8\\d\\d', true);
print "Deleted $num_deleted2 fields from the shallow copy record.\n";

$num_deleted3 = $duplicate_record->deleteFields('9\\d\\d', true);
print "Deleted $num_deleted3 fields from the duplicate record.\n";

print "Original:\n";
print $marc_record;

print "\nCopy:\n";
print $copy_record;

print "\nDuplicate:\n";
print $duplicate_record;
print "\n";

?>
--EXPECT--
Deleted 1 fields from the original record.
Deleted 12 fields from the shallow copy record.
Deleted 7 fields from the duplicate record.
Original:
LDR 01850     2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra ber�ttelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
005     20050204111518.0

Copy:
LDR 01850     2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra ber�ttelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
005     20050204111518.0

Duplicate:
LDR 01850     2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra ber�ttelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
005     20050204111518.0
PKN1[	V�U,,%File_MARC/tests/marc_field_21246.phptnu�[���--TEST--
marc_field_21246: Delete multiple subfields
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$field = new File_MARC_Data_Field(650, [
    new File_MARC_Subfield('9', 'test1'),
    new File_MARC_Subfield('9', 'test2'),
    new File_MARC_Subfield('0', 'test3'),
    new File_MARC_Subfield('9', 'test4'),
  ]
);
echo "--- Before: ---\n$field\n\n";
foreach ($field->getSubfields('9') as $subfield) {
  echo "Deleting subfield: $subfield\n";
  $field->deleteSubfield($subfield);
}
echo "\n--- After: ---\n$field\n\n";
?>
--EXPECT--
--- Before: ---
650    _9test1
       _9test2
       _0test3
       _9test4

Deleting subfield: [9]: test1
Deleting subfield: [9]: test2
Deleting subfield: [9]: test4

--- After: ---
650    _0test3
PKN1[�_|6	6	"File_MARC/tests/marc_lint_002.phptnu�[���--TEST--
marc_lint_002: Tests check041() and check043() called separately
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
<?php include('tests/skipif_noispn.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Create test harness to allow direct calls to check methods:
class File_MARC_Lint_Test_Harness extends File_MARC_Lint
{
    public function check041($field)
    {
        return parent::check041($field);
    }

    public function check043($field)
    {
        return parent::check043($field);
    }

    // override warn method to echo instead of store in object:
    protected function warn($msg)
    {
        echo $msg . "\n";
    }
}

$marc_lint = new File_MARC_Lint_Test_Harness();

$field = new File_MARC_Data_Field(
    '041',
    array(
        new File_MARC_Subfield('a', 'end'),             // invalid
        new File_MARC_Subfield('a', 'span'),            // too long
        new File_MARC_Subfield('h', 'far')              // obsolete
    ),
    "0", ""
);
$marc_lint->check041($field);

$field = new File_MARC_Data_Field(
    '041',
    array(
        new File_MARC_Subfield('a', 'endorviwo'),       // invalid
        new File_MARC_Subfield('a', 'spanowpalasba')    // too long and invalid
    ),
    "1", ""
);
$marc_lint->check041($field);

$field = new File_MARC_Data_Field(
    '043',
    array(
        new File_MARC_Subfield('a', 'n-----'),          // 6 chars vs. 7
        new File_MARC_Subfield('a', 'n-us----'),        // 8 chars vs. 7
        new File_MARC_Subfield('a', 'n-ma-us'),         // invalid code
        new File_MARC_Subfield('a', 'e-ur-ai')          // obsolete code
    ),
    "", ""
);
$marc_lint->check043($field);

?>
--EXPECT--
041: Subfield _a, end (end), is not valid.
041: Subfield _a must be evenly divisible by 3 or exactly three characters if ind2 is not 7, (span).
041: Subfield _h, far, may be obsolete.
041: Subfield _a, endorviwo (end), is not valid.
041: Subfield _a, endorviwo (orv), is not valid.
041: Subfield _a, endorviwo (iwo), is not valid.
041: Subfield _a must be evenly divisible by 3 or exactly three characters if ind2 is not 7, (spanowpalasba).
043: Subfield _a must be exactly 7 characters, n-----
043: Subfield _a must be exactly 7 characters, n-us----
043: Subfield _a, n-ma-us, is not valid.
043: Subfield _a, e-ur-ai, may be obsolete.
PKN1[�=O	
	
File_MARC/tests/sandburg.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record>
  <leader>01142cam  2200301 a 4500</leader>
  <controlfield tag="001">   92005291 </controlfield>
  <controlfield tag="003">DLC</controlfield>
  <controlfield tag="005">19930521155141.9</controlfield>
  <controlfield tag="008">920219s1993    caua   j      000 0 eng  </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   92005291 </subfield>
  </datafield>
  <datafield tag="020" ind1=" " ind2=" ">
   <subfield code="a">0152038655 :</subfield>
   <subfield code="c">$15.95</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">DLC</subfield>
   <subfield code="c">DLC</subfield>
   <subfield code="d">DLC</subfield>
  </datafield>
  <datafield tag="042" ind1=" " ind2=" ">
   <subfield code="a">lcac</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">PS3537.A618</subfield>
   <subfield code="b">A88 1993</subfield>
  </datafield>
  <datafield tag="082" ind1="0" ind2="0">
   <subfield code="a">811/.52</subfield>
   <subfield code="2">20</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Sandburg, Carl,</subfield>
   <subfield code="d">1878-1967.</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
   <subfield code="a">Arithmetic /</subfield>
   <subfield code="c">Carl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
   <subfield code="a">1st ed.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">San Diego :</subfield>
   <subfield code="b">Harcourt Brace Jovanovich,</subfield>
   <subfield code="c">c1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 v. (unpaged) :</subfield>
   <subfield code="b">ill. (some col.) ;</subfield>
   <subfield code="c">26 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">One Mylar sheet included in pocket.</subfield>
  </datafield>
  <datafield tag="520" ind1=" " ind2=" ">
   <subfield code="a">A poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Juvenile poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Children's poetry, American.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">American poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Visual perception.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Rand, Ted,</subfield>
   <subfield code="e">ill.</subfield>
  </datafield>
 </record>
</collection>
PKN1[�s}���.File_MARC/tests/marc_xml_namespace_prefix.phptnu�[���--TEST--
marc_xml_namespace: iterate and pretty print a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'namespace.xml',File_MARC::SOURCE_FILE,"marc",true);
while ($marc_record = $marc_file->next()) {
  print $marc_record->getLeader();
  print "\n";
  $field = $marc_record->getField('050');
  print $field->getIndicator(1);
  print "\n";
  print $field->getIndicator(2);
  print "\n";
  $subfield = $field->getSubfield('a');
  print $subfield->getData();
  print "\n";
}
?>
--EXPECT--
00925njm  22002777a 4500
0
0
Atlantic 1259
01832cmma 2200349 a 4500
0
0
F204.W5
PKN1[!Ņ\��!File_MARC/tests/marc_xml_001.phptnu�[���--TEST--
marc_xml_001: iterate and pretty print a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

while ($marc_record = $marc_file->next()) {
  /* Note that this adds characters to the leader to satisfy MARCXML schema */
  print $marc_record->toXML();
  print "\n";
}
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record>
  <leader>01850na   2200517   4500</leader>
  <controlfield tag="001">0000000044</controlfield>
  <controlfield tag="003">EMILDA</controlfield>
  <controlfield tag="008">980120s1998    fi     j      000 0 swe</controlfield>
  <datafield tag="020" ind1=" " ind2=" ">
   <subfield code="a">9515008808</subfield>
   <subfield code="c">FIM 72:00</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="9">9515008808</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">NB</subfield>
  </datafield>
  <datafield tag="042" ind1=" " ind2=" ">
   <subfield code="9">NB</subfield>
   <subfield code="9">SEE</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
   <subfield code="a">Hcd,u</subfield>
   <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
   <subfield code="5">NB</subfield>
   <subfield code="a">uHc</subfield>
   <subfield code="2">kssb</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
   <subfield code="5">SEE</subfield>
   <subfield code="a">Hcf</subfield>
   <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
   <subfield code="5">Q</subfield>
   <subfield code="a">Hcd,uf</subfield>
   <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="4">
   <subfield code="a">Det osynliga barnet och andra ber�ttelser /</subfield>
   <subfield code="c">Tove Jansson</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
   <subfield code="a">7. uppl.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">Helsingfors :</subfield>
   <subfield code="b">Schildt,</subfield>
   <subfield code="c">1998 ;</subfield>
   <subfield code="e">(Falun :</subfield>
   <subfield code="f">Scandbook)</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">166, [4] s. :</subfield>
   <subfield code="b">ill. ;</subfield>
   <subfield code="c">21 cm</subfield>
  </datafield>
  <datafield tag="440" ind1=" " ind2="0">
   <subfield code="a">Mumin-biblioteket,</subfield>
   <subfield code="x">99-0698931-9</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Originaluppl. 1962</subfield>
  </datafield>
  <datafield tag="599" ind1=" " ind2=" ">
   <subfield code="a">Li: S</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
   <subfield code="a">Det osynliga barnet</subfield>
  </datafield>
  <datafield tag="775" ind1="1" ind2=" ">
   <subfield code="z">951-50-0385-7</subfield>
   <subfield code="w">9515003857</subfield>
   <subfield code="9">07</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">Li</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">SEE</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">L</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">NB</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">Q</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
   <subfield code="5">S</subfield>
   <subfield code="a">xa</subfield>
   <subfield code="b">0201080u    0   4000uu   |000000</subfield>
   <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">NB</subfield>
   <subfield code="b">NB</subfield>
   <subfield code="c">NB98:12</subfield>
   <subfield code="h">plikt</subfield>
   <subfield code="j">R, 980520</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">Li</subfield>
   <subfield code="b">Li</subfield>
   <subfield code="c">CNB</subfield>
   <subfield code="h">h,u</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">SEE</subfield>
   <subfield code="b">SEE</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">Q</subfield>
   <subfield code="b">Q</subfield>
   <subfield code="j">98947</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">L</subfield>
   <subfield code="b">L</subfield>
   <subfield code="c">0100</subfield>
   <subfield code="h">98/</subfield>
   <subfield code="j">3043 H</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
   <subfield code="5">S</subfield>
   <subfield code="b">S</subfield>
   <subfield code="h">Sv97</subfield>
   <subfield code="j">7235</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Yanson, Tobe,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Janssonov�, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Jansone, Tuve,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Janson, Tuve,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Jansson, Tuve,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
   <subfield code="a">Janssonova, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
   <subfield code="u">Jansson, Tove,</subfield>
   <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="976" ind1=" " ind2="2">
   <subfield code="a">Hcd,u</subfield>
   <subfield code="b">Sk�nlitteratur</subfield>
  </datafield>
  <controlfield tag="005">20050204111518.0</controlfield>
 </record>
</collection>
PKN1[F;�Re%e%File_MARC/tests/marc_004.phptnu�[���--TEST--
marc_004: Delete fields and subfields
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

print "\nDelete all fields with tag 650\n";
while ($marc_record = $marc_file->next()) {
  print "\nNext record:\n";
  $fields = $marc_record->getFields('650');
  foreach ($fields as $field) {
    $field->delete();
  }
  print $marc_record;
}

$marc_file = null;
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

print "\nDelete all subfields with code 'a' from fields with tag 650\n";
while ($marc_record = $marc_file->next()) {
  print "\nNext record:\n";
  $fields = $marc_record->getFields('650');
  foreach ($fields as $field) {
    $sf = $field->getSubfields('a');
    foreach ($sf as $subfield) {
      $field->deleteSubfield($subfield);
    }
  }
  print $marc_record;
}

?>
--EXPECT--
Delete all fields with tag 650

Next record:
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

Next record:
LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

Next record:
LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual

Delete all subfields with code 'a' from fields with tag 650

Next record:
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
650  0 _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

Next record:
LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
650  0 _y1971-1980.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

Next record:
LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
PKN1[�jS�File_MARC/tests/marc_015.phptnu�[���--TEST--
marc_015: ensure that pandemonium does not occur if a record doesn't have a given field
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

while ($marc_record = $marc_file->next()) {

  // Record #2 doesn't contain an 852; getField() returns false
  $mfhd = $marc_record->getField('852');
  if ($mfhd) {
    $mfhd = $mfhd->getSubfield('b');
  }

  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
650  0 _aJazz.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
650  0 _aJazz
       _y1971-1980.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
650  0 _aJazz.
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
PKN1[7�File_MARC/tests/marc_009.phptnu�[���--TEST--
marc_009: Parse a record where leader record length != real record length
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'wronglen.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
  print "WARNINGS:\n";
  foreach ($marc_record->getWarnings() as $warning) {
    print "  * $warning\n";
  }
}
?>
--EXPECT--
LDR 00727nam  2200205 a 4500
001     03-0016458
005     19971103184734.0
008     970701s1997    oru          u000 0 eng u
035    _a(Sirsi) a351664
050 00 _aML270.2
       _b.A6 1997
100 1  _aAnthony, James R.
245 00 _aFrench baroque music from Beaujoyeulx to Rameau
250    _aRev. and expanded ed.
260    _aPortland, OR :
       _bAmadeus Press,
       _c1997.
300    _a586 p. :
       _bmusic
650  0 _aMusic
       _<France
       _y16th century
       _xHistory and criticism.
650  0 _aMusic
       _zFrance
       _y17th century
       _xHistory and criticism.
650  0 _aMusic
       _zFrance
       _y18th century
       _xHistory and criticism.
949    _aML 270.2 A6 1997
       _wLC
       _i30007006841505
       _rY
       _tBOOKS
       _lHUNT-CIRC
       _mHUNEXTRALON

WARNINGS:
  * Invalid record length: Leader says "00727" bytes; actual record length is "741"
  * Field for tag "949" does not end with an end of field character
  * Field for tag "596" does not end with an end of field character
  * Invalid indicators "GSTUFF" forced to blanks for tag "596"
PKN1[(Y����File_MARC/tests/xmlescape.mrcnu�[���00727nam  2200205 a 450000100110000000500170001100800410002803500200006905000220008910000220011124500520013325000260018526000420021130000200025365000560027365000560032965000560038594900740044159600060051503-001645819971103184734.0970701s1997    oru          u000 0 eng u  a(Sirsi) a35166400aML270.2b.A6 19971 aAnthony, James R.00aFrench baroque music from Beaujoyeulx to Rameau  aRev. and expanded ed.  aPortland, OR :bAmadeus Press,c1997.  a586 p. :bmusic 0aMusic<Francey16th centuryxHistory and criticism. 0aMusiczFrancey17th centuryxHistory and criticism. 0aMusiczFrancey18th centuryxHistory and criticism.  aML 270.2 A6 1997wLCi30007006841505rYtBOOKSlHUNT-CIRCmHUNTINGTON  a1
PKN1[�2�.iiFile_MARC/tests/marc_018.phptnu�[���--TEST--
marc_018: iterate and print a MARC record to JSON MARC-HASH format
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toJSONHash();
  print "\n";
}
?>
--EXPECT--
{"type":"marc-hash","version":[1,0],"leader":"01850     2200517   4500","fields":[["001","0000000044"],["003","EMILDA"],["008","980120s1998    fi     j      000 0 swe"],["020"," "," ",[["a","9515008808"],["c","FIM 72:00"]]],["035"," "," ",[["9","9515008808"]]],["040"," "," ",[["a","NB"]]],["042"," "," ",[["9","NB"],["9","SEE"]]],["084"," "," ",[["a","Hcd,u"],["2","kssb\/6"]]],["084"," "," ",[["5","NB"],["a","uHc"],["2","kssb"]]],["084"," "," ",[["5","SEE"],["a","Hcf"],["2","kssb\/6"]]],["084"," "," ",[["5","Q"],["a","Hcd,uf"],["2","kssb\/6"]]],["100","1"," ",[["a","Jansson, Tove,"],["d","1914-2001"]]],["245","0","4",[["a","Det osynliga barnet och andra ber\u00e4ttelser \/"],["c","Tove Jansson"]]],["250"," "," ",[["a","7. uppl."]]],["260"," "," ",[["a","Helsingfors :"],["b","Schildt,"],["c","1998 ;"],["e","(Falun :"],["f","Scandbook)"]]],["300"," "," ",[["a","166, [4] s. :"],["b","ill. ;"],["c","21 cm"]]],["440"," ","0",[["a","Mumin-biblioteket,"],["x","99-0698931-9"]]],["500"," "," ",[["a","Originaluppl. 1962"]]],["599"," "," ",[["a","Li: S"]]],["740","4"," ",[["a","Det osynliga barnet"]]],["775","1"," ",[["z","951-50-0385-7"],["w","9515003857"],["9","07"]]],["841"," "," ",[["5","Li"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["841"," "," ",[["5","SEE"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["841"," "," ",[["5","L"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["841"," "," ",[["5","NB"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["841"," "," ",[["5","Q"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["841"," "," ",[["5","S"],["a","xa"],["b","0201080u    0   4000uu   |000000"],["e","1"]]],["852"," "," ",[["5","NB"],["b","NB"],["c","NB98:12"],["h","plikt"],["j","R, 980520"]]],["852"," "," ",[["5","Li"],["b","Li"],["c","CNB"],["h","h,u"]]],["852"," "," ",[["5","SEE"],["b","SEE"]]],["852"," "," ",[["5","Q"],["b","Q"],["j","98947"]]],["852"," "," ",[["5","L"],["b","L"],["c","0100"],["h","98\/"],["j","3043 H"]]],["852"," "," ",[["5","S"],["b","S"],["h","Sv97"],["j","7235"]]],["900","1","s",[["a","Yanson, Tobe,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["900","1","s",[["a","Janssonov\u00e1, Tove,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["900","1","s",[["a","Jansone, Tuve,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["900","1","s",[["a","Janson, Tuve,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["900","1","s",[["a","Jansson, Tuve,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["900","1","s",[["a","Janssonova, Tove,"],["d","1914-2001"],["u","Jansson, Tove,"],["d","1914-2001"]]],["976"," ","2",[["a","Hcd,u"],["b","Sk\u00f6nlitteratur"]]],["005","20050204111518.0"]]}
PKN1[8��11$File_MARC/tests/marc_record_001.phptnu�[���--TEST--
marc_record_001: create a MARC record from scratch
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc = new File_MARC_Record();

$marc->appendField(new File_MARC_Data_Field('245', array(
        new File_MARC_Subfield('a', 'Main title: '),
        new File_MARC_Subfield('b', 'subtitle'),
        new File_MARC_Subfield('c', 'author')
    ), null, null
));

print $marc;

?>
--EXPECT--
LDR                         
245    _aMain title: 
       _bsubtitle
       _cauthor
PKN1[2���File_MARC/tests/skipif.incnu�[���<?php

// Stash the current error_reporting value
$error_reporting = error_reporting();

// Restore the error reporting to previous value
error_reporting($error_reporting);

?>
PKN1[\.i�vvFile_MARC/tests/sandburg.mrcnu�[���01142cam  2200301 a 4500001001300000003000400013005001700017008004100034010001700075020002500092040001800117042000900135050002600144082001600170100003200186245008600218250001200304260005200316300004900368500004000417520022800457650003300685650003300718650002400751650002100775650002300796700002100819   92005291 DLC19930521155141.9920219s1993    caua   j      000 0 eng    a   92005291   a0152038655 :c$15.95  aDLCcDLCdDLC  alcac00aPS3537.A618bA88 199300a811/.522201 aSandburg, Carl,d1878-1967.10aArithmetic /cCarl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.  a1st ed.  aSan Diego :bHarcourt Brace Jovanovich,cc1993.  a1 v. (unpaged) :bill. (some col.) ;c26 cm.  aOne Mylar sheet included in pocket.  aA poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone. 0aArithmeticxJuvenile poetry. 0aChildren's poetry, American. 1aArithmeticxPoetry. 1aAmerican poetry. 1aVisual perception.1 aRand, Ted,eill.PKN1[#c����File_MARC/tests/onerecord.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01142cam  2200301 a 4500</leader>
  <controlfield tag="001">   92005291 </controlfield>
  <controlfield tag="003">DLC</controlfield>
  <controlfield tag="005">19930521155141.9</controlfield>
  <controlfield tag="008">920219s1993    caua   j      000 0 eng  </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   92005291 </subfield>
  </datafield>
  <datafield tag="020" ind1=" " ind2=" ">
   <subfield code="a">0152038655 :</subfield>
   <subfield code="c">$15.95</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">DLC</subfield>
   <subfield code="c">DLC</subfield>
   <subfield code="d">DLC</subfield>
  </datafield>
  <datafield tag="042" ind1=" " ind2=" ">
   <subfield code="a">lcac</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">PS3537.A618</subfield>
   <subfield code="b">A88 1993</subfield>
  </datafield>
  <datafield tag="082" ind1="0" ind2="0">
   <subfield code="a">811/.52</subfield>
   <subfield code="2">20</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Sandburg, Carl,</subfield>
   <subfield code="d">1878-1967.</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
   <subfield code="a">Arithmetic /</subfield>
   <subfield code="c">Carl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
   <subfield code="a">1st ed.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">San Diego :</subfield>
   <subfield code="b">Harcourt Brace Jovanovich,</subfield>
   <subfield code="c">c1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 v. (unpaged) :</subfield>
   <subfield code="b">ill. (some col.) ;</subfield>
   <subfield code="c">26 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">One Mylar sheet included in pocket.</subfield>
  </datafield>
  <datafield tag="520" ind1=" " ind2=" ">
   <subfield code="a">A poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Juvenile poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Children's poetry, American.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">American poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Visual perception.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Rand, Ted,</subfield>
   <subfield code="e">ill.</subfield>
  </datafield>
 </record>
PKN1[�_X���#File_MARC/tests/marc_field_004.phptnu�[���--TEST--
marc_field_004: Add subfields to an existing field (corner case)
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// create a field
$field = new File_MARC_Data_Field('100', $subfields, '0');

// create some new subfields
$subfield1 = new File_MARC_Subfield('g', 'a little');

// test the fieldpost corner case by inserting prior to the first subfield
$sf = $field->getSubfields('a');
// we might get an array back; in this case, we want the first subfield
if (is_array($sf)) {
  $field->insertSubfield($subfield1, $sf[0], true);
}
else {
  $field->insertSubfield($subfield1, $sf, true);
}

// let's see the results
print $field;
print "\n";

?>
--EXPECT--
100 0  _ga little
       _anothing
       _zeverything
PKN1[.%�``File_MARC/tests/marc_010.phptnu�[���--TEST--
marc_010: iterate and pretty print MARC records from a stream
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$marc_file = new File_MARC("compress.zlib://$dir/compressed.mrc.gz");

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
650  0 _aJazz.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
650  0 _aJazz
       _y1971-1980.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
650  0 _aJazz.
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
PKN1[B�1��
�
"File_MARC/tests/marc_lint_005.phptnu�[���--TEST--
marc_lint_005: Tests check_020() called separately
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
<?php include('tests/skipif_noispn.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Create test harness to allow direct calls to check methods:
class File_MARC_Lint_Test_Harness extends File_MARC_Lint
{
    public function check020($field)
    {
        return parent::check020($field);
    }

    // override warn method to echo instead of store in object:
    protected function warn($msg)
    {
        echo $msg . "\n";
    }
}

$marc_lint = new File_MARC_Lint_Test_Harness();

$testData = array(
    array('a' => "154879473"), //too few digits
    array('a' => "1548794743"), //invalid checksum
    array('a' => "15487947443"), //11 digits
    array('a' => "15487947443324"), //14 digits
    array('a' => "9781548794743"), //13 digit valid
    array('a' => "9781548794745"), //13 digit invalid
    array('a' => "1548794740 (10 : good checksum)"), //10 digit valid with qualifier
    array('a' => "1548794745 (10 : bad checksum)"), //10 digit invalid with qualifier
    array('a' => "1-54879-474-0 (hyphens and good checksum)"), //10 digit invalid with hyphens and qualifier
    array('a' => "1-54879-474-5 (hyphens and bad checksum)"), //10 digit invalid with hyphens and qualifier
    array('a' => "1548794740(10 : unspaced qualifier)"), //10 valid without space before qualifier
    array('a' => "1548794745(10 : unspaced qualifier : bad checksum)"), //10 invalid without space before qualifier
    array('z' => "1548794743"), //subfield z
);

foreach ($testData as $current) {
    $subfields = array();
    foreach ($current as $key => $value) {
        $subfields[] = new File_MARC_Subfield($key, $value);
    }
    $field = new File_MARC_Data_Field('020', $subfields, '', '');
    $marc_lint->check020($field);
}

?>
--EXPECT--
020: Subfield a has the wrong number of digits, 154879473.
020: Subfield a has bad checksum, 1548794743.
020: Subfield a has the wrong number of digits, 15487947443.
020: Subfield a has the wrong number of digits, 15487947443324.
020: Subfield a has bad checksum (13 digit), 9781548794745.
020: Subfield a has bad checksum, 1548794745 (10 : bad checksum).
020: Subfield a may have invalid characters.
020: Subfield a may have invalid characters.
020: Subfield a has bad checksum, 1-54879-474-5 (hyphens and bad checksum).
020: Subfield a qualifier must be preceded by space, 1548794740(10 : unspaced qualifier).
020: Subfield a qualifier must be preceded by space, 1548794745(10 : unspaced qualifier : bad checksum).
020: Subfield a has bad checksum, 1548794745(10 : unspaced qualifier : bad checksum).
PKN1[ye@��!File_MARC/tests/marc_xml_007.phptnu�[���--TEST--
marc_xml_007: test getTag(), isControlField(), and isDataField() convenience methods on MARCXML
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'bigarchive.xml');

while ($marc_record = $marc_file->next()) {
  $fields = $marc_record->getFields();
  foreach ($fields as $field) {
    print $field->getTag();
    if ($field->isControlField()) {
      print "\tControl field!";
    }
    if ($field->isDataField()) {
      print "\tData field!";
    }
    print "\n";
  }
}

?>
--EXPECT--
001	Control field!
003	Control field!
005	Control field!
006	Control field!
007	Control field!
008	Control field!
037	Data field!
040	Data field!
245	Data field!
246	Data field!
260	Data field!
300	Data field!
500	Data field!
500	Data field!
500	Data field!
510	Data field!
510	Data field!
533	Data field!
651	Data field!
830	Data field!
856	Data field!
909	Data field!
PKN1[�����File_MARC/tests/marc_008.phptnu�[���--TEST--
marc_008: Attempt to open a file that does not exist
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

try {
    $marc_file = new File_MARC('super_bogus_file');
}
catch (File_MARC_Exception $fme) {
    print $fme->getMessage();
}

?>
--EXPECTF--
Warning: fopen(super_bogus_file): failed to open stream: No such file or directory in %sMARC.php on line %d
Invalid input file "super_bogus_file"
PKN1[+W��
�
File_MARC/tests/bigarchive.xmlnu�[���<?xml version="1.0"?>
<record xmlns="http://www.loc.gov/MARC21/slim"><leader>00000nam  2200277   4500</leader><controlfield tag="001">99865026e</controlfield><controlfield tag="003">UnM</controlfield><controlfield tag="005">19961010163452.0</controlfield><controlfield tag="006">m    g   d</controlfield><controlfield tag="007">cr bn |||a|bb|</controlfield><controlfield tag="008">940112s1649    enk     s     00| | eng d</controlfield><datafield tag="037" ind1=" " ind2=" "><subfield code="a">CL0051000003</subfield><subfield code="b">ProQuest Information and Learning. 300 N. Zeeb Rd., Ann Arbor, MI 48106</subfield></datafield><datafield tag="040" ind1=" " ind2=" "><subfield code="a">Cu-RivES</subfield><subfield code="c">Cu-RivES</subfield><subfield code="d">CStRLIN</subfield><subfield code="e">dcrb</subfield><subfield code="d">WaOLN</subfield></datafield><datafield tag="245" ind1="0" ind2="4"><subfield code="a">The VVelsh embassador, or the happy newes his vvorship hath brought to London.</subfield><subfield code="h">[electronic resource] :</subfield><subfield code="b">Togetherwith her thirteen articles of acreements, which her propounds to all her cousens in her principality of Wales,and her Cities of London.</subfield></datafield><datafield tag="246" ind1="2" ind2=" "><subfield code="a">Happy newes his vvorship hath brought to London</subfield></datafield><datafield tag="260" ind1=" " ind2=" "><subfield code="a">[London] :</subfield><subfield code="b">Printed for George Roberts, and are to be soldat the Maiden Head on Snow-Hill neer Holborn Conduit,</subfield><subfield code="c">1649.</subfield></datafield><datafield tag="300" ind1=" " ind2=" "><subfield code="a">[2], 6 p.</subfield></datafield><datafield tag="500" ind1=" " ind2=" "><subfield code="a">Place of publication from Wing.</subfield></datafield><datafield tag="500" ind1=" " ind2=" "><subfield code="a">Annotation on Thomason copy: "May 4th".</subfield></datafield><datafield tag="500" ind1=" " ind2=" "><subfield code="a">Reproduction of the original in the British Library.</subfield></datafield><datafield tag="510" ind1="4" ind2=" "><subfield code="a">Wing (2nd ed.)</subfield><subfield code="c">W1315.</subfield></datafield><datafield tag="510" ind1="4" ind2=" "><subfield code="a">Thomason</subfield><subfield code="c">E.552[19].</subfield></datafield><datafield tag="533" ind1=" " ind2=" "><subfield code="a">Electronic reproduction.</subfield><subfield code="b">Ann Arbor, Mich. :</subfield><subfield code="c">UMI,</subfield><subfield code="d">1999-</subfield><subfield code="f">(Early English books online)</subfield><subfield code="n">Digital version of: (Thomason Tracts ; 85:E552[19])</subfield><subfield code="7">s1999    miun s</subfield></datafield><datafield tag="651" ind1=" " ind2="4"><subfield code="a">Great Britain</subfield><subfield code="x">Politics and government</subfield><subfield code="y">1642-1649</subfield><subfield code="v">Early works to 1800.</subfield></datafield><datafield tag="830" ind1=" " ind2="0"><subfield code="a">Early English books online.</subfield></datafield><datafield tag="856" ind1="4" ind2="0"><subfield code="z">E-book (Onsite access at NYPL Research Libraries)</subfield><subfield code="u">http://gateway.proquest.com/openurl?ctx_ver=Z39.88-2003&amp;res_id=xri:eebo&amp;rft_val_fmt=&amp;rft_id=xri:eebo:image:117259</subfield></datafield><datafield tag="909" ind1=" " ind2=" "><subfield code="a">Not for export in OCLC Reclamation Project</subfield></datafield></record>
PKN1[��ԛ�
�
File_MARC/tests/marc_014.phptnu�[���--TEST--
marc_014: Add fields to a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Get ourselves a MARC record
$marc_file = new File_MARC($dir . '/' . 'example.mrc');
$marc_record = $marc_file->next();

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// create a data field
$data_field = new File_MARC_Data_Field('100', $subfields, '0');

// append the data field
$marc_record->appendField($data_field);

// create a control field
$ctrl_field = new File_MARC_Control_Field('001', '01234567890');

// prepend the control field
$marc_record->prependField($ctrl_field);

// reproduce test case reported by Mark Jordan
$subfields_966_2[] = new File_MARC_Subfield('l', 'web');
$subfields_966_2[] = new File_MARC_Subfield('r', '0');
$subfields_966_2[] = new File_MARC_Subfield('s', 'b');
$subfields_966_2[] = new File_MARC_Subfield('i', '49');
$subfields_966_2[] = new File_MARC_Subfield('c', '1');
$field_966_2 = new File_MARC_Data_Field('966', $subfields_966_2, null, null);
$marc_record->appendField($field_966_2);

// let's see the results
print utf8_encode($marc_record);
print "\n";

?>
--EXPECT--
LDR 01850     2200517   4500
001     01234567890
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
020    _a9515008808
       _cFIM 72:00
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra berättelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
841    _5Li
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5SEE
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5L
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5NB
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5Q
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5S
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
852    _5NB
       _bNB
       _cNB98:12
       _hplikt
       _jR, 980520
852    _5Li
       _bLi
       _cCNB
       _hh,u
852    _5SEE
       _bSEE
852    _5Q
       _bQ
       _j98947
852    _5L
       _bL
       _c0100
       _h98/
       _j3043 H
852    _5S
       _bS
       _hSv97
       _j7235
900 1s _aYanson, Tobe,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonová, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansone, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonova, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
976  2 _aHcd,u
       _bSkönlitteratur
005     20050204111518.0
100 0  _anothing
       _zeverything
966    _lweb
       _r0
       _sb
       _i49
       _c1
PKN1[�����'File_MARC/tests/marc_xml_namespace.phptnu�[���--TEST--
marc_xml_namespace: iterate and pretty print a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'namespace.xml',File_MARC::SOURCE_FILE,"http://www.loc.gov/MARC21/slim");
while ($marc_record = $marc_file->next()) {
  print $marc_record->getLeader();
  print "\n";
  $field = $marc_record->getField('050');
  print $field->getIndicator(1);
  print "\n";
  print $field->getIndicator(2);
  print "\n";
  $subfield = $field->getSubfield('a');
  print $subfield->getData();
  print "\n";
}
?>
--EXPECT--
00925njm  22002777a 4500
0
0
Atlantic 1259
01832cmma 2200349 a 4500
0
0
F204.W5
PKN1[f��~#File_MARC/tests/marc_field_001.phptnu�[���--TEST--
marc_field_001: Exercise basic methods for File_MARC_Field class
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// create some subfields
$subfields[] = new File_MARC_Subfield('a', 'nothing');
$subfields[] = new File_MARC_Subfield('z', 'everything');

// test constructor
$field = new File_MARC_Data_Field('100', $subfields, '0');

// test basic getter methods
print "Tag: " . $field->getTag() . "\n";
print "Get Ind1: " . $field->getIndicator(1) . "\n";
print "Get Ind2: " . $field->getIndicator(2) . "\n";

// test basic setter methods
print "Set Ind1: " . $field->setIndicator(1, '3') . "\n";

// test pretty print
print $field;
print "\n";

// test raw print
print $field->toRaw();
?>
--EXPECT--
Tag: 100
Get Ind1: 0
Get Ind2:  
Set Ind1: 3
100 3  _anothing
       _zeverything
3 anothingzeverything
PKN1[���YY!File_MARC/tests/marc_xml_009.phptnu�[���--TEST--
marc_xml_009: convert a MARCXML record with an overly long leader to MARC
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'bad_leader.xml');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toRaw();
}
?>
--EXPECT--
00749cam a2200241 454500001001400000003000600014005001700020008004100037020001800078020001500096035002100111040003600132050002400168100002500192245007800217260003700295300002100332504004100353650001700394650002200411852004800433901002600481LIBN539044247OCoLC20081030150430.0070630|||||    |||           000 0 eng d  a9781856075442  a1856075443  a(OCoLC)156822300  aBTCTAcBTCTAdYDXCPdBAKERdEMT 4aBL2747.2b.W45 20061 aWhite, Stephen Ross.10aSpace for unknowing :bthe place of agnosis in faith /cStephen R. White.  aDublin :bColumba Press,cc2006.  a160 p. ;c22 cm.  aIncludes bibliographical references. 0aAgnosticism. 0aBelief and doubt.  a1h230 WHIp11111027105040t65112549p26.95  aLIBN539044247bSystem
PKN1[~N0�::File_MARC/tests/example.mrcnu�[���01850     2200517   45000010011000000030007000110080039000180200026000570350015000830400007000980420012001050840018001170840018001350840021001530840022001741000030001962450062002262500013002882600058003013000033003594400037003925000023004295990010004527400024004627750034004868410048005208410049005688410047006178410048006648410047007128410047007598520038008068520021008448520013008658520016008788520028008948520021009229000056009439000060009999000057010599000056011169000057011729000060012299760026012890050017013150000000044EMILDA980120s1998    fi     j      000 0 swe  a9515008808cFIM 72:00  99515008808  aNB  9NB9SEE  aHcd,u2kssb/6  5NBauHc2kssb  5SEEaHcf2kssb/6  5QaHcd,uf2kssb/61 aJansson, Tove,d1914-200104aDet osynliga barnet och andra ber�ttelser /cTove Jansson  a7. uppl.  aHelsingfors :bSchildt,c1998 ;e(Falun :fScandbook)  a166, [4] s. :bill. ;c21 cm 0aMumin-biblioteket,x99-0698931-9  aOriginaluppl. 1962  aLi: S4 aDet osynliga barnet1 z951-50-0385-7w9515003857907  5Liaxab0201080u    0   4000uu   |000000e1  5SEEaxab0201080u    0   4000uu   |000000e1  5Laxab0201080u    0   4000uu   |000000e1  5NBaxab0201080u    0   4000uu   |000000e1  5Qaxab0201080u    0   4000uu   |000000e1  5Saxab0201080u    0   4000uu   |000000e1  5NBbNBcNB98:12hpliktjR, 980520  5LibLicCNBhh,u  5SEEbSEE  5QbQj98947  5LbLc0100h98/j3043 H  5SbShSv97j72351saYanson, Tobe,d1914-2001uJansson, Tove,d1914-20011saJanssonov�, Tove,d1914-2001uJansson, Tove,d1914-20011saJansone, Tuve,d1914-2001uJansson, Tove,d1914-20011saJanson, Tuve,d1914-2001uJansson, Tove,d1914-20011saJansson, Tuve,d1914-2001uJansson, Tove,d1914-20011saJanssonova, Tove,d1914-2001uJansson, Tove,d1914-2001 2aHcd,ubSk�nlitteratur20050204111518.0PKO1[}۶\ppFile_MARC/tests/bad_example.xmlnu�[���<collection xmlns="http://www.loc.gov/MARC21/slim">
<record>
  <leader>01850    a2200517   4500</leader>
  <controlfield tag="001">0000000044</controlfield>
  <controlfield tag="003">EMILDA</controlfield>
  <controlfield tag="008">980120s1998    fi     j      000 0 swe</controlfield>
  <datafield tag="020" ind1=" " ind2=" ">
    <subfield code="a">9515008808</subfield>
    <subfield code="c">FIM 72:00</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
    <subfield code="9">9515008808</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
    <subfield code="a">NB</subfield>
  </datafield>
  <datafield tag="042" ind1=" " ind2=" ">
    <subfield code="9">NB</subfield>
    <subfield code="9">SEE</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
    <subfield code="a">Hcd,u</subfield>
    <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
    <subfield code="5">NB</subfield>
    <subfield code="a">uHc</subfield>
    <subfield code="2">kssb</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
    <subfield code="5">SEE</subfield>
    <subfield code="a">Hcf</subfield>
    <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="084" ind1=" " ind2=" ">
    <subfield code="5">Q</subfield>
    <subfield code="a">Hcd,uf</subfield>
    <subfield code="2">kssb/6</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
    <subfield code="a">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="245" ind1="0">
    <subfield code="a">Det osynliga barnet och andra bert̃telser /</subfield>
    <subfield code="c">Tove Jansson</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
    <subfield code="a">7. uppl.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
    <subfield code="a">Helsingfors :</subfield>
    <subfield code="b">Schildt,</subfield>
    <subfield code="c">1998 ;</subfield>
    <subfield code="e">(Falun :</subfield>
    <subfield code="f">Scandbook)</subfield>
  </datafield>
  <datafield tag="30-" ind1=" " ind2=" ">
    <subfield code="a">166, [4] s. :</subfield>
    <subfield code="b">ill. ;</subfield>
    <subfield code="c">21 cm</subfield>
  </datafield>
  <datafield tag="440" ind1=" " ind2="0">
    <subfield code="a">Mumin-biblioteket,</subfield>
    <subfield code="x">99-0698931-9</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">Originaluppl. 1962</subfield>
  </datafield>
  <datafield tag="599" ind1=" " ind2=" ">
    <subfield code="a">Li: S</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
    <subfield code="a">Det osynliga barnet</subfield>
  </datafield>
  <datafield tag="775" ind1="1" ind2=" ">
    <subfield code="z">951-50-0385-7</subfield>
    <subfield code="w">9515003857</subfield>
    <subfield code="9">07</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">Li</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">SEE</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">L</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">NB</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">Q</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="841" ind1=" " ind2=" ">
    <subfield code="5">S</subfield>
    <subfield code="a">xa</subfield>
    <subfield code="b">0201080u    0   4000uu   |000000</subfield>
    <subfield code="e">1</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">NB</subfield>
    <subfield code="b">NB</subfield>
    <subfield code="c">NB98:12</subfield>
    <subfield code="h">plikt</subfield>
    <subfield code="j">R, 980520</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">Li</subfield>
    <subfield code="b">Li</subfield>
    <subfield code="c">CNB</subfield>
    <subfield code="h">h,u</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">SEE</subfield>
    <subfield code="b">SEE</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">Q</subfield>
    <subfield code="b">Q</subfield>
    <subfield code="j">98947</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">L</subfield>
    <subfield code="b">L</subfield>
    <subfield code="c">0100</subfield>
    <subfield code="h">98/</subfield>
    <subfield code="j">3043 H</subfield>
  </datafield>
  <datafield tag="852" ind1=" " ind2=" ">
    <subfield code="5">S</subfield>
    <subfield code="b">S</subfield>
    <subfield code="h">Sv97</subfield>
    <subfield code="j">7235</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Yanson, Tobe,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Janssonov,̀ Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Jansone, Tuve,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Janson, Tuve,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Jansson, Tuve,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="900" ind1="1" ind2="s">
    <subfield code="a">Janssonova, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
    <subfield code="u">Jansson, Tove,</subfield>
    <subfield code="d">1914-2001</subfield>
  </datafield>
  <datafield tag="976" ind1=" " ind2="2">
    <subfield code="a">Hcd,u</subfield>
    <subfield code="b">Skn̲litteratur</subfield>
  </datafield>
  <controlfield tag="005">20050204111518.0</controlfield>
</record>
</collection>
PKO1[9�DDFile_MARC/tests/marc_017.phptnu�[���--TEST--
marc_017: iterate and print a MARC record to JSON format
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toJSON();
  print "\n";
}
?>
--EXPECT--
{"leader":"01850     2200517   4500","fields":[{"001":"0000000044"},{"003":"EMILDA"},{"008":"980120s1998    fi     j      000 0 swe"},{"020":{"ind1":" ","ind2":" ","subfields":[{"a":"9515008808"},{"c":"FIM 72:00"}]}},{"035":{"ind1":" ","ind2":" ","subfields":[{"9":"9515008808"}]}},{"040":{"ind1":" ","ind2":" ","subfields":[{"a":"NB"}]}},{"042":{"ind1":" ","ind2":" ","subfields":[{"9":"NB"},{"9":"SEE"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"a":"Hcd,u"},{"2":"kssb\/6"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"a":"uHc"},{"2":"kssb"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"a":"Hcf"},{"2":"kssb\/6"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"a":"Hcd,uf"},{"2":"kssb\/6"}]}},{"100":{"ind1":"1","ind2":" ","subfields":[{"a":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"245":{"ind1":"0","ind2":"4","subfields":[{"a":"Det osynliga barnet och andra ber\u00e4ttelser \/"},{"c":"Tove Jansson"}]}},{"250":{"ind1":" ","ind2":" ","subfields":[{"a":"7. uppl."}]}},{"260":{"ind1":" ","ind2":" ","subfields":[{"a":"Helsingfors :"},{"b":"Schildt,"},{"c":"1998 ;"},{"e":"(Falun :"},{"f":"Scandbook)"}]}},{"300":{"ind1":" ","ind2":" ","subfields":[{"a":"166, [4] s. :"},{"b":"ill. ;"},{"c":"21 cm"}]}},{"440":{"ind1":" ","ind2":"0","subfields":[{"a":"Mumin-biblioteket,"},{"x":"99-0698931-9"}]}},{"500":{"ind1":" ","ind2":" ","subfields":[{"a":"Originaluppl. 1962"}]}},{"599":{"ind1":" ","ind2":" ","subfields":[{"a":"Li: S"}]}},{"740":{"ind1":"4","ind2":" ","subfields":[{"a":"Det osynliga barnet"}]}},{"775":{"ind1":"1","ind2":" ","subfields":[{"z":"951-50-0385-7"},{"w":"9515003857"},{"9":"07"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"Li"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"L"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"S"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"b":"NB"},{"c":"NB98:12"},{"h":"plikt"},{"j":"R, 980520"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"Li"},{"b":"Li"},{"c":"CNB"},{"h":"h,u"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"b":"SEE"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"b":"Q"},{"j":"98947"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"L"},{"b":"L"},{"c":"0100"},{"h":"98\/"},{"j":"3043 H"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"S"},{"b":"S"},{"h":"Sv97"},{"j":"7235"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Yanson, Tobe,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janssonov\u00e1, Tove,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Jansone, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janson, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Jansson, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janssonova, Tove,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"976":{"ind1":" ","ind2":"2","subfields":[{"a":"Hcd,u"},{"b":"Sk\u00f6nlitteratur"}]}},{"005":"20050204111518.0"}]}
PKO1[�&��ccFile_MARC/tests/marc_002.phptnu�[���--TEST--
marc_002: iterate and pretty print MARC records from a file with multiple records
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
650  0 _aJazz.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
650  0 _aJazz
       _y1971-1980.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
650  0 _aJazz.
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
PKO1[�����!File_MARC/tests/marc_xml_005.phptnu�[���--TEST--
marc_xml_005: Round-trip a MARCXML record with a root element of "record" to MARC21
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'onerecord.xml');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toRaw();
}
?>
--EXPECT--
01142cam  2200301 a 4500001001300000003000400013005001700017008004100034010001700075020002500092040001800117042000900135050002600144082001600170100003200186245008600218250001200304260005200316300004900368500004000417520022800457650003300685650003300718650002400751650002100775650002300796700002100819   92005291 DLC19930521155141.9920219s1993    caua   j      000 0 eng    a   92005291   a0152038655 :c$15.95  aDLCcDLCdDLC  alcac00aPS3537.A618bA88 199300a811/.522201 aSandburg, Carl,d1878-1967.10aArithmetic /cCarl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.  a1st ed.  aSan Diego :bHarcourt Brace Jovanovich,cc1993.  a1 v. (unpaged) :bill. (some col.) ;c26 cm.  aOne Mylar sheet included in pocket.  aA poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone. 0aArithmeticxJuvenile poetry. 0aChildren's poetry, American. 1aArithmeticxPoetry. 1aAmerican poetry. 1aVisual perception.1 aRand, Ted,eill.
PKO1[�5;�-�-File_MARC/tests/music.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
<record>
  <leader>01145ncm a2200277 i 4500</leader>
  <controlfield tag="001">000073594</controlfield>
  <controlfield tag="004">AAJ5802</controlfield>
  <controlfield tag="005">20030415102100.0</controlfield>
  <controlfield tag="008">801107s1977    nyujza                   </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
    <subfield code="a">   77771106 </subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
    <subfield code="a">(CaOTUIC)15460184</subfield>
  </datafield>
  <datafield tag="035" ind1="9" ind2=" ">
    <subfield code="a">AAJ5802</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
    <subfield code="a">LC</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
    <subfield code="a">M1366</subfield>
    <subfield code="b">.M62</subfield>
    <subfield code="d">M1527.2</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="4">
    <subfield code="a">The Modern Jazz Quartet :</subfield>
    <subfield code="b">The legendary profile. --</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
    <subfield code="a">New York :</subfield>
    <subfield code="b">M.J.Q. Music,</subfield>
    <subfield code="c">c1977.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
    <subfield code="a">score (72 p.) ;</subfield>
    <subfield code="c">31 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">For piano, vibraphone, drums, and double bass.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
    <subfield code="a">Lewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B́Ư.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
    <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
    <subfield code="a">Motion picture music</subfield>
    <subfield code="v">Excerpts</subfield>
    <subfield code="v">Scores.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
    <subfield code="a">Lewis, John,</subfield>
    <subfield code="d">1920-</subfield>
    <subfield code="t">Selections.</subfield>
    <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
    <subfield code="a">Jackson, Milt.</subfield>
    <subfield code="t">Martyrs.</subfield>
    <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
    <subfield code="a">Jackson, Milt.</subfield>
    <subfield code="t">Legendary profile.</subfield>
    <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
    <subfield code="a">The legendary profile.</subfield>
  </datafield>
  <datafield tag="852" ind1="0" ind2="0">
    <subfield code="b">MUSIC</subfield>
    <subfield code="c">MAIN</subfield>
    <subfield code="k">folio</subfield>
    <subfield code="h">M1366</subfield>
    <subfield code="i">M62</subfield>
    <subfield code="9">1</subfield>
    <subfield code="4">Marvin Duchow Music</subfield>
    <subfield code="5"></subfield>
  </datafield>
</record>
<record>
  <leader>01293cjm a2200289 a 4500</leader>
  <controlfield tag="001">001878039</controlfield>
  <controlfield tag="005">20050110174900.0</controlfield>
  <controlfield tag="007">sd fungnn|||e|</controlfield>
  <controlfield tag="008">940202r19931981nyujzn   i              d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
    <subfield code="a">7464573372</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="2">
    <subfield code="a">JK 57337</subfield>
    <subfield code="b">Red Baron</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
    <subfield code="a">(OCoLC)29737267</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
    <subfield code="a">SVP</subfield>
    <subfield code="c">SVP</subfield>
    <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
    <subfield code="a">Desmond, Paul,</subfield>
    <subfield code="d">1924-</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
    <subfield code="a">Paul Desmond &amp; the Modern Jazz Quartet</subfield>
    <subfield code="h">[sound recording]</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
    <subfield code="a">New York, N.Y. :</subfield>
    <subfield code="b">Red Baron :</subfield>
    <subfield code="b">Manufactured by Sony Music Entertainment,</subfield>
    <subfield code="c">p1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
    <subfield code="a">1 sound disc (39 min.) :</subfield>
    <subfield code="b">digital ;</subfield>
    <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
    <subfield code="a">Paul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">All arrangements by John Lewis.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
    <subfield code="a">Recorded live on December 25, 1971 at Town Hall, NYC.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">Originally released in 1981 by Finesse as LP FW 27487.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">Program notes by Irving Townsend, June 1981, on container insert.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
    <subfield code="a">Greensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here&apos;s that rainy day -- East of the sun -- Bags&apos; new groove.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
    <subfield code="a">Jazz</subfield>
    <subfield code="y">1971-1980.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Lewis, John,</subfield>
    <subfield code="d">1920-</subfield>
  </datafield>
  <datafield tag="710" ind1="2" ind2=" ">
    <subfield code="a">Modern Jazz Quartet.</subfield>
  </datafield>
  <datafield tag="740" ind1="0" ind2=" ">
    <subfield code="a">Paul Desmond and the Modern Jazz Quartet.</subfield>
  </datafield>
</record>
<record>
  <leader>01829cjm a2200385 a 4500</leader>
  <controlfield tag="001">001964482</controlfield>
  <controlfield tag="005">20060626132700.0</controlfield>
  <controlfield tag="007">sd fzngnn|m|e|</controlfield>
  <controlfield tag="008">871211p19871957nyujzn                  d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
    <subfield code="a">4228332902</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="1">
    <subfield code="a">833 290-2</subfield>
    <subfield code="b">Verve</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
    <subfield code="a">19571027</subfield>
    <subfield code="b">6299</subfield>
    <subfield code="c">D56</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
    <subfield code="a">196112--</subfield>
    <subfield code="b">3804</subfield>
    <subfield code="c">N4</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
    <subfield code="a">19571019</subfield>
    <subfield code="b">4104</subfield>
    <subfield code="c">C6</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
    <subfield code="a">197107--</subfield>
    <subfield code="b">6299</subfield>
    <subfield code="c">V7</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
    <subfield code="a">(OCoLC)17222092</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
    <subfield code="a">CPL</subfield>
    <subfield code="c">CPL</subfield>
    <subfield code="d">OCL</subfield>
    <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="048" ind1=" " ind2=" ">
    <subfield code="a">pz01</subfield>
    <subfield code="a">ka01</subfield>
    <subfield code="a">sd01</subfield>
    <subfield code="a">pd01</subfield>
  </datafield>
  <datafield tag="110" ind1="2" ind2=" ">
    <subfield code="a">Modern Jazz Quartet.</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="4">
    <subfield code="a">The Modern Jazz Quartet plus</subfield>
    <subfield code="h">[sound recording].</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
    <subfield code="a">[New York] :</subfield>
    <subfield code="b">Verve,</subfield>
    <subfield code="c">p1987.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
    <subfield code="a">1 sound disc :</subfield>
    <subfield code="b">digital ;</subfield>
    <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="440" ind1=" " ind2="0">
    <subfield code="a">Compact jazz</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
    <subfield code="a">Modern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
    <subfield code="a">Recorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">Compact disc.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
    <subfield code="a">Analog recording.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
    <subfield code="a">The golden striker (4:08) -- On Green Dolphin Street (7:28) -- D &amp; E (4:55) -- I&apos;ll remember April (4:51) -- Cort©·ge (7:15) -- Now&apos;s the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- &apos;Round midnight (3:56) -- Three windows (7:20).</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
    <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Jackson, Milt.</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Peterson, Oscar,</subfield>
    <subfield code="d">1925-</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Brown, Ray,</subfield>
    <subfield code="d">1926-2002.</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Thigpen, Ed.</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
    <subfield code="a">Hayes, Louis,</subfield>
    <subfield code="d">1937-</subfield>
    <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="852" ind1="8" ind2="0">
    <subfield code="b">MUSIC</subfield>
    <subfield code="c">AV</subfield>
    <subfield code="h">CD 1131</subfield>
    <subfield code="4">Marvin Duchow Music</subfield>
    <subfield code="5">Audio-Visual</subfield>
  </datafield>
</record>
</collection>
PKO1[��`��File_MARC/tests/marc_012.phptnu�[���--TEST--
marc_012: test isControlField() and isDataField() convenience methods
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

while ($marc_record = $marc_file->next()) {
  $fields = $marc_record->getFields();
  foreach ($fields as $field) {
    print $field->getTag();
    if ($field->isControlField()) {
      print "\tControl field!";
    }
    if ($field->isDataField()) {
      print "\tData field!";
    }
    print "\n";
  }
}

?>
--EXPECT--
001	Control field!
004	Control field!
005	Control field!
008	Control field!
010	Data field!
035	Data field!
035	Data field!
040	Data field!
050	Data field!
245	Data field!
260	Data field!
300	Data field!
500	Data field!
505	Data field!
650	Data field!
650	Data field!
700	Data field!
700	Data field!
700	Data field!
740	Data field!
852	Data field!
001	Control field!
005	Control field!
007	Control field!
008	Control field!
024	Data field!
028	Data field!
035	Data field!
040	Data field!
100	Data field!
245	Data field!
260	Data field!
300	Data field!
511	Data field!
500	Data field!
518	Data field!
500	Data field!
500	Data field!
505	Data field!
650	Data field!
700	Data field!
710	Data field!
740	Data field!
001	Control field!
005	Control field!
007	Control field!
008	Control field!
024	Data field!
028	Data field!
033	Data field!
033	Data field!
033	Data field!
033	Data field!
035	Data field!
040	Data field!
048	Data field!
110	Data field!
245	Data field!
260	Data field!
300	Data field!
440	Data field!
511	Data field!
518	Data field!
500	Data field!
500	Data field!
505	Data field!
650	Data field!
700	Data field!
700	Data field!
700	Data field!
700	Data field!
700	Data field!
852	Data field!
PKO1[�S3File_MARC/tests/marc_021.phptnu�[���--TEST--
marc_021: test MARC-in-JSON serialization with subfield 0
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

while ($marc_record = $marc_file->next()) {
  // create some subfields
  $subfields[] = new File_MARC_Subfield('0', 'nothing');
  $subfields[] = new File_MARC_Subfield('1', 'everything');
  $field = new File_MARC_Data_Field('999', $subfields, '', '');
  $marc_record->appendField($field);
  
  $subfields = null;
  $field = null;
  $subfields[] = new File_MARC_Subfield('a', 'bee');
  $subfields[] = new File_MARC_Subfield('0', 'cee');
  $subfields[] = new File_MARC_Subfield('d', 'eee');
  $field = new File_MARC_Data_Field('999', $subfields, '', '');

  $marc_record->appendField($field);

  print $marc_record->toJSON();
  print "\n";
}
?>
--EXPECT--
{"leader":"01850     2200517   4500","fields":[{"001":"0000000044"},{"003":"EMILDA"},{"008":"980120s1998    fi     j      000 0 swe"},{"020":{"ind1":" ","ind2":" ","subfields":[{"a":"9515008808"},{"c":"FIM 72:00"}]}},{"035":{"ind1":" ","ind2":" ","subfields":[{"9":"9515008808"}]}},{"040":{"ind1":" ","ind2":" ","subfields":[{"a":"NB"}]}},{"042":{"ind1":" ","ind2":" ","subfields":[{"9":"NB"},{"9":"SEE"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"a":"Hcd,u"},{"2":"kssb\/6"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"a":"uHc"},{"2":"kssb"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"a":"Hcf"},{"2":"kssb\/6"}]}},{"084":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"a":"Hcd,uf"},{"2":"kssb\/6"}]}},{"100":{"ind1":"1","ind2":" ","subfields":[{"a":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"245":{"ind1":"0","ind2":"4","subfields":[{"a":"Det osynliga barnet och andra ber\u00e4ttelser \/"},{"c":"Tove Jansson"}]}},{"250":{"ind1":" ","ind2":" ","subfields":[{"a":"7. uppl."}]}},{"260":{"ind1":" ","ind2":" ","subfields":[{"a":"Helsingfors :"},{"b":"Schildt,"},{"c":"1998 ;"},{"e":"(Falun :"},{"f":"Scandbook)"}]}},{"300":{"ind1":" ","ind2":" ","subfields":[{"a":"166, [4] s. :"},{"b":"ill. ;"},{"c":"21 cm"}]}},{"440":{"ind1":" ","ind2":"0","subfields":[{"a":"Mumin-biblioteket,"},{"x":"99-0698931-9"}]}},{"500":{"ind1":" ","ind2":" ","subfields":[{"a":"Originaluppl. 1962"}]}},{"599":{"ind1":" ","ind2":" ","subfields":[{"a":"Li: S"}]}},{"740":{"ind1":"4","ind2":" ","subfields":[{"a":"Det osynliga barnet"}]}},{"775":{"ind1":"1","ind2":" ","subfields":[{"z":"951-50-0385-7"},{"w":"9515003857"},{"9":"07"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"Li"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"L"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"841":{"ind1":" ","ind2":" ","subfields":[{"5":"S"},{"a":"xa"},{"b":"0201080u    0   4000uu   |000000"},{"e":"1"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"NB"},{"b":"NB"},{"c":"NB98:12"},{"h":"plikt"},{"j":"R, 980520"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"Li"},{"b":"Li"},{"c":"CNB"},{"h":"h,u"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"SEE"},{"b":"SEE"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"Q"},{"b":"Q"},{"j":"98947"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"L"},{"b":"L"},{"c":"0100"},{"h":"98\/"},{"j":"3043 H"}]}},{"852":{"ind1":" ","ind2":" ","subfields":[{"5":"S"},{"b":"S"},{"h":"Sv97"},{"j":"7235"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Yanson, Tobe,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janssonov\u00e1, Tove,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Jansone, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janson, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Jansson, Tuve,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"900":{"ind1":"1","ind2":"s","subfields":[{"a":"Janssonova, Tove,"},{"d":"1914-2001"},{"u":"Jansson, Tove,"},{"d":"1914-2001"}]}},{"976":{"ind1":" ","ind2":"2","subfields":[{"a":"Hcd,u"},{"b":"Sk\u00f6nlitteratur"}]}},{"005":"20050204111518.0"},{"999":{"ind1":" ","ind2":" ","subfields":[{"0":"nothing"},{"1":"everything"}]}},{"999":{"ind1":" ","ind2":" ","subfields":[{"a":"bee"},{"0":"cee"},{"d":"eee"}]}}]}
PKO1[<��--&File_MARC/tests/marc_subfield_002.phptnu�[���--TEST--
marc_subfield_002: Exercise setter and isEmpty() methods for File_MARC_Subfield class
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

function testEmpty($testSubfield) {
  print "Subfield is ";
  if ($testSubfield->isEmpty()) {
    print "empty.\n";
  }
  else {
    print "not empty.\n";
  }

}

$subfield = new File_MARC_Subfield('a', 'wasssup');

// test isEmpty() scenarios
testEmpty($subfield);

$subfield->setData(null);
testEmpty($subfield);

$subfield->setData('just hangin');
testEmpty($subfield);

// test setCode() scenarios
print "\nSet code to 'z'...";
if ($subfield->setCode('z')) {
  print "\n";
  print $subfield;
}

print "\nSet code to ''...";
if ($subfield->setCode('')) {
  print "\n";
  print $subfield;
}

print "\nSet code to null...";
if ($subfield->setCode(null)) {
  print "\n";
  print $subfield;
}

?>
--EXPECT--
Subfield is not empty.
Subfield is empty.
Subfield is not empty.

Set code to 'z'...
[z]: just hangin
Set code to ''...
Set code to null...
PKO1[�f==File_MARC/tests/bad_example.mrcnu�[���01853    a2200517   450000100110000000300070001100800390001802000260005703500150008304000070009804200120010508400180011708400180013508400210015308400220017410000300019624500630022625000130028926000580030230-0033003604400037003935000023004305990010004537400024004637750034004878410048005218410049005698410047006188410048006658410047007138410047007608520038008078520021008458520013008668520016008798520028008958520021009239000056009449000061010009000057010619000056011189000057011749000060012319760027012910050017013180000000044EMILDA980120s1998    fi     j      000 0 swe  a9515008808cFIM 72:00  99515008808  aNB  9NB9SEE  aHcd,u2kssb/6  5NBauHc2kssb  5SEEaHcf2kssb/6  5QaHcd,uf2kssb/61 aJansson, Tove,d1914-200104aDet osynliga barnet och andra bert̃telser /cTove Jansson  a7. uppl.  aHelsingfors :bSchildt,c1998 ;e(Falun :fScandbook)  a166, [4] s. :bill. ;c21 cm 0aMumin-biblioteket,x99-0698931-9  aOriginaluppl. 1962  aLi: S4 aDet osynliga barnet1 z951-50-0385-7w9515003857907  5Liaxab0201080u    0   4000uu   |000000e1  5SEEaxab0201080u    0   4000uu   |000000e1  5Laxab0201080u    0   4000uu   |000000e1  5NBaxab0201080u    0   4000uu   |000000e1  5Qaxab0201080u    0   4000uu   |000000e1  5Saxab0201080u    0   4000uu   |000000e1  5NBbNBcNB98:12hpliktjR, 980520  5LibLicCNBhh,u  5SEEbSEE  5QbQj98947  5LbLc0100h98/j3043 H  5SbShSv97j72351saYanson, Tobe,d1914-2001uJansson, Tove,d1914-20011saJanssonov,̀ Tove,d1914-2001uJansson, Tove,d1914-20011saJansone, Tuve,d1914-2001uJansson, Tove,d1914-20011saJanson, Tuve,d1914-2001uJansson, Tove,d1914-20011saJansson, Tuve,d1914-2001uJansson, Tove,d1914-20011saJanssonova, Tove,d1914-2001uJansson, Tove,d1914-2001 2aHcd,ubSkn̲litteratur20050204111518.0PKO1[�kP�File_MARC/tests/marc_023.phptnu�[���--TEST--
marc_023: test extended Record interface
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

class MyRecord extends File_MARC_Record {
  public function myNewMethod() {
    return $this->getField('040')->getSubfield('a')->getData();
  }
}

$marc_file = new File_MARC($dir . '/' . 'example.mrc', File_MARC::SOURCE_FILE, MyRecord::class);

$rec = $marc_file->next();
print get_class($rec) . "\n";
print $rec->myNewMethod() . "\n";

?>
--EXPECT--
MyRecord
NB
PKO1[W��))File_MARC/tests/marc_019.phptnu�[���--TEST--
marc_019: generate a MARCXML record not in a collection element
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$records = new File_MARC($dir . '/' . 'music.mrc');

// Iterate through the retrieved records
$record = $records->next();

// Change each 852 $c to "Audio-Visual"
$holdings = $record->getFields('852');
foreach ($holdings as $holding) {

    // Get the $c subfields from this field
    $formats = $holding->getSubfields('c');
    foreach ($formats as $format) {
        if ($format->getData('AV')) {
            $format->setData('Audio-Visual');
        }
    }
}

// Generate the XML output for this record
print($record->toXML('UTF-8', true, true));
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record>
  <leader>01145ncm  2200277 i 4500</leader>
  <controlfield tag="001">000073594</controlfield>
  <controlfield tag="004">AAJ5802</controlfield>
  <controlfield tag="005">20030415102100.0</controlfield>
  <controlfield tag="008">801107s1977    nyujza                   </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   77771106 </subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(CaOTUIC)15460184</subfield>
  </datafield>
  <datafield tag="035" ind1="9" ind2=" ">
   <subfield code="a">AAJ5802</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">LC</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">M1366</subfield>
   <subfield code="b">.M62</subfield>
   <subfield code="d">M1527.2</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="4">
   <subfield code="a">The Modern Jazz Quartet :</subfield>
   <subfield code="b">The legendary profile. --</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">New York :</subfield>
   <subfield code="b">M.J.Q. Music,</subfield>
   <subfield code="c">c1977.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">score (72 p.) ;</subfield>
   <subfield code="c">31 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">For piano, vibraphone, drums, and double bass.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">Lewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Motion picture music</subfield>
   <subfield code="v">Excerpts</subfield>
   <subfield code="v">Scores.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Lewis, John,</subfield>
   <subfield code="d">1920-</subfield>
   <subfield code="t">Selections.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Martyrs.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Legendary profile.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
   <subfield code="a">The legendary profile.</subfield>
  </datafield>
  <datafield tag="852" ind1="0" ind2="0">
   <subfield code="b">MUSIC</subfield>
   <subfield code="c">Audio-Visual</subfield>
   <subfield code="k">folio</subfield>
   <subfield code="h">M1366</subfield>
   <subfield code="i">M62</subfield>
   <subfield code="9">1</subfield>
   <subfield code="4">Marvin Duchow Music</subfield>
   <subfield code="5"></subfield>
  </datafield>
 </record>
</collection>
PKO1[�泮�File_MARC/tests/music.mrcnu�[���01145ncm  2200277 i 4500001001000000004000800010005001700018008004100035010001700076035002200093035001200115040000700127050002500134245005700159260003800216300002800254500005100282505026600333650001000599650004400609700004400653700003600697700004600733740002700779852006100806000073594AAJ580220030415102100.0801107s1977    nyujza                     a   77771106   a(CaOTUIC)154601849 aAAJ5802  aLC00aM1366b.M62dM1527.204aThe Modern Jazz Quartet :bThe legendary profile. --  aNew York :bM.J.Q. Music,cc1977.  ascore (72 p.) ;c31 cm.  aFor piano, vibraphone, drums, and double bass.0 aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile. 0aJazz. 0aMotion picture musicvExcerptsvScores.12aLewis, John,d1920-tSelections.f1977.12aJackson, Milt.tMartyrs.f1977.12aJackson, Milt.tLegendary profile.f1977.4 aThe legendary profile.00bMUSICcMAINkfoliohM1366iM62914Marvin Duchow Music5
01293cjm  2200289 a 450000100100000000500170001000700150002700800410004202400150008302800240009803500200012204000180014210000260016024500620018626000850024830000510033351101380038450000360052251800580055850000590061650000700067550501420074565000210088770000240090871000250093274000460095700187803920050110174900.0sd fungnn|||e|940202r19931981nyujzn   i              d1 a746457337202aJK 57337bRed Baron  a(OCoLC)29737267  aSVPcSVPdLGG1 aDesmond, Paul,d1924-10aPaul Desmond & the Modern Jazz Quarteth[sound recording]  aNew York, N.Y. :bRed Baron :bManufactured by Sony Music Entertainment,cp1993.  a1 sound disc (39 min.) :bdigital ;c4 3/4 in.0 aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.  aAll arrangements by John Lewis.  aRecorded live on December 25, 1971 at Town Hall, NYC.  aOriginally released in 1981 by Finesse as LP FW 27487.  aProgram notes by Irving Townsend, June 1981, on container insert.0 aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove. 0aJazzy1971-1980.1 aLewis, John,d1920-2 aModern Jazz Quartet.0 aPaul Desmond and the Modern Jazz Quartet.
01829cjm  2200385 a 450000100100000000500170001000700150002700800410004202400150008302800210009803300240011903300230014303300230016603300230018903500200021204000230023204800270025511000300028224500530031226000330036530000410039844000170043951102230045651802640067950000180094350000220096150502500098365000100123370000240124370000330126770000330130070000220133370000300135585200580138500196448220060626132700.0sd fzngnn|m|e|871211p19871957nyujzn                  d1 a422833290201a833 290-2bVerve0 a19571027b6299cD560 a196112--b3804cN40 a19571019b4104cC60 a197107--b6299cV7  a(OCoLC)17222092  aCPLcCPLdOCLdLGG  apz01aka01asd01apd012 aModern Jazz Quartet.4prf14aThe Modern Jazz Quartet plush[sound recording].  a[New York] :bVerve,cp1987.  a1 sound disc :bdigital ;c4 3/4 in. 0aCompact jazz0 aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.  aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).  aCompact disc.  aAnalog recording.0 aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20). 0aJazz.1 aJackson, Milt.4prf1 aPeterson, Oscar,d1925-4prf1 aBrown, Ray,d1926-2002.4prf1 aThigpen, Ed.4prf1 aHayes, Louis,d1937-4prf80bMUSICcAVhCD 11314Marvin Duchow Music5Audio-Visual
PKO1[E4kL�	�	File_MARC/tests/marc_001.phptnu�[���--TEST--
marc_001: iterate and pretty print a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'example.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01850     2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
020    _a9515008808
       _cFIM 72:00
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra ber�ttelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
841    _5Li
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5SEE
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5L
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5NB
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5Q
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5S
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
852    _5NB
       _bNB
       _cNB98:12
       _hplikt
       _jR, 980520
852    _5Li
       _bLi
       _cCNB
       _hh,u
852    _5SEE
       _bSEE
852    _5Q
       _bQ
       _j98947
852    _5L
       _bL
       _c0100
       _h98/
       _j3043 H
852    _5S
       _bS
       _hSv97
       _j7235
900 1s _aYanson, Tobe,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonov�, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansone, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonova, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
976  2 _aHcd,u
       _bSk�nlitteratur
005     20050204111518.0
PKO1[�#"�
)
)File_MARC/tests/marc_022.phptnu�[���--TEST--
marc_022: Insert fields
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

print "\nInsert a new 100 field before the first 650\n";
while ($record = $marc_file->next()) {
  print "\nNext record:\n";
  // Create the new field
  $subfields = null;
  $subfields[] = new File_MARC_Subfield('a', 'Scott, Daniel.');
  $new_field = new File_MARC_Data_Field('100', $subfields, 0, null);

  // Retrieve the target field for our insertion point
  $subject = $record->getFields('650');

  // Insert the new field
  if (is_array($subject)) {
    $record->insertField($new_field, $subject[0], true);
  }
  elseif ($subject) {
    $record->insertField($new_field, $subject, true);
  }
  print $record;
}

$record = null;
$marc_file = new File_MARC($dir . '/' . 'music.mrc');
print "\nInsert a new 100 field after the first 650\n";
while ($record = $marc_file->next()) {
  print "\nNext record:\n";
  // Create the new field
  $subfields = null;
  $subfields[] = new File_MARC_Subfield('a', 'Scott, Daniel.');
  $new_field = new File_MARC_Data_Field('100', $subfields, 0, null);

  // Retrieve the target field for our insertion point
  $subject = $record->getFields('650');

  // Insert the new field
  if (is_array($subject)) {
    $record->insertField($new_field, $subject[0]);
  }
  elseif ($subject) {
    $record->insertField($new_field, $subject);
  }
  print $record;
}
?>
--EXPECT--
Insert a new 100 field before the first 650

Next record:
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
100    _aScott, Daniel.
650  0 _aJazz.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

Next record:
LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
100    _aScott, Daniel.
650  0 _aJazz
       _y1971-1980.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

Next record:
LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
100    _aScott, Daniel.
650  0 _aJazz.
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual

Insert a new 100 field after the first 650

Next record:
LDR 01145ncm  2200277 i 4500
001     000073594
004     AAJ5802
005     20030415102100.0
008     801107s1977    nyujza                   
010    _a   77771106 
035    _a(CaOTUIC)15460184
035 9  _aAAJ5802
040    _aLC
050 00 _aM1366
       _b.M62
       _dM1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
300    _ascore (72 p.) ;
       _c31 cm.
500    _aFor piano, vibraphone, drums, and double bass.
505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
650  0 _aJazz.
100    _aScott, Daniel.
650  0 _aMotion picture music
       _vExcerpts
       _vScores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
740 4  _aThe legendary profile.
852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5

Next record:
LDR 01293cjm  2200289 a 4500
001     001878039
005     20050110174900.0
007     sd fungnn|||e|
008     940202r19931981nyujzn   i              d
024 1  _a7464573372
028 02 _aJK 57337
       _bRed Baron
035    _a(OCoLC)29737267
040    _aSVP
       _cSVP
       _dLGG
100 1  _aDesmond, Paul,
       _d1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
500    _aAll arrangements by John Lewis.
518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
500    _aOriginally released in 1981 by Finesse as LP FW 27487.
500    _aProgram notes by Irving Townsend, June 1981, on container insert.
505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
650  0 _aJazz
       _y1971-1980.
100    _aScott, Daniel.
700 1  _aLewis, John,
       _d1920-
710 2  _aModern Jazz Quartet.
740 0  _aPaul Desmond and the Modern Jazz Quartet.

Next record:
LDR 01829cjm  2200385 a 4500
001     001964482
005     20060626132700.0
007     sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
024 1  _a4228332902
028 01 _a833 290-2
       _bVerve
033 0  _a19571027
       _b6299
       _cD56
033 0  _a196112--
       _b3804
       _cN4
033 0  _a19571019
       _b4104
       _cC6
033 0  _a197107--
       _b6299
       _cV7
035    _a(OCoLC)17222092
040    _aCPL
       _cCPL
       _dOCL
       _dLGG
048    _apz01
       _aka01
       _asd01
       _apd01
110 2  _aModern Jazz Quartet.
       _4prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
440  0 _aCompact jazz
511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
500    _aCompact disc.
500    _aAnalog recording.
505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
650  0 _aJazz.
100    _aScott, Daniel.
700 1  _aJackson, Milt.
       _4prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
700 1  _aThigpen, Ed.
       _4prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
PKO1[�p̎u1u1File_MARC/tests/marc_016.phptnu�[���--TEST--
marc_016: generate a single collection of MARCXML records from a MARC record
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$records = new File_MARC($dir . '/' . 'music.mrc');

// Add the XML header and opening <collection> element
$records->toXMLHeader();

// Iterate through the retrieved records
while ($record = $records->next()) {

    // Change each 852 $c to "Audio-Visual"
    $holdings = $record->getFields('852');
    foreach ($holdings as $holding) {

        // Get the $c subfields from this field
        $formats = $holding->getSubfields('c');
        foreach ($formats as $format) {
            if ($format->getData('AV')) {
                $format->setData('Audio-Visual');
            }
        }
    }

    // Generate the XML output for this record
    print $record->toXML('UTF-8', true, false);
}
// Add the </collection> closing element and dump the XMLWriter contents
print $records->toXMLFooter();
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01145ncm  2200277 i 4500</leader>
  <controlfield tag="001">000073594</controlfield>
  <controlfield tag="004">AAJ5802</controlfield>
  <controlfield tag="005">20030415102100.0</controlfield>
  <controlfield tag="008">801107s1977    nyujza                   </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   77771106 </subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(CaOTUIC)15460184</subfield>
  </datafield>
  <datafield tag="035" ind1="9" ind2=" ">
   <subfield code="a">AAJ5802</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">LC</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">M1366</subfield>
   <subfield code="b">.M62</subfield>
   <subfield code="d">M1527.2</subfield>
  </datafield>
  <datafield tag="245" ind1="0" ind2="4">
   <subfield code="a">The Modern Jazz Quartet :</subfield>
   <subfield code="b">The legendary profile. --</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">New York :</subfield>
   <subfield code="b">M.J.Q. Music,</subfield>
   <subfield code="c">c1977.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">score (72 p.) ;</subfield>
   <subfield code="c">31 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">For piano, vibraphone, drums, and double bass.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">Lewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Motion picture music</subfield>
   <subfield code="v">Excerpts</subfield>
   <subfield code="v">Scores.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Lewis, John,</subfield>
   <subfield code="d">1920-</subfield>
   <subfield code="t">Selections.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Martyrs.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2="2">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="t">Legendary profile.</subfield>
   <subfield code="f">1977.</subfield>
  </datafield>
  <datafield tag="740" ind1="4" ind2=" ">
   <subfield code="a">The legendary profile.</subfield>
  </datafield>
  <datafield tag="852" ind1="0" ind2="0">
   <subfield code="b">MUSIC</subfield>
   <subfield code="c">Audio-Visual</subfield>
   <subfield code="k">folio</subfield>
   <subfield code="h">M1366</subfield>
   <subfield code="i">M62</subfield>
   <subfield code="9">1</subfield>
   <subfield code="4">Marvin Duchow Music</subfield>
   <subfield code="5"></subfield>
  </datafield>
 </record>
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01293cjm  2200289 a 4500</leader>
  <controlfield tag="001">001878039</controlfield>
  <controlfield tag="005">20050110174900.0</controlfield>
  <controlfield tag="007">sd fungnn|||e|</controlfield>
  <controlfield tag="008">940202r19931981nyujzn   i              d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
   <subfield code="a">7464573372</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="2">
   <subfield code="a">JK 57337</subfield>
   <subfield code="b">Red Baron</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(OCoLC)29737267</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">SVP</subfield>
   <subfield code="c">SVP</subfield>
   <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Desmond, Paul,</subfield>
   <subfield code="d">1924-</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
   <subfield code="a">Paul Desmond &amp; the Modern Jazz Quartet</subfield>
   <subfield code="h">[sound recording]</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">New York, N.Y. :</subfield>
   <subfield code="b">Red Baron :</subfield>
   <subfield code="b">Manufactured by Sony Music Entertainment,</subfield>
   <subfield code="c">p1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 sound disc (39 min.) :</subfield>
   <subfield code="b">digital ;</subfield>
   <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
   <subfield code="a">Paul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">All arrangements by John Lewis.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
   <subfield code="a">Recorded live on December 25, 1971 at Town Hall, NYC.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Originally released in 1981 by Finesse as LP FW 27487.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Program notes by Irving Townsend, June 1981, on container insert.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">Greensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz</subfield>
   <subfield code="y">1971-1980.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Lewis, John,</subfield>
   <subfield code="d">1920-</subfield>
  </datafield>
  <datafield tag="710" ind1="2" ind2=" ">
   <subfield code="a">Modern Jazz Quartet.</subfield>
  </datafield>
  <datafield tag="740" ind1="0" ind2=" ">
   <subfield code="a">Paul Desmond and the Modern Jazz Quartet.</subfield>
  </datafield>
 </record>
 <record xmlns="http://www.loc.gov/MARC21/slim">
  <leader>01829cjm  2200385 a 4500</leader>
  <controlfield tag="001">001964482</controlfield>
  <controlfield tag="005">20060626132700.0</controlfield>
  <controlfield tag="007">sd fzngnn|m|e|</controlfield>
  <controlfield tag="008">871211p19871957nyujzn                  d</controlfield>
  <datafield tag="024" ind1="1" ind2=" ">
   <subfield code="a">4228332902</subfield>
  </datafield>
  <datafield tag="028" ind1="0" ind2="1">
   <subfield code="a">833 290-2</subfield>
   <subfield code="b">Verve</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">19571027</subfield>
   <subfield code="b">6299</subfield>
   <subfield code="c">D56</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">196112--</subfield>
   <subfield code="b">3804</subfield>
   <subfield code="c">N4</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">19571019</subfield>
   <subfield code="b">4104</subfield>
   <subfield code="c">C6</subfield>
  </datafield>
  <datafield tag="033" ind1="0" ind2=" ">
   <subfield code="a">197107--</subfield>
   <subfield code="b">6299</subfield>
   <subfield code="c">V7</subfield>
  </datafield>
  <datafield tag="035" ind1=" " ind2=" ">
   <subfield code="a">(OCoLC)17222092</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">CPL</subfield>
   <subfield code="c">CPL</subfield>
   <subfield code="d">OCL</subfield>
   <subfield code="d">LGG</subfield>
  </datafield>
  <datafield tag="048" ind1=" " ind2=" ">
   <subfield code="a">pz01</subfield>
   <subfield code="a">ka01</subfield>
   <subfield code="a">sd01</subfield>
   <subfield code="a">pd01</subfield>
  </datafield>
  <datafield tag="110" ind1="2" ind2=" ">
   <subfield code="a">Modern Jazz Quartet.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="4">
   <subfield code="a">The Modern Jazz Quartet plus</subfield>
   <subfield code="h">[sound recording].</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">[New York] :</subfield>
   <subfield code="b">Verve,</subfield>
   <subfield code="c">p1987.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 sound disc :</subfield>
   <subfield code="b">digital ;</subfield>
   <subfield code="c">4 3/4 in.</subfield>
  </datafield>
  <datafield tag="440" ind1=" " ind2="0">
   <subfield code="a">Compact jazz</subfield>
  </datafield>
  <datafield tag="511" ind1="0" ind2=" ">
   <subfield code="a">Modern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.</subfield>
  </datafield>
  <datafield tag="518" ind1=" " ind2=" ">
   <subfield code="a">Recorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Compact disc.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">Analog recording.</subfield>
  </datafield>
  <datafield tag="505" ind1="0" ind2=" ">
   <subfield code="a">The golden striker (4:08) -- On Green Dolphin Street (7:28) -- D &amp; E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Jazz.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Jackson, Milt.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Peterson, Oscar,</subfield>
   <subfield code="d">1925-</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Brown, Ray,</subfield>
   <subfield code="d">1926-2002.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Thigpen, Ed.</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Hayes, Louis,</subfield>
   <subfield code="d">1937-</subfield>
   <subfield code="4">prf</subfield>
  </datafield>
  <datafield tag="852" ind1="8" ind2="0">
   <subfield code="b">MUSIC</subfield>
   <subfield code="c">Audio-Visual</subfield>
   <subfield code="h">CD 1131</subfield>
   <subfield code="4">Marvin Duchow Music</subfield>
   <subfield code="5">Audio-Visual</subfield>
  </datafield>
 </record>
</collection>
PKO1[O~iK!K!File_MARC/tests/marc_013.phptnu�[���--TEST--
marc_013: test formatField() convenience method
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'music.mrc');

while ($marc_record = $marc_file->next()) {
  $fields = $marc_record->getFields();
  foreach ($fields as $field) {
    print $field;
    print "\n";
    print $field->formatField();
    print "\n";
    print $field->formatField(array('a', '2', 'c'));
    print "\n";
  }
}

?>
--EXPECT--
001     000073594
000073594
000073594
004     AAJ5802
AAJ5802
AAJ5802
005     20030415102100.0
20030415102100.0
20030415102100.0
008     801107s1977    nyujza                   
801107s1977    nyujza                   
801107s1977    nyujza                   
010    _a   77771106 
77771106

035    _a(CaOTUIC)15460184
(CaOTUIC)15460184

035 9  _aAAJ5802
AAJ5802

040    _aLC
LC

050 00 _aM1366
       _b.M62
       _dM1527.2
M1366 .M62 M1527.2
.M62 M1527.2
245 04 _aThe Modern Jazz Quartet :
       _bThe legendary profile. --
The Modern Jazz Quartet : The legendary profile. --
The legendary profile. --
260    _aNew York :
       _bM.J.Q. Music,
       _cc1977.
New York : M.J.Q. Music, c1977.
M.J.Q. Music,
300    _ascore (72 p.) ;
       _c31 cm.
score (72 p.) ; 31 cm.

500    _aFor piano, vibraphone, drums, and double bass.
For piano, vibraphone, drums, and double bass.

505 0  _aLewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.
Lewis, J. Django.--Lewis, J. Plastic dreams (music from the film Kemek).--Lewis, J. Dancing (music from the film Kemek).--Lewis, J. Blues in A minor.--Lewis, J. Blues in B♭.--Lewis, J. Precious joy.--Jackson, M. The martyr.--Jackson, M. The legendary profile.

650  0 _aJazz.
Jazz.

650  0 _aMotion picture music
       _vExcerpts
       _vScores.
Motion picture music -- Excerpts -- Scores.
-- Excerpts -- Scores.
700 12 _aLewis, John,
       _d1920-
       _tSelections.
       _f1977.
Lewis, John, 1920- Selections. 1977.
1920- Selections. 1977.
700 12 _aJackson, Milt.
       _tMartyrs.
       _f1977.
Jackson, Milt. Martyrs. 1977.
Martyrs. 1977.
700 12 _aJackson, Milt.
       _tLegendary profile.
       _f1977.
Jackson, Milt. Legendary profile. 1977.
Legendary profile. 1977.
740 4  _aThe legendary profile.
The legendary profile.

852 00 _bMUSIC
       _cMAIN
       _kfolio
       _hM1366
       _iM62
       _91
       _4Marvin Duchow Music
       _5
MUSIC MAIN folio M1366 M62 1 Marvin Duchow Music
MUSIC folio M1366 M62 1 Marvin Duchow Music
001     001878039
001878039
001878039
005     20050110174900.0
20050110174900.0
20050110174900.0
007     sd fungnn|||e|
sd fungnn|||e|
sd fungnn|||e|
008     940202r19931981nyujzn   i              d
940202r19931981nyujzn   i              d
940202r19931981nyujzn   i              d
024 1  _a7464573372
7464573372

028 02 _aJK 57337
       _bRed Baron
JK 57337 Red Baron
Red Baron
035    _a(OCoLC)29737267
(OCoLC)29737267

040    _aSVP
       _cSVP
       _dLGG
SVP SVP LGG
LGG
100 1  _aDesmond, Paul,
       _d1924-
Desmond, Paul, 1924-
1924-
245 10 _aPaul Desmond & the Modern Jazz Quartet
       _h[sound recording]
Paul Desmond & the Modern Jazz Quartet [sound recording]
[sound recording]
260    _aNew York, N.Y. :
       _bRed Baron :
       _bManufactured by Sony Music Entertainment,
       _cp1993.
New York, N.Y. : Red Baron : Manufactured by Sony Music Entertainment, p1993.
Red Baron : Manufactured by Sony Music Entertainment,
300    _a1 sound disc (39 min.) :
       _bdigital ;
       _c4 3/4 in.
1 sound disc (39 min.) : digital ; 4 3/4 in.
digital ;
511 0  _aPaul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.
Paul Desmond, alto saxophone; Modern Jazz Quartet: John Lewis, piano; Milt Jackson, vibraphone; Percy Heath, bass; Connie Kay, drums.

500    _aAll arrangements by John Lewis.
All arrangements by John Lewis.

518    _aRecorded live on December 25, 1971 at Town Hall, NYC.
Recorded live on December 25, 1971 at Town Hall, NYC.

500    _aOriginally released in 1981 by Finesse as LP FW 27487.
Originally released in 1981 by Finesse as LP FW 27487.

500    _aProgram notes by Irving Townsend, June 1981, on container insert.
Program notes by Irving Townsend, June 1981, on container insert.

505 0  _aGreensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.
Greensleeves -- You go to my head -- Blue dove -- Jesus Christ Superstar -- Here's that rainy day -- East of the sun -- Bags' new groove.

650  0 _aJazz
       _y1971-1980.
Jazz -- 1971-1980.
-- 1971-1980.
700 1  _aLewis, John,
       _d1920-
Lewis, John, 1920-
1920-
710 2  _aModern Jazz Quartet.
Modern Jazz Quartet.

740 0  _aPaul Desmond and the Modern Jazz Quartet.
Paul Desmond and the Modern Jazz Quartet.

001     001964482
001964482
001964482
005     20060626132700.0
20060626132700.0
20060626132700.0
007     sd fzngnn|m|e|
sd fzngnn|m|e|
sd fzngnn|m|e|
008     871211p19871957nyujzn                  d
871211p19871957nyujzn                  d
871211p19871957nyujzn                  d
024 1  _a4228332902
4228332902

028 01 _a833 290-2
       _bVerve
833 290-2 Verve
Verve
033 0  _a19571027
       _b6299
       _cD56
19571027 6299 D56
6299
033 0  _a196112--
       _b3804
       _cN4
196112-- 3804 N4
3804
033 0  _a19571019
       _b4104
       _cC6
19571019 4104 C6
4104
033 0  _a197107--
       _b6299
       _cV7
197107-- 6299 V7
6299
035    _a(OCoLC)17222092
(OCoLC)17222092

040    _aCPL
       _cCPL
       _dOCL
       _dLGG
CPL CPL OCL LGG
OCL LGG
048    _apz01
       _aka01
       _asd01
       _apd01
pz01 ka01 sd01 pd01

110 2  _aModern Jazz Quartet.
       _4prf
Modern Jazz Quartet. prf
prf
245 14 _aThe Modern Jazz Quartet plus
       _h[sound recording].
The Modern Jazz Quartet plus [sound recording].
[sound recording].
260    _a[New York] :
       _bVerve,
       _cp1987.
[New York] : Verve, p1987.
Verve,
300    _a1 sound disc :
       _bdigital ;
       _c4 3/4 in.
1 sound disc : digital ; 4 3/4 in.
digital ;
440  0 _aCompact jazz
Compact jazz

511 0  _aModern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.
Modern Jazz Quartet (principally) ; Milt Jackson, vibraphone (2nd and 8th works) ; Oscar Peterson, piano (2nd and 8th works) ; Ray Brown, bass (2nd and 8th works) ; Ed Thigpen (2nd work), Louis Hayes (8th work), drums.

518    _aRecorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).
Recorded live, Oct. 27, 1957, at the Donaueschingen Jazz Festival (1st, 5th, 7th, and 10th works); Dec. 1961, in New York (2nd work); live, Oct. 19, 1957, at the Opera House, Chicago (3rd, 4th, 6th, and 9th works); July 1971, in Villingen, Germany (8th work).

500    _aCompact disc.
Compact disc.

500    _aAnalog recording.
Analog recording.

505 0  _aThe golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).
The golden striker (4:08) -- On Green Dolphin Street (7:28) -- D & E (4:55) -- I'll remember April (4:51) -- Cortège (7:15) -- Now's the time (4:43) -- J.B. blues (5:09) -- Reunion blues (6:35) -- 'Round midnight (3:56) -- Three windows (7:20).

650  0 _aJazz.
Jazz.

700 1  _aJackson, Milt.
       _4prf
Jackson, Milt. prf
prf
700 1  _aPeterson, Oscar,
       _d1925-
       _4prf
Peterson, Oscar, 1925- prf
1925- prf
700 1  _aBrown, Ray,
       _d1926-2002.
       _4prf
Brown, Ray, 1926-2002. prf
1926-2002. prf
700 1  _aThigpen, Ed.
       _4prf
Thigpen, Ed. prf
prf
700 1  _aHayes, Louis,
       _d1937-
       _4prf
Hayes, Louis, 1937- prf
1937- prf
852 80 _bMUSIC
       _cAV
       _hCD 1131
       _4Marvin Duchow Music
       _5Audio-Visual
MUSIC AV CD 1131 Marvin Duchow Music Audio-Visual
MUSIC CD 1131 Marvin Duchow Music Audio-Visual
PKO1[e����
�
File_MARC/tests/marc_011.phptnu�[���--TEST--
marc_011: iterate and pretty print a MARC record (SOURCE_STRING)
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

// Pull the MARC records into a string (as though we got it from YAZ)
$marc_string = file_get_contents($dir . '/' . 'example.mrc');

// Use the File_MARC::SOURCE_STRING flag to indicate that our source is a, uh, string
$marc_file = new File_MARC($marc_string, File_MARC::SOURCE_STRING);

while ($marc_record = $marc_file->next()) {
  print $marc_record;
  print "\n";
}
?>
--EXPECT--
LDR 01850     2200517   4500
001     0000000044
003     EMILDA
008     980120s1998    fi     j      000 0 swe
020    _a9515008808
       _cFIM 72:00
035    _99515008808
040    _aNB
042    _9NB
       _9SEE
084    _aHcd,u
       _2kssb/6
084    _5NB
       _auHc
       _2kssb
084    _5SEE
       _aHcf
       _2kssb/6
084    _5Q
       _aHcd,uf
       _2kssb/6
100 1  _aJansson, Tove,
       _d1914-2001
245 04 _aDet osynliga barnet och andra ber�ttelser /
       _cTove Jansson
250    _a7. uppl.
260    _aHelsingfors :
       _bSchildt,
       _c1998 ;
       _e(Falun :
       _fScandbook)
300    _a166, [4] s. :
       _bill. ;
       _c21 cm
440  0 _aMumin-biblioteket,
       _x99-0698931-9
500    _aOriginaluppl. 1962
599    _aLi: S
740 4  _aDet osynliga barnet
775 1  _z951-50-0385-7
       _w9515003857
       _907
841    _5Li
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5SEE
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5L
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5NB
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5Q
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
841    _5S
       _axa
       _b0201080u    0   4000uu   |000000
       _e1
852    _5NB
       _bNB
       _cNB98:12
       _hplikt
       _jR, 980520
852    _5Li
       _bLi
       _cCNB
       _hh,u
852    _5SEE
       _bSEE
852    _5Q
       _bQ
       _j98947
852    _5L
       _bL
       _c0100
       _h98/
       _j3043 H
852    _5S
       _bS
       _hSv97
       _j7235
900 1s _aYanson, Tobe,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonov�, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansone, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJansson, Tuve,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
900 1s _aJanssonova, Tove,
       _d1914-2001
       _uJansson, Tove,
       _d1914-2001
976  2 _aHcd,u
       _bSk�nlitteratur
005     20050204111518.0
PKP1[�>���!File_MARC/tests/marc_xml_003.phptnu�[���--TEST--
marc_xml_003: Round-trip a MARCXML record to MARC21 (LOC standard)
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARCXML($dir . '/' . 'sandburg.xml');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toRaw();
}
?>
--EXPECT--
01142cam  2200301 a 4500001001300000003000400013005001700017008004100034010001700075020002500092040001800117042000900135050002600144082001600170100003200186245008600218250001200304260005200316300004900368500004000417520022800457650003300685650003300718650002400751650002100775650002300796700002100819   92005291 DLC19930521155141.9920219s1993    caua   j      000 0 eng    a   92005291   a0152038655 :c$15.95  aDLCcDLCdDLC  alcac00aPS3537.A618bA88 199300a811/.522201 aSandburg, Carl,d1878-1967.10aArithmetic /cCarl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.  a1st ed.  aSan Diego :bHarcourt Brace Jovanovich,cc1993.  a1 v. (unpaged) :bill. (some col.) ;c26 cm.  aOne Mylar sheet included in pocket.  aA poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone. 0aArithmeticxJuvenile poetry. 0aChildren's poetry, American. 1aArithmeticxPoetry. 1aAmerican poetry. 1aVisual perception.1 aRand, Ted,eill.
PKP1[N���&&!File_MARC/tests/marc_xml_002.phptnu�[���--TEST--
marc_xml_002: iterate and pretty print a MARC record (LOC standard)
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';
$marc_file = new File_MARC($dir . '/' . 'sandburg.mrc');

while ($marc_record = $marc_file->next()) {
  print $marc_record->toXML();
  print "\n";
}
?>
--EXPECT--
<?xml version="1.0" encoding="UTF-8"?>
<collection xmlns="http://www.loc.gov/MARC21/slim">
 <record>
  <leader>01142cam  2200301 a 4500</leader>
  <controlfield tag="001">   92005291 </controlfield>
  <controlfield tag="003">DLC</controlfield>
  <controlfield tag="005">19930521155141.9</controlfield>
  <controlfield tag="008">920219s1993    caua   j      000 0 eng  </controlfield>
  <datafield tag="010" ind1=" " ind2=" ">
   <subfield code="a">   92005291 </subfield>
  </datafield>
  <datafield tag="020" ind1=" " ind2=" ">
   <subfield code="a">0152038655 :</subfield>
   <subfield code="c">$15.95</subfield>
  </datafield>
  <datafield tag="040" ind1=" " ind2=" ">
   <subfield code="a">DLC</subfield>
   <subfield code="c">DLC</subfield>
   <subfield code="d">DLC</subfield>
  </datafield>
  <datafield tag="042" ind1=" " ind2=" ">
   <subfield code="a">lcac</subfield>
  </datafield>
  <datafield tag="050" ind1="0" ind2="0">
   <subfield code="a">PS3537.A618</subfield>
   <subfield code="b">A88 1993</subfield>
  </datafield>
  <datafield tag="082" ind1="0" ind2="0">
   <subfield code="a">811/.52</subfield>
   <subfield code="2">20</subfield>
  </datafield>
  <datafield tag="100" ind1="1" ind2=" ">
   <subfield code="a">Sandburg, Carl,</subfield>
   <subfield code="d">1878-1967.</subfield>
  </datafield>
  <datafield tag="245" ind1="1" ind2="0">
   <subfield code="a">Arithmetic /</subfield>
   <subfield code="c">Carl Sandburg ; illustrated as an anamorphic adventure by Ted Rand.</subfield>
  </datafield>
  <datafield tag="250" ind1=" " ind2=" ">
   <subfield code="a">1st ed.</subfield>
  </datafield>
  <datafield tag="260" ind1=" " ind2=" ">
   <subfield code="a">San Diego :</subfield>
   <subfield code="b">Harcourt Brace Jovanovich,</subfield>
   <subfield code="c">c1993.</subfield>
  </datafield>
  <datafield tag="300" ind1=" " ind2=" ">
   <subfield code="a">1 v. (unpaged) :</subfield>
   <subfield code="b">ill. (some col.) ;</subfield>
   <subfield code="c">26 cm.</subfield>
  </datafield>
  <datafield tag="500" ind1=" " ind2=" ">
   <subfield code="a">One Mylar sheet included in pocket.</subfield>
  </datafield>
  <datafield tag="520" ind1=" " ind2=" ">
   <subfield code="a">A poem about numbers and their characteristics. Features anamorphic, or distorted, drawings which can be restored to normal by viewing from a particular angle or by viewing the image's reflection in the provided Mylar cone.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Juvenile poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="0">
   <subfield code="a">Children's poetry, American.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Arithmetic</subfield>
   <subfield code="x">Poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">American poetry.</subfield>
  </datafield>
  <datafield tag="650" ind1=" " ind2="1">
   <subfield code="a">Visual perception.</subfield>
  </datafield>
  <datafield tag="700" ind1="1" ind2=" ">
   <subfield code="a">Rand, Ted,</subfield>
   <subfield code="e">ill.</subfield>
  </datafield>
 </record>
</collection>
PKP1[y���
�
"File_MARC/tests/marc_lint_003.phptnu�[���--TEST--
marc_lint_003: Tests for field 880 and for subfield 6
--SKIPIF--
<?php include('tests/skipif.inc'); ?>
<?php include('tests/skipif_noispn.inc'); ?>
--FILE--
<?php
$dir = dirname(__FILE__);
require __DIR__ . '/bootstrap.php';

$marc_lint = new File_MARC_Lint();

$rec = new File_MARC_Record();
$rec->setLeader("00000nam  22002538a 4500");
$rec->appendField(
    new File_MARC_Control_Field(
        '001', 'ttt07000001 '
    )
);
$rec->appendField(
    new File_MARC_Control_Field(
        '003', 'TEST '
    )
);
$rec->appendField(
    new File_MARC_Control_Field(
        '008', '070520s2007    ilu           000 0 eng d'
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '040',
        array(
            new File_MARC_Subfield('a', 'TEST'),
            new File_MARC_Subfield('c', 'TEST')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '050',
        array(
            new File_MARC_Subfield('a', 'RZ999'),
            new File_MARC_Subfield('b', '.J66 2007')
        ),
        "", "4"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '082',
        array(
            new File_MARC_Subfield('a', '615.8/9'),
            new File_MARC_Subfield('2', '22')
        ),
        "0", "4"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '100',
        array(
            new File_MARC_Subfield('a', 'Jones, John')
        ),
        "1", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '245',
        array(
            new File_MARC_Subfield('6', '880-02'),
            new File_MARC_Subfield('a', 'Test 880.')
        ),
        "1", "0"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '260',
        array(
            new File_MARC_Subfield('a', 'Mount Morris, Ill. :'),
            new File_MARC_Subfield('b', "B. Baldus,"),
            new File_MARC_Subfield('c', '2007.')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '300',
        array(
            new File_MARC_Subfield('a', '1 v. ;'),
            new File_MARC_Subfield('c', '23 cm.')
        ),
        "", ""
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '880',
        array(
            new File_MARC_Subfield('6', '245-02/$1'),
            new File_MARC_Subfield('a', '<Title in CJK script>.')
        ),
        "1", "0"
    )
);
$rec->appendField(
    new File_MARC_Data_Field(
        '880',
        array(
            new File_MARC_Subfield('6', '245-02/$1'),
            new File_MARC_Subfield('a', 'Illegal duplicate field.')
        ),
        "1", "0"
    )
);
$warnings = $marc_lint->checkRecord($rec);
foreach ($warnings as $warning) {
  print $warning . "\n";
}

?>
--EXPECT--
245: Field is not repeatable.
PKP1[]�Q�� � MClassLoader/Symfony/Component/ClassLoader/Tests/ClassCollectionLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\ClassLoader\Tests;

use Symfony\Component\ClassLoader\ClassCollectionLoader;

require_once __DIR__.'/Fixtures/ClassesWithParents/GInterface.php';
require_once __DIR__.'/Fixtures/ClassesWithParents/CInterface.php';
require_once __DIR__.'/Fixtures/ClassesWithParents/B.php';
require_once __DIR__.'/Fixtures/ClassesWithParents/A.php';

class ClassCollectionLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testTraitDependencies()
    {
        if (version_compare(phpversion(), '5.4', '<')) {
            $this->markTestSkipped('Requires PHP > 5.4');

            return;
        }

        require_once __DIR__.'/Fixtures/deps/traits.php';

        $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader');
        $m = $r->getMethod('getOrderedClasses');
        $m->setAccessible(true);

        $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', array('CTFoo'));

        $this->assertEquals(
            array('TD', 'TC', 'TB', 'TA', 'TZ', 'CTFoo'),
            array_map(function ($class) { return $class->getName(); }, $ordered)
        );

        $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', array('CTBar'));

        $this->assertEquals(
            array('TD', 'TZ', 'TC', 'TB', 'TA', 'CTBar'),
            array_map(function ($class) { return $class->getName(); }, $ordered)
        );
    }

    /**
     * @dataProvider getDifferentOrders
     */
    public function testClassReordering(array $classes)
    {
        $expected = array(
            'ClassesWithParents\\GInterface',
            'ClassesWithParents\\CInterface',
            'ClassesWithParents\\B',
            'ClassesWithParents\\A',
        );

        $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader');
        $m = $r->getMethod('getOrderedClasses');
        $m->setAccessible(true);

        $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', $classes);

        $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered));
    }

    public function getDifferentOrders()
    {
        return array(
            array(array(
                'ClassesWithParents\\A',
                'ClassesWithParents\\CInterface',
                'ClassesWithParents\\GInterface',
                'ClassesWithParents\\B',
            )),
            array(array(
                'ClassesWithParents\\B',
                'ClassesWithParents\\A',
                'ClassesWithParents\\CInterface',
            )),
            array(array(
                'ClassesWithParents\\CInterface',
                'ClassesWithParents\\B',
                'ClassesWithParents\\A',
            )),
            array(array(
                'ClassesWithParents\\A',
            )),
        );
    }

    /**
     * @dataProvider getDifferentOrdersForTraits
     */
    public function testClassWithTraitsReordering(array $classes)
    {
        if (version_compare(phpversion(), '5.4', '<')) {
            $this->markTestSkipped('Requires PHP > 5.4');

            return;
        }

        require_once __DIR__.'/Fixtures/ClassesWithParents/ATrait.php';
        require_once __DIR__.'/Fixtures/ClassesWithParents/BTrait.php';
        require_once __DIR__.'/Fixtures/ClassesWithParents/CTrait.php';
        require_once __DIR__.'/Fixtures/ClassesWithParents/D.php';
        require_once __DIR__.'/Fixtures/ClassesWithParents/E.php';

        $expected = array(
            'ClassesWithParents\\GInterface',
            'ClassesWithParents\\CInterface',
            'ClassesWithParents\\ATrait',
            'ClassesWithParents\\BTrait',
            'ClassesWithParents\\CTrait',
            'ClassesWithParents\\B',
            'ClassesWithParents\\A',
            'ClassesWithParents\\D',
            'ClassesWithParents\\E',
        );

        $r = new \ReflectionClass('Symfony\Component\ClassLoader\ClassCollectionLoader');
        $m = $r->getMethod('getOrderedClasses');
        $m->setAccessible(true);

        $ordered = $m->invoke('Symfony\Component\ClassLoader\ClassCollectionLoader', $classes);

        $this->assertEquals($expected, array_map(function ($class) { return $class->getName(); }, $ordered));
    }

    public function getDifferentOrdersForTraits()
    {
        return array(
            array(array(
                'ClassesWithParents\\E',
                'ClassesWithParents\\ATrait',
            )),
            array(array(
                'ClassesWithParents\\E',
            )),
        );
    }

    /**
     * @dataProvider getFixNamespaceDeclarationsData
     */
    public function testFixNamespaceDeclarations($source, $expected)
    {
        $this->assertEquals('<?php '.$expected, ClassCollectionLoader::fixNamespaceDeclarations('<?php '.$source));
    }

    public function getFixNamespaceDeclarationsData()
    {
        return array(
            array("namespace;\nclass Foo {}\n", "namespace\n{\nclass Foo {}\n}"),
            array("namespace Foo;\nclass Foo {}\n", "namespace Foo\n{\nclass Foo {}\n}"),
            array("namespace   Bar ;\nclass Foo {}\n", "namespace Bar\n{\nclass Foo {}\n}"),
            array("namespace Foo\Bar;\nclass Foo {}\n", "namespace Foo\Bar\n{\nclass Foo {}\n}"),
            array("namespace Foo\Bar\Bar\n{\nclass Foo {}\n}\n", "namespace Foo\Bar\Bar\n{\nclass Foo {}\n}"),
            array("namespace\n{\nclass Foo {}\n}\n", "namespace\n{\nclass Foo {}\n}"),
        );
    }

    /**
     * @dataProvider getFixNamespaceDeclarationsDataWithoutTokenizer
     */
    public function testFixNamespaceDeclarationsWithoutTokenizer($source, $expected)
    {
        ClassCollectionLoader::enableTokenizer(false);
        $this->assertEquals('<?php '.$expected, ClassCollectionLoader::fixNamespaceDeclarations('<?php '.$source));
        ClassCollectionLoader::enableTokenizer(true);
    }

    public function getFixNamespaceDeclarationsDataWithoutTokenizer()
    {
        return array(
            array("namespace;\nclass Foo {}\n", "namespace\n{\nclass Foo {}\n}\n"),
            array("namespace Foo;\nclass Foo {}\n", "namespace Foo\n{\nclass Foo {}\n}\n"),
            array("namespace   Bar ;\nclass Foo {}\n", "namespace   Bar\n{\nclass Foo {}\n}\n"),
            array("namespace Foo\Bar;\nclass Foo {}\n", "namespace Foo\Bar\n{\nclass Foo {}\n}\n"),
            array("namespace Foo\Bar\Bar\n{\nclass Foo {}\n}\n", "namespace Foo\Bar\Bar\n{\nclass Foo {}\n}\n"),
            array("namespace\n{\nclass Foo {}\n}\n", "namespace\n{\nclass Foo {}\n}\n"),
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testUnableToLoadClassException()
    {
        if (is_file($file = sys_get_temp_dir().'/foo.php')) {
            unlink($file);
        }

        ClassCollectionLoader::load(array('SomeNotExistingClass'), sys_get_temp_dir(), 'foo', false);
    }

    public function testCommentStripping()
    {
        if (is_file($file = sys_get_temp_dir().'/bar.php')) {
            unlink($file);
        }
        spl_autoload_register($r = function ($class) {
            if (0 === strpos($class, 'Namespaced') || 0 === strpos($class, 'Pearlike_')) {
                require_once __DIR__.'/Fixtures/'.str_replace(array('\\', '_'), '/', $class).'.php';
            }
        });

        ClassCollectionLoader::load(
            array('Namespaced\\WithComments', 'Pearlike_WithComments'),
            sys_get_temp_dir(),
            'bar',
            false
        );

        spl_autoload_unregister($r);

        $this->assertEquals(<<<EOF
namespace Namespaced
{
class WithComments
{
public static \$loaded = true;
}
\$string ='string shoult not be   modified {\$string}';
\$heredoc = (<<<HD


Heredoc should not be   modified {\$string}


HD
);
\$nowdoc =<<<'ND'


Nowdoc should not be   modified {\$string}


ND
;
}
namespace
{
class Pearlike_WithComments
{
public static \$loaded = true;
}
}
EOF
        , str_replace("<?php \n", '', file_get_contents($file)));

        unlink($file);
    }
}
PKP1[h4A!AAJClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Bar.phpnu�[���<?php

class Pearlike2_Bar
{
    public static $loaded = true;
}
PKP1[��2[AAJClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Baz.phpnu�[���<?php

class Pearlike2_Baz
{
    public static $loaded = true;
}
PKP1[���	AAJClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Foo.phpnu�[���<?php

class Pearlike2_Foo
{
    public static $loaded = true;
}
PKP1[�Cq�""PClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeParent.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ClassMap;

abstract class SomeParent
{

}
PKP1[�֡Z  SClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeInterface.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ClassMap;

interface SomeInterface
{

}
PKP1[KG9Ո�PClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/multipleNs.phpnu�[���<?php
namespace {
    class A {}
}

namespace Alpha {
    class A {}
    class B {}
}

namespace Beta {
    class A {}
    class B {}
}
PKP1[�Қ[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/sameNsMultipleClasses.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Foo\Bar;

class A {}
class B {}
PKP1[.~�oDDOClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeClass.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ClassMap;

class SomeClass extends SomeParent implements SomeInterface
{

}
PKP1[�R��OClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/notPhpFile.mdnu�[���This file should be skipped.
PKP1[��iOClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/notAClass.phpnu�[���<?php

$a = new stdClass();
PKP1[�{�tKKYClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/C/B/Bar.phpnu�[���<?php

class PrefixCollision_C_B_Bar
{
    public static $loaded = true;
}
PKP1[P�F\KKYClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/C/B/Foo.phpnu�[���<?php

class PrefixCollision_C_B_Foo
{
    public static $loaded = true;
}
PKP1[�Lk�KKYClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/A/B/Bar.phpnu�[���<?php

class PrefixCollision_A_B_Bar
{
    public static $loaded = true;
}
PKP1[v�գKKYClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/A/B/Foo.phpnu�[���<?php

class PrefixCollision_A_B_Foo
{
    public static $loaded = true;
}
PKP1[��cZZ\ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/C/B/Bar.phpnu�[���<?php

namespace NamespaceCollision\C\B;

class Bar
{
    public static $loaded = true;
}
PKP1[LVAKZZ\ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/C/B/Foo.phpnu�[���<?php

namespace NamespaceCollision\C\B;

class Foo
{
    public static $loaded = true;
}
PKP1[Ka�AA\ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/A/B/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NamespaceCollision\A\B;

class Bar
{
    public static $loaded = true;
}
PKP1[����AA\ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NamespaceCollision\A\B;

class Foo
{
    public static $loaded = true;
}
PKP1[��@OOLClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Bar.phpnu�[���<?php

namespace Namespaced2;

class Bar
{
    public static $loaded = true;
}
PKP1[
Z3bOOLClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Baz.phpnu�[���<?php

namespace Namespaced2;

class Baz
{
    public static $loaded = true;
}
PKP1[d�0OOLClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Foo.phpnu�[���<?php

namespace Namespaced2;

class Foo
{
    public static $loaded = true;
}
PKP1[��55KClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Namespaced;

class Bar
{
    public static $loaded = true;
}
PKP1[ᒟ�55KClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Baz.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Namespaced;

class Baz
{
    public static $loaded = true;
}
PKP1[��R�55KClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Namespaced;

class Foo
{
    public static $loaded = true;
}
PKP1[�UX�TClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/WithComments.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Namespaced;

class WithComments
{
    /** @Boolean */
    public static $loaded = true;
}

$string = 'string shoult not be   modified {$string}';

$heredoc = (<<<HD


Heredoc should not be   modified {$string}


HD
);

$nowdoc = <<<'ND'


Nowdoc should not be   modified {$string}


ND;
PKP1[�d�LClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/includepath/Foo.phpnu�[���<?php

class Foo
{
}
PKP1[l�@@IClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Bar.phpnu�[���<?php

class Pearlike_Bar
{
    public static $loaded = true;
}
PKQ1[��q�@@IClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Baz.phpnu�[���<?php

class Pearlike_Baz
{
    public static $loaded = true;
}
PKQ1[�Ӽ�@@IClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Foo.phpnu�[���<?php

class Pearlike_Foo
{
    public static $loaded = true;
}
PKQ1[5J�DDRClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/WithComments.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

class Pearlike_WithComments
{
    /** @Boolean */
    public static $loaded = true;
}
PKQ1[�>�X��HClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/deps/traits.phpnu�[���<?php

trait TD
{}

trait TZ
{
    use TD;
}

trait TC
{
    use TD;
}

trait TB
{
    use TC;
}

trait TA
{
    use TB;
}

class CTFoo
{
    use TA;
    use TZ;
}

class CTBar
{
    use TZ;
    use TA;
}
PKQ1[:5T+JClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/php5.4/traits.phpnu�[���<?php
namespace {
    trait TFoo
    {
    }

    class CFoo
    {
        use TFoo;
    }
}

namespace Foo {
    trait TBar
    {
    }

    interface IBar
    {
    }

    trait TFooBar
    {
    }

    class CBar implements IBar
    {
        use TBar, TFooBar;
    }
}
PKQ1[�
N�77VClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/ATrait.phpnu�[���<?php

namespace ClassesWithParents;

trait ATrait
{
}
PKQ1[��`�RRZClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/CInterface.phpnu�[���<?php

namespace ClassesWithParents;

interface CInterface extends GInterface
{
}
PKQ1[��;;QClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/A.phpnu�[���<?php

namespace ClassesWithParents;

class A extends B {}
PKQ1[ ��LLQClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/D.phpnu�[���<?php

namespace ClassesWithParents;

class D extends A
{
    use BTrait;
}
PKQ1[t��LLQClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/E.phpnu�[���<?php

namespace ClassesWithParents;

class E extends D
{
    use CTrait;
}
PKQ1[��HGGVClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/BTrait.phpnu�[���<?php

namespace ClassesWithParents;

trait BTrait
{
    use ATrait;
}
PKQ1[��LqGGQClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/B.phpnu�[���<?php

namespace ClassesWithParents;

class B implements CInterface {}
PKQ1[[�"�77VClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/CTrait.phpnu�[���<?php

namespace ClassesWithParents;

trait CTrait
{
}
PKQ1[���Z??ZClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/GInterface.phpnu�[���<?php

namespace ClassesWithParents;

interface GInterface
{
}
PKQ1[�6S�IIXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/C/Bar.phpnu�[���<?php

class PrefixCollision_C_Bar
{
    public static $loaded = true;
}
PKQ1[	���IIXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/C/Foo.phpnu�[���<?php

class PrefixCollision_C_Foo
{
    public static $loaded = true;
}
PKQ1[&F�IIXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/A/Bar.phpnu�[���<?php

class PrefixCollision_A_Bar
{
    public static $loaded = true;
}
PKQ1[���IIXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/A/Foo.phpnu�[���<?php

class PrefixCollision_A_Foo
{
    public static $loaded = true;
}
PKQ1[�]�>XX[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.phpnu�[���<?php

namespace NamespaceCollision\C;

class Bar
{
    public static $loaded = true;
}
PKQ1[~�(XX[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/C/Foo.phpnu�[���<?php

namespace NamespaceCollision\C;

class Foo
{
    public static $loaded = true;
}
PKQ1[99A??[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/A/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NamespaceCollision\A;

class Bar
{
    public static $loaded = true;
}
PKQ1[���i??[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NamespaceCollision\A;

class Foo
{
    public static $loaded = true;
}
PKQ1[n��DDVClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Pearlike2/FooBar.phpnu�[���<?php

class Pearlike2_FooBar
{
    public static $loaded = true;
}
PKQ1[�gy�RRXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Namespaced2/FooBar.phpnu�[���<?php

namespace Namespaced2;

class FooBar
{
    public static $loaded = true;
}
PKR1[[�“88WClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Namespaced/FooBar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Namespaced;

class FooBar
{
    public static $loaded = true;
}
PKR1[x�wCCUClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Pearlike/FooBar.phpnu�[���<?php

class Pearlike_FooBar
{
    public static $loaded = true;
}
PKR1[>\oNNdClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.phpnu�[���<?php

class ApcPrefixCollision_A_B_Bar
{
    public static $loaded = true;
}
PKR1[���GNNdClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Foo.phpnu�[���<?php

class ApcPrefixCollision_A_B_Foo
{
    public static $loaded = true;
}
PKR1[�F�EEdClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\NamespaceCollision\A\B;

class Bar
{
    public static $loaded = true;
}
PKR1[]�[�EEdClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\NamespaceCollision\A\B;

class Foo
{
    public static $loaded = true;
}
PKR1[/5�<<RClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/FooBar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\Namespaced;

class FooBar
{
    public static $loaded = true;
}
PKR1[ے�99OClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\Namespaced;

class Bar
{
    public static $loaded = true;
}
PKR1[$�y99OClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Baz.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\Namespaced;

class Baz
{
    public static $loaded = true;
}
PKR1[0- +99OClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\Namespaced;

class Foo
{
    public static $loaded = true;
}
PKR1[yQUmDDMClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Bar.phpnu�[���<?php

class Apc_Pearlike_Bar
{
    public static $loaded = true;
}
PKR1[��&DDMClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Baz.phpnu�[���<?php

class Apc_Pearlike_Baz
{
    public static $loaded = true;
}
PKR1[���EDDMClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Foo.phpnu�[���<?php

class Apc_Pearlike_Foo
{
    public static $loaded = true;
}
PKR1[�7LLcClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/ApcPrefixCollision/A/Bar.phpnu�[���<?php

class ApcPrefixCollision_A_Bar
{
    public static $loaded = true;
}
PKR1[.��&LLcClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/ApcPrefixCollision/A/Foo.phpnu�[���<?php

class ApcPrefixCollision_A_Foo
{
    public static $loaded = true;
}
PKR1[4���CCcClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Bar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\NamespaceCollision\A;

class Bar
{
    public static $loaded = true;
}
PKR1[�qo�CCcClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\NamespaceCollision\A;

class Foo
{
    public static $loaded = true;
}
PKR1[/5�<<[ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/fallback/Namespaced/FooBar.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Apc\Namespaced;

class FooBar
{
    public static $loaded = true;
}
PKR1[���GG]ClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.phpnu�[���<?php

class Apc_Pearlike_FooBar
{
    public static $loaded = true;
}
PKR1[�M��� � CClassLoader/Symfony/Component/ClassLoader/Tests/ClassLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\ClassLoader\Tests;

use Symfony\Component\ClassLoader\ClassLoader;

class ClassLoaderTest extends \PHPUnit_Framework_TestCase
{
    public function testGetPrefixes()
    {
        $loader = new ClassLoader();
        $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $prefixes = $loader->getPrefixes();
        $this->assertArrayHasKey('Foo', $prefixes);
        $this->assertArrayNotHasKey('Foo1', $prefixes);
        $this->assertArrayHasKey('Bar', $prefixes);
        $this->assertArrayHasKey('Bas', $prefixes);
    }

    public function testGetFallbackDirs()
    {
        $loader = new ClassLoader();
        $loader->addPrefix(null, __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix(null, __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $fallback_dirs = $loader->getFallbackDirs();
        $this->assertCount(2, $fallback_dirs);
    }

    /**
     * @dataProvider getLoadClassTests
     */
    public function testLoadClass($className, $testClassName, $message)
    {
        $loader = new ClassLoader();
        $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->loadClass($testClassName);
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassTests()
    {
        return array(
            array('\\Namespaced2\\Foo', 'Namespaced2\\Foo',   '->loadClass() loads Namespaced2\Foo class'),
            array('\\Pearlike2_Foo',    'Pearlike2_Foo',      '->loadClass() loads Pearlike2_Foo class'),
        );
    }

    /**
     * @dataProvider getLoadNonexistentClassTests
     */
    public function testLoadNonexistentClass($className, $testClassName, $message)
    {
        $loader = new ClassLoader();
        $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->loadClass($testClassName);
        $this->assertFalse(class_exists($className), $message);
    }

    public function getLoadNonexistentClassTests()
    {
        return array(
            array('\\Pearlike3_Bar', '\\Pearlike3_Bar', '->loadClass() loads non existing Pearlike3_Bar class with a leading slash'),
        );
    }

    public function testAddPrefix()
    {
        $loader = new ClassLoader();
        $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $prefixes = $loader->getPrefixes();
        $this->assertArrayHasKey('Foo', $prefixes);
        $this->assertCount(2, $prefixes['Foo']);
    }

    public function testUseIncludePath()
    {
        $loader = new ClassLoader();
        $this->assertFalse($loader->getUseIncludePath());

        $this->assertNull($loader->findFile('Foo'));

        $includePath = get_include_path();

        $loader->setUseIncludePath(true);
        $this->assertTrue($loader->getUseIncludePath());

        set_include_path(__DIR__.'/Fixtures/includepath'.PATH_SEPARATOR.$includePath);

        $this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'includepath'.DIRECTORY_SEPARATOR.'Foo.php', $loader->findFile('Foo'));

        set_include_path($includePath);
    }

    /**
     * @dataProvider getLoadClassFromFallbackTests
     */
    public function testLoadClassFromFallback($className, $testClassName, $message)
    {
        $loader = new ClassLoader();
        $loader->addPrefix('Namespaced2\\', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('Pearlike2_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->addPrefix('', array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'));
        $loader->loadClass($testClassName);
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassFromFallbackTests()
    {
        return array(
            array('\\Namespaced2\\Baz',    'Namespaced2\\Baz',    '->loadClass() loads Namespaced2\Baz class'),
            array('\\Pearlike2_Baz',       'Pearlike2_Baz',       '->loadClass() loads Pearlike2_Baz class'),
            array('\\Namespaced2\\FooBar', 'Namespaced2\\FooBar', '->loadClass() loads Namespaced2\Baz class from fallback dir'),
            array('\\Pearlike2_FooBar',    'Pearlike2_FooBar',    '->loadClass() loads Pearlike2_Baz class from fallback dir'),
        );
    }

    /**
     * @dataProvider getLoadClassNamespaceCollisionTests
     */
    public function testLoadClassNamespaceCollision($namespaces, $className, $message)
    {
        $loader = new ClassLoader();
        $loader->addPrefixes($namespaces);

        $loader->loadClass($className);
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassNamespaceCollisionTests()
    {
        return array(
            array(
                array(
                    'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'NamespaceCollision\C\Foo',
                '->loadClass() loads NamespaceCollision\C\Foo from alpha.',
            ),
            array(
                array(
                    'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'NamespaceCollision\C\Bar',
                '->loadClass() loads NamespaceCollision\C\Bar from alpha.',
            ),
            array(
                array(
                    'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'NamespaceCollision\C\B\Foo',
                '->loadClass() loads NamespaceCollision\C\B\Foo from beta.',
            ),
            array(
                array(
                    'NamespaceCollision\\C\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'NamespaceCollision\\C' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'NamespaceCollision\C\B\Bar',
                '->loadClass() loads NamespaceCollision\C\B\Bar from beta.',
            ),
            array(
                array(
                    'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'PrefixCollision_C_Foo',
                '->loadClass() loads PrefixCollision_C_Foo from alpha.',
            ),
            array(
                array(
                    'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'PrefixCollision_C_Bar',
                '->loadClass() loads PrefixCollision_C_Bar from alpha.',
            ),
            array(
                array(
                    'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'PrefixCollision_C_B_Foo',
                '->loadClass() loads PrefixCollision_C_B_Foo from beta.',
            ),
            array(
                array(
                    'PrefixCollision_C_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'PrefixCollision_C_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'PrefixCollision_C_B_Bar',
                '->loadClass() loads PrefixCollision_C_B_Bar from beta.',
            ),
        );
    }
}
PKR1[e:{a��OClassLoader/Symfony/Component/ClassLoader/Tests/ApcUniversalClassLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\ClassLoader\Tests;

use Symfony\Component\ClassLoader\ApcUniversalClassLoader;

class ApcUniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        if (!extension_loaded('apc')) {
            $this->markTestSkipped('The apc extension is not available.');
        }

        if (!(ini_get('apc.enabled') && ini_get('apc.enable_cli'))) {
            $this->markTestSkipped('The apc extension is available, but not enabled.');
        } else {
            apc_clear_cache('user');
        }
    }

    protected function tearDown()
    {
        if (ini_get('apc.enabled') && ini_get('apc.enable_cli')) {
            apc_clear_cache('user');
        }
    }

    public function testConstructor()
    {
        $loader = new ApcUniversalClassLoader('test.prefix.');
        $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');

        $this->assertEquals($loader->findFile('\Apc\Namespaced\FooBar'), apc_fetch('test.prefix.\Apc\Namespaced\FooBar'), '__construct() takes a prefix as its first argument');
    }

   /**
    * @dataProvider getLoadClassTests
    */
   public function testLoadClass($className, $testClassName, $message)
   {
       $loader = new ApcUniversalClassLoader('test.prefix.');
       $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
       $loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
       $loader->loadClass($testClassName);
       $this->assertTrue(class_exists($className), $message);
   }

   public function getLoadClassTests()
   {
       return array(
           array('\\Apc\\Namespaced\\Foo', '\\Apc\\Namespaced\\Foo',   '->loadClass() loads Apc\Namespaced\Foo class'),
           array('Apc_Pearlike_Foo',    'Apc_Pearlike_Foo',      '->loadClass() loads Apc_Pearlike_Foo class'),
           array('\\Apc\\Namespaced\\Bar', '\\Apc\\Namespaced\\Bar', '->loadClass() loads Apc\Namespaced\Bar class with a leading slash'),
           array('Apc_Pearlike_Bar',    '\\Apc_Pearlike_Bar',    '->loadClass() loads Apc_Pearlike_Bar class with a leading slash'),
       );
   }

   /**
    * @dataProvider getLoadClassFromFallbackTests
    */
   public function testLoadClassFromFallback($className, $testClassName, $message)
   {
       $loader = new ApcUniversalClassLoader('test.prefix.fallback');
       $loader->registerNamespace('Apc\Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
       $loader->registerPrefix('Apc_Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
       $loader->registerNamespaceFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback'));
       $loader->registerPrefixFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/fallback'));
       $loader->loadClass($testClassName);
       $this->assertTrue(class_exists($className), $message);
   }

   public function getLoadClassFromFallbackTests()
   {
       return array(
           array('\\Apc\\Namespaced\\Baz',    '\\Apc\\Namespaced\\Baz',    '->loadClass() loads Apc\Namespaced\Baz class'),
           array('Apc_Pearlike_Baz',       'Apc_Pearlike_Baz',       '->loadClass() loads Apc_Pearlike_Baz class'),
           array('\\Apc\\Namespaced\\FooBar', '\\Apc\\Namespaced\\FooBar', '->loadClass() loads Apc\Namespaced\Baz class from fallback dir'),
           array('Apc_Pearlike_FooBar',    'Apc_Pearlike_FooBar',    '->loadClass() loads Apc_Pearlike_Baz class from fallback dir'),
       );
   }

   /**
    * @dataProvider getLoadClassNamespaceCollisionTests
    */
   public function testLoadClassNamespaceCollision($namespaces, $className, $message)
   {
       $loader = new ApcUniversalClassLoader('test.prefix.collision.');
       $loader->registerNamespaces($namespaces);

       $loader->loadClass($className);

       $this->assertTrue(class_exists($className), $message);
   }

   public function getLoadClassNamespaceCollisionTests()
   {
       return array(
           array(
               array(
                   'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
                   'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
               ),
               '\Apc\NamespaceCollision\A\Foo',
               '->loadClass() loads NamespaceCollision\A\Foo from alpha.',
           ),
           array(
               array(
                   'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
                   'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
               ),
               '\Apc\NamespaceCollision\A\Bar',
               '->loadClass() loads NamespaceCollision\A\Bar from alpha.',
           ),
           array(
               array(
                   'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
                   'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
               ),
               '\Apc\NamespaceCollision\A\B\Foo',
               '->loadClass() loads NamespaceCollision\A\B\Foo from beta.',
           ),
           array(
               array(
                   'Apc\\NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta',
                   'Apc\\NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha',
               ),
               '\Apc\NamespaceCollision\A\B\Bar',
               '->loadClass() loads NamespaceCollision\A\B\Bar from beta.',
           ),
       );
   }

   /**
    * @dataProvider getLoadClassPrefixCollisionTests
    */
   public function testLoadClassPrefixCollision($prefixes, $className, $message)
   {
       $loader = new ApcUniversalClassLoader('test.prefix.collision.');
       $loader->registerPrefixes($prefixes);

       $loader->loadClass($className);
       $this->assertTrue(class_exists($className), $message);
   }

   public function getLoadClassPrefixCollisionTests()
   {
       return array(
           array(
               array(
                   'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
                   'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
               ),
               'ApcPrefixCollision_A_Foo',
               '->loadClass() loads ApcPrefixCollision_A_Foo from alpha.',
           ),
           array(
               array(
                   'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
                   'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
               ),
               'ApcPrefixCollision_A_Bar',
               '->loadClass() loads ApcPrefixCollision_A_Bar from alpha.',
           ),
           array(
               array(
                   'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
                   'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
               ),
               'ApcPrefixCollision_A_B_Foo',
               '->loadClass() loads ApcPrefixCollision_A_B_Foo from beta.',
           ),
           array(
               array(
                   'ApcPrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/beta/Apc',
                   'ApcPrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/Apc/alpha/Apc',
               ),
               'ApcPrefixCollision_A_B_Bar',
               '->loadClass() loads ApcPrefixCollision_A_B_Bar from beta.',
           ),
       );
   }
}
PKR1[8`�##LClassLoader/Symfony/Component/ClassLoader/Tests/UniversalClassLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\ClassLoader\Tests;

use Symfony\Component\ClassLoader\UniversalClassLoader;

class UniversalClassLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getLoadClassTests
     */
    public function testLoadClass($className, $testClassName, $message)
    {
        $loader = new UniversalClassLoader();
        $loader->registerNamespace('Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerPrefix('Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $this->assertTrue($loader->loadClass($testClassName));
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassTests()
    {
        return array(
            array('\\Namespaced\\Foo', 'Namespaced\\Foo',   '->loadClass() loads Namespaced\Foo class'),
            array('\\Pearlike_Foo',    'Pearlike_Foo',      '->loadClass() loads Pearlike_Foo class'),
        );
    }

    public function testUseIncludePath()
    {
        $loader = new UniversalClassLoader();
        $this->assertFalse($loader->getUseIncludePath());

        $this->assertNull($loader->findFile('Foo'));

        $includePath = get_include_path();

        $loader->useIncludePath(true);
        $this->assertTrue($loader->getUseIncludePath());

        set_include_path(__DIR__.'/Fixtures/includepath'.PATH_SEPARATOR.$includePath);

        $this->assertEquals(__DIR__.DIRECTORY_SEPARATOR.'Fixtures'.DIRECTORY_SEPARATOR.'includepath'.DIRECTORY_SEPARATOR.'Foo.php', $loader->findFile('Foo'));

        set_include_path($includePath);
    }

    public function testGetNamespaces()
    {
        $loader = new UniversalClassLoader();
        $loader->registerNamespace('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerNamespace('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerNamespace('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $namespaces = $loader->getNamespaces();
        $this->assertArrayHasKey('Foo', $namespaces);
        $this->assertArrayNotHasKey('Foo1', $namespaces);
        $this->assertArrayHasKey('Bar', $namespaces);
        $this->assertArrayHasKey('Bas', $namespaces);
    }

    public function testGetPrefixes()
    {
        $loader = new UniversalClassLoader();
        $loader->registerPrefix('Foo', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerPrefix('Bar', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerPrefix('Bas', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $prefixes = $loader->getPrefixes();
        $this->assertArrayHasKey('Foo', $prefixes);
        $this->assertArrayNotHasKey('Foo1', $prefixes);
        $this->assertArrayHasKey('Bar', $prefixes);
        $this->assertArrayHasKey('Bas', $prefixes);
    }

    /**
     * @dataProvider getLoadClassFromFallbackTests
     */
    public function testLoadClassFromFallback($className, $testClassName, $message)
    {
        $loader = new UniversalClassLoader();
        $loader->registerNamespace('Namespaced', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerPrefix('Pearlike_', __DIR__.DIRECTORY_SEPARATOR.'Fixtures');
        $loader->registerNamespaceFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'));
        $loader->registerPrefixFallbacks(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'));
        $this->assertTrue($loader->loadClass($testClassName));
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassFromFallbackTests()
    {
        return array(
            array('\\Namespaced\\Baz',    'Namespaced\\Baz',    '->loadClass() loads Namespaced\Baz class'),
            array('\\Pearlike_Baz',       'Pearlike_Baz',       '->loadClass() loads Pearlike_Baz class'),
            array('\\Namespaced\\FooBar', 'Namespaced\\FooBar', '->loadClass() loads Namespaced\Baz class from fallback dir'),
            array('\\Pearlike_FooBar',    'Pearlike_FooBar',    '->loadClass() loads Pearlike_Baz class from fallback dir'),
        );
    }

    public function testRegisterPrefixFallback()
    {
        $loader = new UniversalClassLoader();
        $loader->registerPrefixFallback(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback');
        $this->assertEquals(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/fallback'), $loader->getPrefixFallbacks());
    }

    public function testRegisterNamespaceFallback()
    {
        $loader = new UniversalClassLoader();
        $loader->registerNamespaceFallback(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Namespaced/fallback');
        $this->assertEquals(array(__DIR__.DIRECTORY_SEPARATOR.'Fixtures/Namespaced/fallback'), $loader->getNamespaceFallbacks());
    }

    /**
     * @dataProvider getLoadClassNamespaceCollisionTests
     */
    public function testLoadClassNamespaceCollision($namespaces, $className, $message)
    {
        $loader = new UniversalClassLoader();
        $loader->registerNamespaces($namespaces);

        $this->assertTrue($loader->loadClass($className));
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassNamespaceCollisionTests()
    {
        return array(
            array(
                array(
                    'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'NamespaceCollision\A\Foo',
                '->loadClass() loads NamespaceCollision\A\Foo from alpha.',
            ),
            array(
                array(
                    'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'NamespaceCollision\A\Bar',
                '->loadClass() loads NamespaceCollision\A\Bar from alpha.',
            ),
            array(
                array(
                    'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'NamespaceCollision\A\B\Foo',
                '->loadClass() loads NamespaceCollision\A\B\Foo from beta.',
            ),
            array(
                array(
                    'NamespaceCollision\\A\\B' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'NamespaceCollision\\A' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'NamespaceCollision\A\B\Bar',
                '->loadClass() loads NamespaceCollision\A\B\Bar from beta.',
            ),
        );
    }

    /**
     * @dataProvider getLoadClassPrefixCollisionTests
     */
    public function testLoadClassPrefixCollision($prefixes, $className, $message)
    {
        $loader = new UniversalClassLoader();
        $loader->registerPrefixes($prefixes);

        $this->assertTrue($loader->loadClass($className));
        $this->assertTrue(class_exists($className), $message);
    }

    public function getLoadClassPrefixCollisionTests()
    {
        return array(
            array(
                array(
                    'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'PrefixCollision_A_Foo',
                '->loadClass() loads PrefixCollision_A_Foo from alpha.',
            ),
            array(
                array(
                    'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'PrefixCollision_A_Bar',
                '->loadClass() loads PrefixCollision_A_Bar from alpha.',
            ),
            array(
                array(
                    'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                    'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                ),
                'PrefixCollision_A_B_Foo',
                '->loadClass() loads PrefixCollision_A_B_Foo from beta.',
            ),
            array(
                array(
                    'PrefixCollision_A_B_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/beta',
                    'PrefixCollision_A_' => __DIR__.DIRECTORY_SEPARATOR.'Fixtures/alpha',
                ),
                'PrefixCollision_A_B_Bar',
                '->loadClass() loads PrefixCollision_A_B_Bar from beta.',
            ),
        );
    }
}
PKR1[\|����IClassLoader/Symfony/Component/ClassLoader/Tests/ClassMapGeneratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\ClassLoader\Tests;

use Symfony\Component\ClassLoader\ClassMapGenerator;

class ClassMapGeneratorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var string $workspace
     */
    private $workspace = null;

    public function prepare_workspace()
    {
        $this->workspace = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.time().rand(0, 1000);
        mkdir($this->workspace, 0777, true);
        $this->workspace = realpath($this->workspace);
    }

    /**
     * @param string $file
     */
    private function clean($file)
    {
        if (is_dir($file) && !is_link($file)) {
            $dir = new \FilesystemIterator($file);
            foreach ($dir as $childFile) {
                $this->clean($childFile);
            }

            rmdir($file);
        } else {
            unlink($file);
        }
    }

    /**
     * @dataProvider getTestCreateMapTests
     */
    public function testDump($directory, $expected)
    {
        $this->prepare_workspace();

        $file = $this->workspace.'/file';

        $generator = new ClassMapGenerator();
        $generator->dump($directory, $file);
        $this->assertFileExists($file);

        $this->clean($this->workspace);
    }

    /**
     * @dataProvider getTestCreateMapTests
     */
    public function testCreateMap($directory, $expected)
    {
        $this->assertEqualsNormalized($expected, ClassMapGenerator::createMap($directory));
    }

    public function getTestCreateMapTests()
    {
        $data = array(
            array(__DIR__.'/Fixtures/Namespaced', array(
                'Namespaced\\Bar'          => realpath(__DIR__).'/Fixtures/Namespaced/Bar.php',
                'Namespaced\\Foo'          => realpath(__DIR__).'/Fixtures/Namespaced/Foo.php',
                'Namespaced\\Baz'          => realpath(__DIR__).'/Fixtures/Namespaced/Baz.php',
                'Namespaced\\WithComments' => realpath(__DIR__).'/Fixtures/Namespaced/WithComments.php',
                )
            ),
            array(__DIR__.'/Fixtures/beta/NamespaceCollision', array(
                'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php',
                'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php',
                'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php',
                'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php',
            )),
            array(__DIR__.'/Fixtures/Pearlike', array(
                'Pearlike_Foo'          => realpath(__DIR__).'/Fixtures/Pearlike/Foo.php',
                'Pearlike_Bar'          => realpath(__DIR__).'/Fixtures/Pearlike/Bar.php',
                'Pearlike_Baz'          => realpath(__DIR__).'/Fixtures/Pearlike/Baz.php',
                'Pearlike_WithComments' => realpath(__DIR__).'/Fixtures/Pearlike/WithComments.php',
            )),
            array(__DIR__.'/Fixtures/classmap', array(
                'Foo\\Bar\\A'             => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php',
                'Foo\\Bar\\B'             => realpath(__DIR__).'/Fixtures/classmap/sameNsMultipleClasses.php',
                'A'                       => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php',
                'Alpha\\A'                => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php',
                'Alpha\\B'                => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php',
                'Beta\\A'                 => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php',
                'Beta\\B'                 => realpath(__DIR__).'/Fixtures/classmap/multipleNs.php',
                'ClassMap\\SomeInterface' => realpath(__DIR__).'/Fixtures/classmap/SomeInterface.php',
                'ClassMap\\SomeParent'    => realpath(__DIR__).'/Fixtures/classmap/SomeParent.php',
                'ClassMap\\SomeClass'     => realpath(__DIR__).'/Fixtures/classmap/SomeClass.php',
            )),
        );

        if (version_compare(PHP_VERSION, '5.4', '>=')) {
            $data[] = array(__DIR__.'/Fixtures/php5.4', array(
                'TFoo' => __DIR__.'/Fixtures/php5.4/traits.php',
                'CFoo' => __DIR__.'/Fixtures/php5.4/traits.php',
                'Foo\\TBar' => __DIR__.'/Fixtures/php5.4/traits.php',
                'Foo\\IBar' => __DIR__.'/Fixtures/php5.4/traits.php',
                'Foo\\TFooBar' => __DIR__.'/Fixtures/php5.4/traits.php',
                'Foo\\CBar' => __DIR__.'/Fixtures/php5.4/traits.php',
            ));
        }

        return $data;
    }

    public function testCreateMapFinderSupport()
    {
        $finder = new \Symfony\Component\Finder\Finder();
        $finder->files()->in(__DIR__.'/Fixtures/beta/NamespaceCollision');

        $this->assertEqualsNormalized(array(
            'NamespaceCollision\\A\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Bar.php',
            'NamespaceCollision\\A\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/A/B/Foo.php',
            'NamespaceCollision\\C\\B\\Bar' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Bar.php',
            'NamespaceCollision\\C\\B\\Foo' => realpath(__DIR__).'/Fixtures/beta/NamespaceCollision/C/B/Foo.php',
        ), ClassMapGenerator::createMap($finder));
    }

    protected function assertEqualsNormalized($expected, $actual, $message = null)
    {
        foreach ($expected as $ns => $path) {
            $expected[$ns] = strtr($path, '\\', '/');
        }
        foreach ($actual as $ns => $path) {
            $actual[$ns] = strtr($path, '\\', '/');
        }
        $this->assertEquals($expected, $actual, $message);
    }
}
PKR1[�)mm:ClassLoader/Symfony/Component/ClassLoader/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony ClassLoader Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PKS1[y�MV����XDependencyInjection/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

require_once __DIR__.'/Fixtures/includes/classes.php';
require_once __DIR__.'/Fixtures/includes/ProjectExtension.php';

use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\ExpressionLanguage\Expression;

class ContainerBuilderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setDefinitions
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getDefinitions
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setDefinition
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getDefinition
     */
    public function testDefinitions()
    {
        $builder = new ContainerBuilder();
        $definitions = array(
            'foo' => new Definition('FooClass'),
            'bar' => new Definition('BarClass'),
        );
        $builder->setDefinitions($definitions);
        $this->assertEquals($definitions, $builder->getDefinitions(), '->setDefinitions() sets the service definitions');
        $this->assertTrue($builder->hasDefinition('foo'), '->hasDefinition() returns true if a service definition exists');
        $this->assertFalse($builder->hasDefinition('foobar'), '->hasDefinition() returns false if a service definition does not exist');

        $builder->setDefinition('foobar', $foo = new Definition('FooBarClass'));
        $this->assertEquals($foo, $builder->getDefinition('foobar'), '->getDefinition() returns a service definition if defined');
        $this->assertTrue($builder->setDefinition('foobar', $foo = new Definition('FooBarClass')) === $foo, '->setDefinition() implements a fluid interface by returning the service reference');

        $builder->addDefinitions($defs = array('foobar' => new Definition('FooBarClass')));
        $this->assertEquals(array_merge($definitions, $defs), $builder->getDefinitions(), '->addDefinitions() adds the service definitions');

        try {
            $builder->getDefinition('baz');
            $this->fail('->getDefinition() throws an InvalidArgumentException if the service definition does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals('The service definition "baz" does not exist.', $e->getMessage(), '->getDefinition() throws an InvalidArgumentException if the service definition does not exist');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::register
     */
    public function testRegister()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'FooClass');
        $this->assertTrue($builder->hasDefinition('foo'), '->register() registers a new service definition');
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $builder->getDefinition('foo'), '->register() returns the newly created Definition instance');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::has
     */
    public function testHas()
    {
        $builder = new ContainerBuilder();
        $this->assertFalse($builder->has('foo'), '->has() returns false if the service does not exist');
        $builder->register('foo', 'FooClass');
        $this->assertTrue($builder->has('foo'), '->has() returns true if a service definition exists');
        $builder->set('bar', new \stdClass());
        $this->assertTrue($builder->has('bar'), '->has() returns true if a service exists');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get
     */
    public function testGet()
    {
        $builder = new ContainerBuilder();
        try {
            $builder->get('foo');
            $this->fail('->get() throws an InvalidArgumentException if the service does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals('The service definition "foo" does not exist.', $e->getMessage(), '->get() throws an InvalidArgumentException if the service does not exist');
        }

        $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument');

        $builder->register('foo', 'stdClass');
        $this->assertInternalType('object', $builder->get('foo'), '->get() returns the service definition associated with the id');
        $builder->set('bar', $bar = new \stdClass());
        $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id');
        $builder->register('bar', 'stdClass');
        $this->assertEquals($bar, $builder->get('bar'), '->get() returns the service associated with the id even if a definition has been defined');

        $builder->register('baz', 'stdClass')->setArguments(array(new Reference('baz')));
        try {
            @$builder->get('baz');
            $this->fail('->get() throws a ServiceCircularReferenceException if the service has a circular reference to itself');
        } catch (\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException $e) {
            $this->assertEquals('Circular reference detected for service "baz", path: "baz".', $e->getMessage(), '->get() throws a LogicException if the service has a circular reference to itself');
        }

        $builder->register('foobar', 'stdClass')->setScope('container');
        $this->assertTrue($builder->get('bar') === $builder->get('bar'), '->get() always returns the same instance if the service is shared');
    }

    /**
     * @covers                   \Symfony\Component\DependencyInjection\ContainerBuilder::get
     * @expectedException        \Symfony\Component\DependencyInjection\Exception\RuntimeException
     * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service.
     */
    public function testGetUnsetLoadingServiceWhenCreateServiceThrowsAnException()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'stdClass')->setSynthetic(true);

        // we expect a RuntimeException here as foo is synthetic
        try {
            $builder->get('foo');
        } catch (RuntimeException $e) {
        }

        // we must also have the same RuntimeException here
        $builder->get('foo');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get
     */
    public function testGetReturnsNullOnInactiveScope()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'stdClass')->setScope('request');

        $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::get
     */
    public function testGetReturnsNullOnInactiveScopeWhenServiceIsCreatedByAMethod()
    {
        $builder = new ProjectContainer();

        $this->assertNull($builder->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getServiceIds
     */
    public function testGetServiceIds()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'stdClass');
        $builder->bar = $bar = new \stdClass();
        $builder->register('bar', 'stdClass');
        $this->assertEquals(array('foo', 'bar', 'service_container'), $builder->getServiceIds(), '->getServiceIds() returns all defined service ids');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setAlias
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::hasAlias
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getAlias
     */
    public function testAliases()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'stdClass');
        $builder->setAlias('bar', 'foo');
        $this->assertTrue($builder->hasAlias('bar'), '->hasAlias() returns true if the alias exists');
        $this->assertFalse($builder->hasAlias('foobar'), '->hasAlias() returns false if the alias does not exist');
        $this->assertEquals('foo', (string) $builder->getAlias('bar'), '->getAlias() returns the aliased service');
        $this->assertTrue($builder->has('bar'), '->setAlias() defines a new service');
        $this->assertTrue($builder->get('bar') === $builder->get('foo'), '->setAlias() creates a service that is an alias to another one');

        try {
            $builder->getAlias('foobar');
            $this->fail('->getAlias() throws an InvalidArgumentException if the alias does not exist');
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals('The service alias "foobar" does not exist.', $e->getMessage(), '->getAlias() throws an InvalidArgumentException if the alias does not exist');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getAliases
     */
    public function testGetAliases()
    {
        $builder = new ContainerBuilder();
        $builder->setAlias('bar', 'foo');
        $builder->setAlias('foobar', 'foo');
        $builder->setAlias('moo', new Alias('foo', false));

        $aliases = $builder->getAliases();
        $this->assertEquals('foo', (string) $aliases['bar']);
        $this->assertTrue($aliases['bar']->isPublic());
        $this->assertEquals('foo', (string) $aliases['foobar']);
        $this->assertEquals('foo', (string) $aliases['moo']);
        $this->assertFalse($aliases['moo']->isPublic());

        $builder->register('bar', 'stdClass');
        $this->assertFalse($builder->hasAlias('bar'));

        $builder->set('foobar', 'stdClass');
        $builder->set('moo', 'stdClass');
        $this->assertCount(0, $builder->getAliases(), '->getAliases() does not return aliased services that have been overridden');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::setAliases
     */
    public function testSetAliases()
    {
        $builder = new ContainerBuilder();
        $builder->setAliases(array('bar' => 'foo', 'foobar' => 'foo'));

        $aliases = $builder->getAliases();
        $this->assertTrue(isset($aliases['bar']));
        $this->assertTrue(isset($aliases['foobar']));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addAliases
     */
    public function testAddAliases()
    {
        $builder = new ContainerBuilder();
        $builder->setAliases(array('bar' => 'foo'));
        $builder->addAliases(array('foobar' => 'foo'));

        $aliases = $builder->getAliases();
        $this->assertTrue(isset($aliases['bar']));
        $this->assertTrue(isset($aliases['foobar']));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addCompilerPass
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getCompilerPassConfig
     */
    public function testAddGetCompilerPass()
    {
        $builder = new ContainerBuilder();
        $builder->setResourceTracking(false);
        $builderCompilerPasses = $builder->getCompiler()->getPassConfig()->getPasses();
        $builder->addCompilerPass($this->getMock('Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface'));
        $this->assertEquals(sizeof($builderCompilerPasses) + 1, sizeof($builder->getCompiler()->getPassConfig()->getPasses()));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateService()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo1', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php');
        $this->assertInstanceOf('\FooClass', $builder->get('foo1'), '->createService() requires the file defined by the service definition');
        $builder->register('foo2', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/%file%.php');
        $builder->setParameter('file', 'foo');
        $this->assertInstanceOf('\FooClass', $builder->get('foo2'), '->createService() replaces parameters in the file provided by the service definition');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateProxyWithRealServiceInstantiator()
    {
        $builder = new ContainerBuilder();

        $builder->register('foo1', 'FooClass')->setFile(__DIR__.'/Fixtures/includes/foo.php');
        $builder->getDefinition('foo1')->setLazy(true);

        $foo1 = $builder->get('foo1');

        $this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved on multiple subsequent calls');
        $this->assertSame('FooClass', get_class($foo1));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceClass()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo1', '%class%');
        $builder->setParameter('class', 'stdClass');
        $this->assertInstanceOf('\stdClass', $builder->get('foo1'), '->createService() replaces parameters in the class provided by the service definition');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceArguments()
    {
        $builder = new ContainerBuilder();
        $builder->register('bar', 'stdClass');
        $builder->register('foo1', 'FooClass')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar'), '%%unescape_it%%'));
        $builder->setParameter('value', 'bar');
        $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar'), '%unescape_it%'), $builder->get('foo1')->arguments, '->createService() replaces parameters and service references in the arguments provided by the service definition');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceFactoryMethod()
    {
        $builder = new ContainerBuilder();
        $builder->register('bar', 'stdClass');
        $builder->register('foo1', 'FooClass')->setFactoryClass('FooClass')->setFactoryMethod('getInstance')->addArgument(array('foo' => '%value%', '%value%' => 'foo', new Reference('bar')));
        $builder->setParameter('value', 'bar');
        $this->assertTrue($builder->get('foo1')->called, '->createService() calls the factory method to create the service instance');
        $this->assertEquals(array('foo' => 'bar', 'bar' => 'foo', $builder->get('bar')), $builder->get('foo1')->arguments, '->createService() passes the arguments to the factory method');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceFactoryService()
    {
        $builder = new ContainerBuilder();
        $builder->register('baz_service')->setFactoryService('baz_factory')->setFactoryMethod('getInstance');
        $builder->register('baz_factory', 'BazClass');

        $this->assertInstanceOf('BazClass', $builder->get('baz_service'));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceMethodCalls()
    {
        $builder = new ContainerBuilder();
        $builder->register('bar', 'stdClass');
        $builder->register('foo1', 'FooClass')->addMethodCall('setBar', array(array('%value%', new Reference('bar'))));
        $builder->setParameter('value', 'bar');
        $this->assertEquals(array('bar', $builder->get('bar')), $builder->get('foo1')->bar, '->createService() replaces the values in the method calls arguments');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     */
    public function testCreateServiceConfigurator()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo1', 'FooClass')->setConfigurator('sc_configure');
        $this->assertTrue($builder->get('foo1')->configured, '->createService() calls the configurator');

        $builder->register('foo2', 'FooClass')->setConfigurator(array('%class%', 'configureStatic'));
        $builder->setParameter('class', 'BazClass');
        $this->assertTrue($builder->get('foo2')->configured, '->createService() calls the configurator');

        $builder->register('baz', 'BazClass');
        $builder->register('foo3', 'FooClass')->setConfigurator(array(new Reference('baz'), 'configure'));
        $this->assertTrue($builder->get('foo3')->configured, '->createService() calls the configurator');

        $builder->register('foo4', 'FooClass')->setConfigurator('foo');
        try {
            $builder->get('foo4');
            $this->fail('->createService() throws an InvalidArgumentException if the configure callable is not a valid callable');
        } catch (\InvalidArgumentException $e) {
            $this->assertEquals('The configure callable for class "FooClass" is not a callable.', $e->getMessage(), '->createService() throws an InvalidArgumentException if the configure callable is not a valid callable');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::createService
     * @expectedException \RuntimeException
     */
    public function testCreateSyntheticService()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'FooClass')->setSynthetic(true);
        $builder->get('foo');
    }

    public function testCreateServiceWithExpression()
    {
        $builder = new ContainerBuilder();
        $builder->setParameter('bar', 'bar');
        $builder->register('bar', 'BarClass');
        $builder->register('foo', 'FooClass')->addArgument(array('foo' => new Expression('service("bar").foo ~ parameter("bar")')));
        $this->assertEquals('foobar', $builder->get('foo')->arguments['foo']);
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::resolveServices
     */
    public function testResolveServices()
    {
        $builder = new ContainerBuilder();
        $builder->register('foo', 'FooClass');
        $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Reference('foo')), '->resolveServices() resolves service references to service instances');
        $this->assertEquals(array('foo' => array('foo', $builder->get('foo'))), $builder->resolveServices(array('foo' => array('foo', new Reference('foo')))), '->resolveServices() resolves service references to service instances in nested arrays');
        $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge
     */
    public function testMerge()
    {
        $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
        $container->setResourceTracking(false);
        $config = new ContainerBuilder(new ParameterBag(array('foo' => 'bar')));
        $container->merge($config);
        $this->assertEquals(array('bar' => 'foo', 'foo' => 'bar'), $container->getParameterBag()->all(), '->merge() merges current parameters with the loaded ones');

        $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
        $container->setResourceTracking(false);
        $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%')));
        $container->merge($config);
        $container->compile();
        $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');

        $container = new ContainerBuilder(new ParameterBag(array('bar' => 'foo')));
        $container->setResourceTracking(false);
        $config = new ContainerBuilder(new ParameterBag(array('foo' => '%bar%', 'baz' => '%foo%')));
        $container->merge($config);
        $container->compile();
        $this->assertEquals(array('bar' => 'foo', 'foo' => 'foo', 'baz' => 'foo'), $container->getParameterBag()->all(), '->merge() evaluates the values of the parameters towards already defined ones');

        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->register('foo', 'FooClass');
        $container->register('bar', 'BarClass');
        $config = new ContainerBuilder();
        $config->setDefinition('baz', new Definition('BazClass'));
        $config->setAlias('alias_for_foo', 'foo');
        $container->merge($config);
        $this->assertEquals(array('foo', 'bar', 'baz'), array_keys($container->getDefinitions()), '->merge() merges definitions already defined ones');

        $aliases = $container->getAliases();
        $this->assertTrue(isset($aliases['alias_for_foo']));
        $this->assertEquals('foo', (string) $aliases['alias_for_foo']);

        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->register('foo', 'FooClass');
        $config->setDefinition('foo', new Definition('BazClass'));
        $container->merge($config);
        $this->assertEquals('BazClass', $container->getDefinition('foo')->getClass(), '->merge() overrides already defined services');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::merge
     * @expectedException \LogicException
     */
    public function testMergeLogicException()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->compile();
        $container->merge(new ContainerBuilder());
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::findTaggedServiceIds
     */
    public function testfindTaggedServiceIds()
    {
        $builder = new ContainerBuilder();
        $builder
            ->register('foo', 'FooClass')
            ->addTag('foo', array('foo' => 'foo'))
            ->addTag('bar', array('bar' => 'bar'))
            ->addTag('foo', array('foofoo' => 'foofoo'))
        ;
        $this->assertEquals($builder->findTaggedServiceIds('foo'), array(
            'foo' => array(
                array('foo' => 'foo'),
                array('foofoo' => 'foofoo'),
            )
        ), '->findTaggedServiceIds() returns an array of service ids and its tag attributes');
        $this->assertEquals(array(), $builder->findTaggedServiceIds('foobar'), '->findTaggedServiceIds() returns an empty array if there is annotated services');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::findDefinition
     */
    public function testFindDefinition()
    {
        $container = new ContainerBuilder();
        $container->setDefinition('foo', $definition = new Definition('FooClass'));
        $container->setAlias('bar', 'foo');
        $container->setAlias('foobar', 'bar');
        $this->assertEquals($definition, $container->findDefinition('foobar'), '->findDefinition() returns a Definition');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addObjectResource
     */
    public function testAddObjectResource()
    {
        $container = new ContainerBuilder();

        $container->setResourceTracking(false);
        $container->addObjectResource(new \BarClass());

        $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');

        $container->setResourceTracking(true);
        $container->addObjectResource(new \BarClass());

        $resources = $container->getResources();

        $this->assertCount(1, $resources, '1 resource was registered');

        /* @var $resource \Symfony\Component\Config\Resource\FileResource */
        $resource = end($resources);

        $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource);
        $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource()));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addClassResource
     */
    public function testAddClassResource()
    {
        $container = new ContainerBuilder();

        $container->setResourceTracking(false);
        $container->addClassResource(new \ReflectionClass('BarClass'));

        $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');

        $container->setResourceTracking(true);
        $container->addClassResource(new \ReflectionClass('BarClass'));

        $resources = $container->getResources();

        $this->assertCount(1, $resources, '1 resource was registered');

        /* @var $resource \Symfony\Component\Config\Resource\FileResource */
        $resource = end($resources);

        $this->assertInstanceOf('Symfony\Component\Config\Resource\FileResource', $resource);
        $this->assertSame(realpath(__DIR__.'/Fixtures/includes/classes.php'), realpath($resource->getResource()));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::compile
     */
    public function testCompilesClassDefinitionsOfLazyServices()
    {
        $container = new ContainerBuilder();

        $this->assertEmpty($container->getResources(), 'No resources get registered without resource tracking');

        $container->register('foo', 'BarClass');
        $container->getDefinition('foo')->setLazy(true);

        $container->compile();

        $classesPath       = realpath(__DIR__.'/Fixtures/includes/classes.php');
        $matchingResources = array_filter(
            $container->getResources(),
            function (ResourceInterface $resource) use ($classesPath) {
                return $resource instanceof FileResource && $classesPath === realpath($resource->getResource());
            }
        );

        $this->assertNotEmpty($matchingResources);
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getResources
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::addResource
     */
    public function testResources()
    {
        $container = new ContainerBuilder();
        $container->addResource($a = new FileResource(__DIR__.'/Fixtures/xml/services1.xml'));
        $container->addResource($b = new FileResource(__DIR__.'/Fixtures/xml/services2.xml'));
        $resources = array();
        foreach ($container->getResources() as $resource) {
            if (false === strpos($resource, '.php')) {
                $resources[] = $resource;
            }
        }
        $this->assertEquals(array($a, $b), $resources, '->getResources() returns an array of resources read for the current configuration');
        $this->assertSame($container, $container->setResources(array()));
        $this->assertEquals(array(), $container->getResources());
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::registerExtension
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getExtension
     */
    public function testExtension()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);

        $container->registerExtension($extension = new \ProjectExtension());
        $this->assertTrue($container->getExtension('project') === $extension, '->registerExtension() registers an extension');

        $this->setExpectedException('LogicException');
        $container->getExtension('no_registered');
    }

    public function testRegisteredButNotLoadedExtension()
    {
        $extension = $this->getMock('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface');
        $extension->expects($this->once())->method('getAlias')->will($this->returnValue('project'));
        $extension->expects($this->never())->method('load');

        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->registerExtension($extension);
        $container->compile();
    }

    public function testRegisteredAndLoadedExtension()
    {
        $extension = $this->getMock('Symfony\\Component\\DependencyInjection\\Extension\\ExtensionInterface');
        $extension->expects($this->exactly(2))->method('getAlias')->will($this->returnValue('project'));
        $extension->expects($this->once())->method('load')->with(array(array('foo' => 'bar')));

        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->registerExtension($extension);
        $container->loadFromExtension('project', array('foo' => 'bar'));
        $container->compile();
    }

    public function testPrivateServiceUser()
    {
        $fooDefinition     = new Definition('BarClass');
        $fooUserDefinition = new Definition('BarUserClass', array(new Reference('bar')));
        $container         = new ContainerBuilder();
        $container->setResourceTracking(false);

        $fooDefinition->setPublic(false);

        $container->addDefinitions(array(
            'bar'       => $fooDefinition,
            'bar_user'  => $fooUserDefinition
        ));

        $container->compile();
        $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar);
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testThrowsExceptionWhenSetServiceOnAFrozenContainer()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->setDefinition('a', new Definition('stdClass'));
        $container->compile();
        $container->set('a', new \stdClass());
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testThrowsExceptionWhenAddServiceOnAFrozenContainer()
    {
        $container = new ContainerBuilder();
        $container->compile();
        $container->set('a', new \stdClass());
    }

    public function testNoExceptionWhenSetSyntheticServiceOnAFrozenContainer()
    {
        $container = new ContainerBuilder();
        $def = new Definition('stdClass');
        $def->setSynthetic(true);
        $container->setDefinition('a', $def);
        $container->compile();
        $container->set('a', $a = new \stdClass());
        $this->assertEquals($a, $container->get('a'));
    }

    public function testSetOnSynchronizedService()
    {
        $container = new ContainerBuilder();
        $container->register('baz', 'BazClass')
            ->setSynchronized(true)
        ;
        $container->register('bar', 'BarClass')
            ->addMethodCall('setBaz', array(new Reference('baz')))
        ;

        $container->set('baz', $baz = new \BazClass());
        $this->assertSame($baz, $container->get('bar')->getBaz());

        $container->set('baz', $baz = new \BazClass());
        $this->assertSame($baz, $container->get('bar')->getBaz());
    }

    public function testSynchronizedServiceWithScopes()
    {
        $container = new ContainerBuilder();
        $container->addScope(new Scope('foo'));
        $container->register('baz', 'BazClass')
            ->setSynthetic(true)
            ->setSynchronized(true)
            ->setScope('foo')
        ;
        $container->register('bar', 'BarClass')
            ->addMethodCall('setBaz', array(new Reference('baz', ContainerInterface::NULL_ON_INVALID_REFERENCE, false)))
        ;
        $container->compile();

        $container->enterScope('foo');
        $container->set('baz', $outerBaz = new \BazClass(), 'foo');
        $this->assertSame($outerBaz, $container->get('bar')->getBaz());

        $container->enterScope('foo');
        $container->set('baz', $innerBaz = new \BazClass(), 'foo');
        $this->assertSame($innerBaz, $container->get('bar')->getBaz());
        $container->leaveScope('foo');

        $this->assertNotSame($innerBaz, $container->get('bar')->getBaz());
        $this->assertSame($outerBaz, $container->get('bar')->getBaz());

        $container->leaveScope('foo');
    }

    /**
     * @expectedException \BadMethodCallException
     */
    public function testThrowsExceptionWhenSetDefinitionOnAFrozenContainer()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->compile();
        $container->setDefinition('a', new Definition());
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::getExtensionConfig
     * @covers Symfony\Component\DependencyInjection\ContainerBuilder::prependExtensionConfig
     */
    public function testExtensionConfig()
    {
        $container = new ContainerBuilder();

        $configs = $container->getExtensionConfig('foo');
        $this->assertEmpty($configs);

        $first = array('foo' => 'bar');
        $container->prependExtensionConfig('foo', $first);
        $configs = $container->getExtensionConfig('foo');
        $this->assertEquals(array($first), $configs);

        $second = array('ding' => 'dong');
        $container->prependExtensionConfig('foo', $second);
        $configs = $container->getExtensionConfig('foo');
        $this->assertEquals(array($second, $first), $configs);
    }

    public function testLazyLoadedService()
    {
        $loader = new ClosureLoader($container = new ContainerBuilder());
        $loader->load(function (ContainerBuilder $container) {
                $container->set('a', new \BazClass());
                $definition = new Definition('BazClass');
                $definition->setLazy(true);
                $container->setDefinition('a', $definition);
            }
        );

        $container->setResourceTracking(true);

        $container->compile();

        $class = new \BazClass();
        $reflectionClass = new \ReflectionClass($class);

        $r = new \ReflectionProperty($container, 'resources');
        $r->setAccessible(true);
        $resources = $r->getValue($container);

        $classInList = false;
        foreach ($resources as $resource) {
            if ($resource->getResource() === $reflectionClass->getFileName()) {
                $classInList = true;
                break;
            }
        }

        $this->assertTrue($classInList);
    }
}

class FooClass {}

class ProjectContainer extends ContainerBuilder
{
    public function getFoobazService()
    {
        throw new InactiveScopeException('foo', 'request');
    }
}
PKS1[�[��QDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\Parameter;

class ParameterTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Parameter::__construct
     */
    public function testConstructor()
    {
        $ref = new Parameter('foo');
        $this->assertEquals('foo', (string) $ref, '__construct() sets the id of the parameter, which is used for the __toString() method');
    }
}
PKS1[~O�99fDependencyInjection/Symfony/Component/DependencyInjection/Tests/LazyProxy/PhpDumper/NullDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\LazyProxy\PhpDumper;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;

/**
 * Tests for {@see \Symfony\Component\DependencyInjection\PhpDumper\NullDumper}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 *
 * @covers \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper
 */
class NullDumperTest extends \PHPUnit_Framework_TestCase
{
    public function testNullDumper()
    {
        $dumper     = new NullDumper();
        $definition = new Definition('stdClass');

        $this->assertFalse($dumper->isProxyCandidate($definition));
        $this->assertSame('', $dumper->getProxyFactoryCode($definition, 'foo'));
        $this->assertSame('', $dumper->getProxyCode($definition));
    }
}
PKS1[I8�i��vDependencyInjection/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\LazyProxy\Instantiator;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;

/**
 * Tests for {@see \Symfony\Component\DependencyInjection\Instantiator\RealServiceInstantiator}
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 *
 * @covers \Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator
 */
class RealServiceInstantiatorTest extends \PHPUnit_Framework_TestCase
{
    public function testInstantiateProxy()
    {
        $instantiator = new RealServiceInstantiator();
        $instance     = new \stdClass();
        $container    = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface');
        $callback     = function () use ($instance) {
            return $instance;
        };

        $this->assertSame($instance, $instantiator->instantiateProxy($container, new Definition(), 'foo', $callback));
    }
}
PKS1[���//WDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/simple.phpnu�[���<?php

$container->setParameter('foo', 'foo');
PKS1[G3G@��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->parameters = $this->getDefaultParameters();

        $this->services =
        $this->scopedServices =
        $this->scopeStacks = array();

        $this->set('service_container', $this);

        $this->scopes = array();
        $this->scopeChildren = array();
        $this->methodMap = array(
            'test' => 'getTestService',
        );

        $this->aliases = array();
    }

    /**
     * Gets the 'test' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return stdClass A stdClass instance.
     */
    protected function getTestService()
    {
        return $this->services['test'] = new \stdClass(array('only dot' => '.', 'concatenation as value' => '.\'\'.', 'concatenation from the start value' => '\'\'.', '.' => 'dot as a key', '.\'\'.' => 'concatenation as a key', '\'\'.' => 'concatenation from the start key', 'optimize concatenation' => 'string1-string2', 'optimize concatenation with empty string' => 'string1string2', 'optimize concatenation from the start' => 'start', 'optimize concatenation at the end' => 'end'));
    }

    /**
     * {@inheritdoc}
     */
    public function getParameter($name)
    {
        $name = strtolower($name);

        if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
            throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
        }

        return $this->parameters[$name];
    }

    /**
     * {@inheritdoc}
     */
    public function hasParameter($name)
    {
        $name = strtolower($name);

        return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function setParameter($name, $value)
    {
        throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
    }

    /**
     * {@inheritDoc}
     */
    public function getParameterBag()
    {
        if (null === $this->parameterBag) {
            $this->parameterBag = new FrozenParameterBag($this->parameters);
        }

        return $this->parameterBag;
    }
    /**
     * Gets the default parameters.
     *
     * @return array An array of the default parameters
     */
    protected function getDefaultParameters()
    {
        return array(
            'empty_value' => '',
            'some_string' => '-',
        );
    }
}
PKS1[E�))\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services1-1.phpnu�[���<?php
namespace Symfony\Component\DependencyInjection\Dump;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * Container
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class Container extends AbstractContainer
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }
}
PKS1[o�TbZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services1.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }
}
PKS1[,�j���ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct(new ParameterBag($this->getDefaultParameters()));
        $this->methodMap = array(
            'bar' => 'getBarService',
            'baz' => 'getBazService',
            'depends_on_request' => 'getDependsOnRequestService',
            'factory_service' => 'getFactoryServiceService',
            'foo' => 'getFooService',
            'foo.baz' => 'getFoo_BazService',
            'foo_bar' => 'getFooBarService',
            'foo_with_inline' => 'getFooWithInlineService',
            'inlined' => 'getInlinedService',
            'method_call1' => 'getMethodCall1Service',
            'request' => 'getRequestService',
        );
        $this->aliases = array(
            'alias_for_alias' => 'foo',
            'alias_for_foo' => 'foo',
        );
    }

    /**
     * Gets the 'bar' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getBarService()
    {
        $this->services['bar'] = $instance = new \FooClass('foo', $this->get('foo.baz'), $this->getParameter('foo_bar'));

        $this->get('foo.baz')->configure($instance);

        return $instance;
    }

    /**
     * Gets the 'baz' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Baz A Baz instance.
     */
    protected function getBazService()
    {
        $this->services['baz'] = $instance = new \Baz();

        $instance->setFoo($this->get('foo_with_inline'));

        return $instance;
    }

    /**
     * Gets the 'depends_on_request' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return stdClass A stdClass instance.
     */
    protected function getDependsOnRequestService()
    {
        $this->services['depends_on_request'] = $instance = new \stdClass();

        $instance->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE));

        return $instance;
    }

    /**
     * Gets the 'factory_service' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Bar A Bar instance.
     */
    protected function getFactoryServiceService()
    {
        return $this->services['factory_service'] = $this->get('foo.baz')->getInstance();
    }

    /**
     * Gets the 'foo' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getFooService()
    {
        $a = $this->get('foo.baz');

        $this->services['foo'] = $instance = call_user_func(array('FooClass', 'getInstance'), 'foo', $a, array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo')), true, $this);

        $instance->setBar($this->get('bar'));
        $instance->initialize();
        $instance->foo = 'bar';
        $instance->moo = $a;
        $instance->qux = array($this->getParameter('foo') => 'foo is '.$this->getParameter('foo').'', 'foobar' => $this->getParameter('foo'));
        sc_configure($instance);

        return $instance;
    }

    /**
     * Gets the 'foo.baz' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return object A %baz_class% instance.
     */
    protected function getFoo_BazService()
    {
        $this->services['foo.baz'] = $instance = call_user_func(array($this->getParameter('baz_class'), 'getInstance'));

        call_user_func(array($this->getParameter('baz_class'), 'configureStatic1'), $instance);

        return $instance;
    }

    /**
     * Gets the 'foo_bar' service.
     *
     * @return object A %foo_class% instance.
     */
    protected function getFooBarService()
    {
        $class = $this->getParameter('foo_class');

        return new $class();
    }

    /**
     * Gets the 'foo_with_inline' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Foo A Foo instance.
     */
    protected function getFooWithInlineService()
    {
        $this->services['foo_with_inline'] = $instance = new \Foo();

        $instance->setBar($this->get('inlined'));

        return $instance;
    }

    /**
     * Gets the 'method_call1' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getMethodCall1Service()
    {
        require_once '%path%foo.php';

        $this->services['method_call1'] = $instance = new \FooClass();

        $instance->setBar($this->get('foo'));
        $instance->setBar($this->get('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE));
        if ($this->has('foo3')) {
            $instance->setBar($this->get('foo3', ContainerInterface::NULL_ON_INVALID_REFERENCE));
        }
        if ($this->has('foobaz')) {
            $instance->setBar($this->get('foobaz', ContainerInterface::NULL_ON_INVALID_REFERENCE));
        }
        $instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo")));

        return $instance;
    }

    /**
     * Gets the 'request' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @throws RuntimeException always since this service is expected to be injected dynamically
     */
    protected function getRequestService()
    {
        throw new RuntimeException('You have requested a synthetic service ("request"). The DIC does not know how to construct this service.');
    }

    /**
     * Updates the 'request' service.
     */
    protected function synchronizeRequestService()
    {
        if ($this->initialized('depends_on_request')) {
            $this->get('depends_on_request')->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE));
        }
    }

    /**
     * Gets the 'inlined' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * This service is private.
     * If you want to be able to request this service from the container directly,
     * make it public, otherwise you might end up with broken code.
     *
     * @return Bar A Bar instance.
     */
    protected function getInlinedService()
    {
        $this->services['inlined'] = $instance = new \Bar();

        $instance->setBaz($this->get('baz'));
        $instance->pub = 'pub';

        return $instance;
    }

    /**
     * Gets the default parameters.
     *
     * @return array An array of the default parameters
     */
    protected function getDefaultParameters()
    {
        return array(
            'baz_class' => 'BazClass',
            'foo_class' => 'FooClass',
            'foo' => 'bar',
        );
    }
}
PKS1[$�oyy[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services11.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->services =
        $this->scopedServices =
        $this->scopeStacks = array();

        $this->set('service_container', $this);

        $this->scopes = array();
        $this->scopeChildren = array();
        $this->methodMap = array(
            'foo' => 'getFooService',
        );

        $this->aliases = array();
    }

    /**
     * Gets the 'foo' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return stdClass A stdClass instance.
     */
    protected function getFooService()
    {
        return $this->services['foo'] = new \stdClass();
    }
}
PKS1[��:A!!cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        $this->parameters = $this->getDefaultParameters();

        $this->services =
        $this->scopedServices =
        $this->scopeStacks = array();

        $this->set('service_container', $this);

        $this->scopes = array();
        $this->scopeChildren = array();
        $this->methodMap = array(
            'bar' => 'getBarService',
            'baz' => 'getBazService',
            'depends_on_request' => 'getDependsOnRequestService',
            'factory_service' => 'getFactoryServiceService',
            'foo' => 'getFooService',
            'foo.baz' => 'getFoo_BazService',
            'foo_bar' => 'getFooBarService',
            'foo_with_inline' => 'getFooWithInlineService',
            'method_call1' => 'getMethodCall1Service',
            'request' => 'getRequestService',
        );
        $this->aliases = array(
            'alias_for_alias' => 'foo',
            'alias_for_foo' => 'foo',
        );
    }

    /**
     * Gets the 'bar' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getBarService()
    {
        $this->services['bar'] = $instance = new \FooClass('foo', $this->get('foo.baz'), $this->getParameter('foo_bar'));

        $this->get('foo.baz')->configure($instance);

        return $instance;
    }

    /**
     * Gets the 'baz' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Baz A Baz instance.
     */
    protected function getBazService()
    {
        $this->services['baz'] = $instance = new \Baz();

        $instance->setFoo($this->get('foo_with_inline'));

        return $instance;
    }

    /**
     * Gets the 'depends_on_request' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return stdClass A stdClass instance.
     */
    protected function getDependsOnRequestService()
    {
        $this->services['depends_on_request'] = $instance = new \stdClass();

        $instance->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE));

        return $instance;
    }

    /**
     * Gets the 'factory_service' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Bar A Bar instance.
     */
    protected function getFactoryServiceService()
    {
        return $this->services['factory_service'] = $this->get('foo.baz')->getInstance();
    }

    /**
     * Gets the 'foo' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getFooService()
    {
        $a = $this->get('foo.baz');

        $this->services['foo'] = $instance = call_user_func(array('FooClass', 'getInstance'), 'foo', $a, array('bar' => 'foo is bar', 'foobar' => 'bar'), true, $this);

        $instance->setBar($this->get('bar'));
        $instance->initialize();
        $instance->foo = 'bar';
        $instance->moo = $a;
        $instance->qux = array('bar' => 'foo is bar', 'foobar' => 'bar');
        sc_configure($instance);

        return $instance;
    }

    /**
     * Gets the 'foo.baz' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return BazClass A BazClass instance.
     */
    protected function getFoo_BazService()
    {
        $this->services['foo.baz'] = $instance = call_user_func(array('BazClass', 'getInstance'));

        call_user_func(array('BazClass', 'configureStatic1'), $instance);

        return $instance;
    }

    /**
     * Gets the 'foo_bar' service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getFooBarService()
    {
        return new \FooClass();
    }

    /**
     * Gets the 'foo_with_inline' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return Foo A Foo instance.
     */
    protected function getFooWithInlineService()
    {
        $a = new \Bar();

        $this->services['foo_with_inline'] = $instance = new \Foo();

        $a->setBaz($this->get('baz'));
        $a->pub = 'pub';

        $instance->setBar($a);

        return $instance;
    }

    /**
     * Gets the 'method_call1' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @return FooClass A FooClass instance.
     */
    protected function getMethodCall1Service()
    {
        require_once '%path%foo.php';

        $this->services['method_call1'] = $instance = new \FooClass();

        $instance->setBar($this->get('foo'));
        $instance->setBar(NULL);
        $instance->setBar(($this->get("foo")->foo() . $this->getParameter("foo")));

        return $instance;
    }

    /**
     * Gets the 'request' service.
     *
     * This service is shared.
     * This method always returns the same instance of the service.
     *
     * @throws RuntimeException always since this service is expected to be injected dynamically
     */
    protected function getRequestService()
    {
        throw new RuntimeException('You have requested a synthetic service ("request"). The DIC does not know how to construct this service.');
    }

    /**
     * Updates the 'request' service.
     */
    protected function synchronizeRequestService()
    {
        if ($this->initialized('depends_on_request')) {
            $this->get('depends_on_request')->setRequest($this->get('request', ContainerInterface::NULL_ON_INVALID_REFERENCE));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getParameter($name)
    {
        $name = strtolower($name);

        if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
            throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
        }

        return $this->parameters[$name];
    }

    /**
     * {@inheritdoc}
     */
    public function hasParameter($name)
    {
        $name = strtolower($name);

        return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
    }

    /**
     * {@inheritdoc}
     */
    public function setParameter($name, $value)
    {
        throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
    }

    /**
     * {@inheritDoc}
     */
    public function getParameterBag()
    {
        if (null === $this->parameterBag) {
            $this->parameterBag = new FrozenParameterBag($this->parameters);
        }

        return $this->parameterBag;
    }
    /**
     * Gets the default parameters.
     *
     * @return array An array of the default parameters
     */
    protected function getDefaultParameters()
    {
        return array(
            'baz_class' => 'BazClass',
            'foo_class' => 'FooClass',
            'foo' => 'bar',
        );
    }
}
PKS1[��7/��ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services8.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * ProjectServiceContainer
 *
 * This class has been auto-generated
 * by the Symfony Dependency Injection Component.
 */
class ProjectServiceContainer extends Container
{
    /**
     * Constructor.
     */
    public function __construct()
    {
        parent::__construct(new ParameterBag($this->getDefaultParameters()));
    }

    /**
     * Gets the default parameters.
     *
     * @return array An array of the default parameters
     */
    protected function getDefaultParameters()
    {
        return array(
            'foo' => '%baz%',
            'baz' => 'bar',
            'bar' => 'foo is %%foo bar',
            'escape' => '@escapeme',
            'values' => array(
                0 => true,
                1 => false,
                2 => NULL,
                3 => 0,
                4 => 1000.3,
                5 => 'true',
                6 => 'false',
                7 => 'null',
            ),
        );
    }
}
PKS1[�(]

ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services1.xmlnu�[���<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"/>
PKS1[�ibĤ�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services5.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="foo" class="FooClass">
      <argument type="service">
        <service class="BarClass">
          <argument type="service">
            <service class="BazClass">
            </service>
          </argument>
        </service>
      </argument>
      <property name="p" type="service">
        <service class="BazClass" />
      </property>
    </service>
  </services>
</container>
PKS1[�![�[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services10.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="foo" class="BarClass">
        <tag name="foo_tag"
            some-option="cat"
            some_option="ciz"
            other-option="lorem"
            an_other-option="ipsum"
        />
    </service>
  </services>
</container>
PKS1[u�

ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services4.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <imports>
    <import resource="services2.xml" />
    <import resource="services3.xml" />
    <import resource="../ini/parameters.ini" />
    <import resource="../ini/parameters2.ini" />
    <import resource="../yaml/services13.yml" />
  </imports>
</container>
PKS1[�_�+WWZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services7.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="foo" class="BarClass" />
  </services>
</container>
PKS1[x'�	11\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/withdoctype.xmlnu�[���<?xml version="1.0"?>
<!DOCTYPE foo>
<foo></foo>
PKT1[�w�zhhZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services8.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <parameters>
    <parameter key="foo">%baz%</parameter>
    <parameter key="baz">bar</parameter>
    <parameter key="bar">foo is %%foo bar</parameter>
    <parameter key="escape">@escapeme</parameter>
    <parameter key="values" type="collection">
      <parameter>true</parameter>
      <parameter>false</parameter>
      <parameter>null</parameter>
      <parameter>0</parameter>
      <parameter>1000.3</parameter>
      <parameter type="string">true</parameter>
      <parameter type="string">false</parameter>
      <parameter type="string">null</parameter>
    </parameter>
  </parameters>
</container>
PKT1[���<ii[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services13.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <parameters>
    <parameter key="imported_from_xml">true</parameter>
  </parameters>
</container>
PKT1[p�Ԡ��ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services6.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="foo" class="FooClass" />
    <service id="baz" class="BazClass" />
    <service id="scope.container" class="FooClass" scope="container" />
    <service id="scope.custom" class="FooClass" scope="custom" />
    <service id="scope.prototype" class="FooClass" scope="prototype" />
    <service id="constructor" class="FooClass" factory-method="getInstance" />
    <service id="file" class="FooClass">
      <file>%path%/foo.php</file>
    </service>
    <service id="arguments" class="FooClass">
      <argument>foo</argument>
      <argument type="service" id="foo" />
      <argument type="collection">
        <argument>true</argument>
        <argument>false</argument>
      </argument>
    </service>
    <service id="configurator1" class="FooClass">
      <configurator function="sc_configure" />
    </service>
    <service id="configurator2" class="FooClass">
      <configurator service="baz" method="configure" />
    </service>
    <service id="configurator3" class="FooClass">
      <configurator class="BazClass" method="configureStatic" />
    </service>
    <service id="method_call1" class="FooClass">
      <call method="setBar" />
      <call method="setBar">
        <argument type="expression">service("foo").foo() ~ parameter("foo")</argument>
      </call>
    </service>
    <service id="method_call2" class="FooClass">
      <call method="setBar">
        <argument>foo</argument>
        <argument type="service" id="foo" />
        <argument type="collection">
          <argument>true</argument>
          <argument>false</argument>
        </argument>
      </call>
    </service>
    <service id="alias_for_foo" alias="foo" />
    <service id="another_alias_for_foo" alias="foo" public="false" />
    <service id="factory_service" factory-method="getInstance" factory-service="baz_factory" />
    <service id="request" class="Request" synthetic="true" synchronized="true" lazy="true"/>
  </services>
</container>
PKT1[˕n%%YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/nonvalid.xmlnu�[���<?xml version="1.0" ?>

<nonvalid />
PKT1[��PggeDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services4_bad_import.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <imports>
    <import resource="foo_fake.xml" ignore-errors="true" />
  </imports>
</container>
PKT1[\_���ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services3.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <parameters>
    <parameter key="foo">foo</parameter>
    <parameter key="values" type="collection">
      <parameter>true</parameter>
      <parameter>false</parameter>
    </parameter>
  </parameters>
</container>
PKT1[]2�
��dDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extension2/services.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="extension2.foo" class="FooClass2">
      <argument type="service">
        <service class="BarClass2">
        </service>
      </argument>
    </service>
  </services>
</container>
PKT1[	�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services2.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <parameters>
    <parameter>a string</parameter>
    <parameter key="FOO">bar</parameter>
    <parameter key="values" type="collection">
      <parameter>0</parameter>
      <parameter key="integer">4</parameter>
      <parameter key="100">null</parameter>
      <parameter type="string">true</parameter>
      <parameter>true</parameter>
      <parameter>false</parameter>
      <parameter>on</parameter>
      <parameter>off</parameter>
      <parameter key="float">1.3</parameter>
      <parameter>1000.3</parameter>
      <parameter>a string</parameter>
      <parameter type="collection">
        <parameter>foo</parameter>
        <parameter>bar</parameter>
      </parameter>
    </parameter>
    <parameter key="foo_bar" type="service" id="foo_bar" />
    <parameter key="MixedCase" type="collection"> <!-- Should be lower cased -->
      <parameter key="MixedCaseKey">value</parameter> <!-- Should stay mixed case -->
    </parameter>
    <parameter key="constant" type="constant">PHP_EOL</parameter>
  </parameters>
</container>
PKT1[������dDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extension1/services.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <services>
    <service id="extension1.foo" class="FooClass1">
      <argument type="service">
        <service class="BarClass1">
        </service>
      </argument>
    </service>
  </services>
</container>
PKT1[B�X�

ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xmlnu�[���<?xml version="1.0" encoding="utf-8"?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
  <parameters>
    <parameter key="baz_class">BazClass</parameter>
    <parameter key="foo_class">FooClass</parameter>
    <parameter key="foo">bar</parameter>
  </parameters>
  <services>
    <service id="foo" class="FooClass" factory-method="getInstance">
      <tag name="foo" foo="foo"/>
      <tag name="foo" bar="bar"/>
      <argument>foo</argument>
      <argument type="service" id="foo.baz"/>
      <argument type="collection">
        <argument key="%foo%">foo is %foo%</argument>
        <argument key="foobar">%foo%</argument>
      </argument>
      <argument>true</argument>
      <argument type="service" id="service_container"/>
      <property name="foo">bar</property>
      <property name="moo" type="service" id="foo.baz"/>
      <property name="qux" type="collection">
        <property key="%foo%">foo is %foo%</property>
        <property key="foobar">%foo%</property>
      </property>
      <call method="setBar">
        <argument type="service" id="bar"/>
      </call>
      <call method="initialize"/>
      <configurator function="sc_configure"/>
    </service>
    <service id="bar" class="FooClass">
      <argument>foo</argument>
      <argument type="service" id="foo.baz"/>
      <argument>%foo_bar%</argument>
      <configurator service="foo.baz" method="configure"/>
    </service>
    <service id="foo.baz" class="%baz_class%" factory-method="getInstance">
      <configurator class="%baz_class%" method="configureStatic1"/>
    </service>
    <service id="foo_bar" class="%foo_class%" scope="prototype"/>
    <service id="method_call1" class="FooClass">
      <file>%path%foo.php</file>
      <call method="setBar">
        <argument type="service" id="foo"/>
      </call>
      <call method="setBar">
        <argument type="service" id="foo2" on-invalid="null"/>
      </call>
      <call method="setBar">
        <argument type="service" id="foo3" on-invalid="ignore"/>
      </call>
      <call method="setBar">
        <argument type="service" id="foobaz" on-invalid="ignore"/>
      </call>
      <call method="setBar">
        <argument type="expression">service("foo").foo() ~ parameter("foo")</argument>
      </call>
    </service>
    <service id="factory_service" class="Bar" factory-method="getInstance" factory-service="foo.baz"/>
    <service id="foo_with_inline" class="Foo">
      <call method="setBar">
        <argument type="service" id="inlined"/>
      </call>
    </service>
    <service id="inlined" class="Bar" public="false">
      <property name="pub">pub</property>
      <call method="setBaz">
        <argument type="service" id="baz"/>
      </call>
    </service>
    <service id="baz" class="Baz">
      <call method="setFoo">
        <argument type="service" id="foo_with_inline"/>
      </call>
    </service>
    <service id="request" class="Request" synthetic="true" synchronized="true"/>
    <service id="depends_on_request" class="stdClass">
      <call method="setRequest">
        <argument type="service" id="request" on-invalid="null" strict="false"/>
      </call>
    </service>
    <service id="alias_for_foo" alias="foo"/>
    <service id="alias_for_alias" alias="foo"/>
  </services>
</container>
PKT1[�^����eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services1.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:project="http://www.example.com/schema/project">

    <parameters>
        <parameter key="project.parameter.foo">BAR</parameter>
    </parameters>

    <services>
        <service id="project.service.foo" class="BAR" />
    </services>

    <project:bar babar="babar">
        <another />
        <another2>%project.parameter.foo%</another2>
    </project:bar>

</container>
PKT1[����eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services5.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:project="http://www.example.com/schema/projectwithxsd"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://www.example.com/schema/projectwithxsd http://www.example.com/schema/projectwithxsd/project-1.0.xsd">

    <project:foobar />

</container>
PKT1[җ'y��eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services4.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:project="http://www.example.com/schema/not_registered_extension">
  <project:bar />
</container>
PKT1[��	eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services7.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:project="http://www.example.com/schema/projectwithxsdinphar"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://www.example.com/schema/projectwithxsdinphar http://www.example.com/schema/projectwithxsdinphar/project-1.0.xsd">

    <project:bar bar="foo" />

</container>
PKT1[ix�C��eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services6.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:project="http://www.example.com/schema/projectwithxsdinphar"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://www.example.com/schema/projectwithxsdinphar http://www.example.com/schema/projectwithxsdinphar/project-1.0.xsd">

    <project:bar />

</container>
PKT1[>U���eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services3.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:project="http://www.example.com/schema/projectwithxsd"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://www.example.com/schema/projectwithxsd http://www.example.com/schema/projectwithxsd/project-1.0.xsd">

    <parameters>
        <parameter key="project.parameter.foo">BAR</parameter>
    </parameters>

    <services>
        <service id="project.service.foo" class="BAR" />
    </services>

    <project:bar bar="bar" />

</container>
PKT1[�}��eDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services2.xmlnu�[���<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:project="http://www.example.com/schema/projectwithxsd"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd
                        http://www.example.com/schema/projectwithxsd http://www.example.com/schema/projectwithxsd/project-1.0.xsd">

    <parameters>
        <parameter key="project.parameter.foo">BAR</parameter>
    </parameters>

    <services>
        <service id="project.service.foo" class="BAR" />
    </services>

    <project:bar />

</container>
PKT1[��33`DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services10.dotnu�[���digraph sc {
  ratio="compress"
  node [fontsize="11" fontname="Arial" shape="record"];
  edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];

  node_foo [label="foo\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];
  node_bar [label="bar\n\n", shape=record, fillcolor="#ff9999", style="filled"];
  node_foo -> node_bar [label="" style="filled"];
}
PKT1[h	�	�	_DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dotnu�[���digraph sc {
  ratio="compress"
  node [fontsize="11" fontname="Arial" shape="record"];
  edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];

  node_foo [label="foo (alias_for_foo)\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_bar [label="bar\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_foo_baz [label="foo.baz\nBazClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_foo_bar [label="foo_bar\nFooClass\n", shape=record, fillcolor="#eeeeee", style="dotted"];
  node_method_call1 [label="method_call1\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_factory_service [label="factory_service\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_foo_with_inline [label="foo_with_inline\nFoo\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_inlined [label="inlined\nBar\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_baz [label="baz\nBaz\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_request [label="request\nRequest\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_depends_on_request [label="depends_on_request\nstdClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];
  node_foo2 [label="foo2\n\n", shape=record, fillcolor="#ff9999", style="filled"];
  node_foo3 [label="foo3\n\n", shape=record, fillcolor="#ff9999", style="filled"];
  node_foobaz [label="foobaz\n\n", shape=record, fillcolor="#ff9999", style="filled"];
  node_foo -> node_foo_baz [label="" style="filled"];
  node_foo -> node_service_container [label="" style="filled"];
  node_foo -> node_foo_baz [label="" style="dashed"];
  node_foo -> node_bar [label="setBar()" style="dashed"];
  node_bar -> node_foo_baz [label="" style="filled"];
  node_method_call1 -> node_foo [label="setBar()" style="dashed"];
  node_method_call1 -> node_foo2 [label="setBar()" style="dashed"];
  node_method_call1 -> node_foo3 [label="setBar()" style="dashed"];
  node_method_call1 -> node_foobaz [label="setBar()" style="dashed"];
  node_foo_with_inline -> node_inlined [label="setBar()" style="dashed"];
  node_inlined -> node_baz [label="setBaz()" style="dashed"];
  node_baz -> node_foo_with_inline [label="setFoo()" style="dashed"];
  node_depends_on_request -> node_request [label="setRequest()" style="dashed"];
}
PKT1[Ձ1*,,bDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services10-1.dotnu�[���digraph sc {
  ratio="normal"
  node [fontsize="13" fontname="Verdana" shape="square"];
  edge [fontsize="12" fontname="Verdana" color="white" arrowhead="closed" arrowsize="1"];

  node_foo [label="foo\nFooClass\n", shape=square, fillcolor="grey", style="filled"];
  node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=square, fillcolor="green", style="empty"];
  node_bar [label="bar\n\n", shape=square, fillcolor="red", style="empty"];
  node_foo -> node_bar [label="" style="filled"];
}
PKT1[&�WW_DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services1.dotnu�[���digraph sc {
  ratio="compress"
  node [fontsize="11" fontname="Arial" shape="record"];
  edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];

  node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];
}
PKT1[ŏD�;;`DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services13.dotnu�[���digraph sc {
  ratio="compress"
  node [fontsize="11" fontname="Arial" shape="record"];
  edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];

  node_foo [label="foo\nFooClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_bar [label="bar\nBarClass\n", shape=record, fillcolor="#eeeeee", style="filled"];
  node_service_container [label="service_container\nSymfony\\Component\\DependencyInjection\\ContainerBuilder\n", shape=record, fillcolor="#9999ff", style="filled"];
  node_foo -> node_bar [label="" style="filled"];
}
PKT1[��8BB`DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services14.dotnu�[���digraph sc {
  ratio="compress"
  node [fontsize="11" fontname="Arial" shape="record"];
  edge [fontsize="9" fontname="Arial" color="grey" arrowhead="open" arrowsize="0.5"];

  node_service_container [label="service_container\nContainer14\\ProjectServiceContainer\n", shape=record, fillcolor="#9999ff", style="filled"];
}
PKT1[�N�{rrtDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtensionInPhar.pharnu�[���<?php require_once "phar://ProjectWithXsdExtensionInPhar.phar/ProjectWithXsdExtensionInPhar.php"; __HALT_COMPILER(); ?>
�"ProjectWithXsdExtensionInPhar.phar!ProjectWithXsdExtensionInPhar.php~�akM~� ���schema/project-1.0.xsd��akM�Qp���<?php

class ProjectWithXsdExtensionInPhar extends ProjectExtension
{
    public function getXsdValidationBasePath()
    {
        return __DIR__.'/schema';
    }

    public function getNamespace()
    {
        return 'http://www.example.com/schema/projectwithxsdinphar';
    }

    public function getAlias()
    {
        return 'projectwithxsdinphar';
    }
}<?xml version="1.0" encoding="UTF-8" ?>

<xsd:schema xmlns="http://www.example.com/schema/projectwithxsdinphar"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.com/schema/projectwithxsdinphar"
    elementFormDefault="qualified">

  <xsd:element name="bar" type="bar" />

  <xsd:complexType name="bar">
    <xsd:attribute name="foo" type="xsd:string" />
  </xsd:complexType>
</xsd:schema>W��]ʯ�`�5,,)E��Y�GBMBPKT1[�
��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.phpnu�[���<?php

class FooClass
{
    public $foo, $moo;

    public $bar = null, $initialized = false, $configured = false, $called = false, $arguments = array();

    public function __construct($arguments = array())
    {
        $this->arguments = $arguments;
    }

    public static function getInstance($arguments = array())
    {
        $obj = new self($arguments);
        $obj->called = true;

        return $obj;
    }

    public function initialize()
    {
        $this->initialized = true;
    }

    public function configure()
    {
        $this->configured = true;
    }

    public function setBar($value = null)
    {
        $this->bar = $value;
    }
}
PKT1[��]���`DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/createphar.phpnu�[���<?php

$file = __DIR__.'/ProjectWithXsdExtensionInPhar.phar';
if (is_file($file)) {
    @unlink($file);
}

$phar = new Phar($file, 0, 'ProjectWithXsdExtensionInPhar.phar');
$phar->addFromString('ProjectWithXsdExtensionInPhar.php',<<<EOT
<?php

class ProjectWithXsdExtensionInPhar extends ProjectExtension
{
    public function getXsdValidationBasePath()
    {
        return __DIR__.'/schema';
    }

    public function getNamespace()
    {
        return 'http://www.example.com/schema/projectwithxsdinphar';
    }

    public function getAlias()
    {
        return 'projectwithxsdinphar';
    }
}
EOT
);
$phar->addFromString('schema/project-1.0.xsd', <<<EOT
<?xml version="1.0" encoding="UTF-8" ?>

<xsd:schema xmlns="http://www.example.com/schema/projectwithxsdinphar"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.com/schema/projectwithxsdinphar"
    elementFormDefault="qualified">

  <xsd:element name="bar" type="bar" />

  <xsd:complexType name="bar">
    <xsd:attribute name="foo" type="xsd:string" />
  </xsd:complexType>
</xsd:schema>
EOT
);
$phar->setStub('<?php require_once "phar://ProjectWithXsdExtensionInPhar.phar/ProjectWithXsdExtensionInPhar.php"; __HALT_COMPILER(); ?>');
PKT1[.Y<ҿ�fDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectExtension.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;

class ProjectExtension implements ExtensionInterface
{
    public function load(array $configs, ContainerBuilder $configuration)
    {
        $config = call_user_func_array('array_merge', $configs);

        $configuration->setDefinition('project.service.bar', new Definition('FooClass'));
        $configuration->setParameter('project.parameter.bar', isset($config['foo']) ? $config['foo'] : 'foobar');

        $configuration->setDefinition('project.service.foo', new Definition('FooClass'));
        $configuration->setParameter('project.parameter.foo', isset($config['foo']) ? $config['foo'] : 'foobar');

        return $configuration;
    }

    public function getXsdValidationBasePath()
    {
        return false;
    }

    public function getNamespace()
    {
        return 'http://www.example.com/schema/project';
    }

    public function getAlias()
    {
        return 'project';
    }

    public function getConfiguration(array $config, ContainerBuilder $container)
    {
        return null;
    }
}
PKT1[Aov:ZZ]DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/classes.phpnu�[���<?php

function sc_configure($instance)
{
    $instance->configure();
}

class BarClass
{
    protected $baz;
    public $foo = 'foo';

    public function setBaz(BazClass $baz)
    {
        $this->baz = $baz;
    }

    public function getBaz()
    {
        return $this->baz;
    }
}

class BazClass
{
    protected $foo;

    public function setFoo(Foo $foo)
    {
        $this->foo = $foo;
    }

    public function configure($instance)
    {
        $instance->configure();
    }

    public static function getInstance()
    {
        return new self();
    }

    public static function configureStatic($instance)
    {
        $instance->configure();
    }

    public static function configureStatic1()
    {
    }
}

class BarUserClass
{
    public $bar;

    public function __construct(BarClass $bar)
    {
        $this->bar = $bar;
    }
}
PKT1[RK:��hDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/schema/project-1.0.xsdnu�[���<?xml version="1.0" encoding="UTF-8" ?>

<xsd:schema xmlns="http://www.example.com/schema/projectwithxsd"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.com/schema/projectwithxsd"
    elementFormDefault="qualified">

  <xsd:element name="bar" type="bar" />

  <xsd:complexType name="bar">
    <xsd:attribute name="foo" type="xsd:string" />
  </xsd:complexType>
</xsd:schema>
PKT1[��[[mDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtension.phpnu�[���<?php

class ProjectWithXsdExtension extends ProjectExtension
{
    public function getXsdValidationBasePath()
    {
        return __DIR__.'/schema';
    }

    public function getNamespace()
    {
        return 'http://www.example.com/schema/projectwithxsd';
    }

    public function getAlias()
    {
        return 'projectwithxsd';
    }
}
PKT1[����[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services8.ymlnu�[���parameters:
    foo: '%baz%'
    baz: bar
    bar: 'foo is %%foo bar'
    escape: '@@escapeme'
    values: [true, false, null, 0, 1000.3, 'true', 'false', 'null']

PKT1[�|��DD[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services3.ymlnu�[���parameters:
    foo: foo
    values:
        - true
        - false
PKT1[6�e3��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services6.ymlnu�[���services:
    foo: { class: FooClass }
    baz: { class: BazClass }
    scope.container: { class: FooClass, scope: container }
    scope.custom: { class: FooClass, scope: custom }
    scope.prototype: { class: FooClass, scope: prototype }
    constructor: { class: FooClass, factory_method: getInstance }
    file: { class: FooClass, file: %path%/foo.php }
    arguments: { class: FooClass, arguments: [foo, @foo, [true, false]] }
    configurator1: { class: FooClass, configurator: sc_configure }
    configurator2: { class: FooClass, configurator: [@baz, configure] }
    configurator3: { class: FooClass, configurator: [BazClass, configureStatic] }
    method_call1:
        class: FooClass
        calls:
            - [ setBar, [] ]
            - [ setBar ]
            - [ setBar, ['@=service("foo").foo() ~ parameter("foo")'] ]
    method_call2:
        class: FooClass
        calls:
            - [ setBar, [ foo, @foo, [true, false] ] ]
    alias_for_foo: @foo
    another_alias_for_foo:
        alias: foo
        public: false
    factory_service: { class: BazClass, factory_method: getInstance, factory_service: baz_factory }
    request:
        class: Request
        synthetic: true
        synchronized: true
        lazy: true
PKT1[V�v�==[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services4.ymlnu�[���imports:
    - { resource: services2.yml }
    - { resource: services3.yml }
    - { resource: "../php/simple.php" }
    - { resource: "../ini/parameters.ini", class: Symfony\Component\DependencyInjection\Loader\IniFileLoader }
    - { resource: "../ini/parameters2.ini" }
    - { resource: "../xml/services13.xml" }
PKT1[#�&#[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/nonvalid1.ymlnu�[���foo:
  bar
PKT1[y��??fDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services4_bad_import.ymlnu�[���imports:
    - { resource: foo_fake.yml, ignore_errors: true }
PKT1[�*_6��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag3.ymlnu�[���services:
    foo_service:
        class:    FooClass
        tags:
          # tag-attribute is not a scalar
          - { name: foo, bar: { foo: foo, bar: bar } }
PKT1[zb��nnYDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag1.ymlnu�[���services:
    foo_service:
        class:    FooClass
        # tags is not an array
        tags:     string
PKT1[����''[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services7.ymlnu�[���services:
    foo: { class: BarClass }
PKT1[�%/���\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services10.ymlnu�[���parameters:
    project.parameter.foo: BAR

services:
    project.service.foo:
        class: BAR

project:
    test: %project.parameter.foo%
PKT1[��2[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services1.ymlnu�[���
PKT1[�MuA\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services11.ymlnu�[���foobarfoobar: {}
PKT1[}�>���YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag2.ymlnu�[���services:
    foo_service:
        class:    FooClass
        tags:
          # tag is missing the name key
          foo_tag:   { foo: bar }
PKU1[:�Ʋ��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services2.ymlnu�[���parameters:
    FOO: bar
    values:
        - true
        - false
        - 0
        - 1000.3
    bar: foo
    escape: @@escapeme
    foo_bar: @foo_bar
    MixedCase:
        MixedCaseKey: value
PKU1[W�%[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/nonvalid2.ymlnu�[���false
PKU1[|�w���[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.ymlnu�[���parameters:
    baz_class: BazClass
    foo_class: FooClass
    foo: bar

services:
    foo:
        class: FooClass
        tags:
            - { name: foo, foo: foo }
            - { name: foo, bar: bar }
        factory_class: FooClass
        factory_method: getInstance
        arguments: [foo, '@foo.baz', { '%foo%': 'foo is %foo%', foobar: '%foo%' }, true, '@service_container']
        properties: { foo: bar, moo: '@foo.baz', qux: { '%foo%': 'foo is %foo%', foobar: '%foo%' } }
        calls:
            - [setBar, ['@bar']]
            - [initialize, {  }]

        configurator: sc_configure
    bar:
        class: FooClass
        arguments: [foo, '@foo.baz', '%foo_bar%']
        configurator: ['@foo.baz', configure]
    foo.baz:
        class: %baz_class%
        factory_class: %baz_class%
        factory_method: getInstance
        configurator: ['%baz_class%', configureStatic1]
    foo_bar:
        class: %foo_class%
        scope: prototype
    method_call1:
        class: FooClass
        file: %path%foo.php
        calls:
            - [setBar, ['@foo']]
            - [setBar, ['@?foo2']]
            - [setBar, ['@?foo3']]
            - [setBar, ['@?foobaz']]
            - [setBar, ['@=service("foo").foo() ~ parameter("foo")']]

    factory_service:
        class: Bar
        factory_method: getInstance
        factory_service: foo.baz
    foo_with_inline:
        class: Foo
        calls:
            - [setBar, ['@inlined']]

    inlined:
        class: Bar
        public: false
        properties: { pub: pub }
        calls:
            - [setBaz, ['@baz']]

    baz:
        class: Baz
        calls:
            - [setFoo, ['@foo_with_inline']]

    request:
        class: Request
        synthetic: true
        synchronized: true
    depends_on_request:
        class: stdClass
        calls:
            - [setRequest, ['@?request']]

    alias_for_foo: @foo
    alias_for_alias: @foo
PKU1[����GG\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services13.ymlnu�[���# used to test imports in XML
parameters:
    imported_from_yaml: true
PKU1[۴)�++YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/nonvalid.ininu�[���{NOT AN INI FILE}
{JUST A PLAIN TEXT FILE}
PKU1[pu��((\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters2.ininu�[���[parameters]
  imported_from_ini = true
PKU1[s4��''[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters.ininu�[���[parameters]
  foo = bar
  bar = %foo%
PKU1[5l%%\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters1.ininu�[���[parameters]
  FOO = foo
  baz = baz
PKU1[�Fm��cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/interfaces2.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

$container = new ContainerBuilder();

$factoryDefinition = new Definition('BarClassFactory');
$container->setDefinition('barFactory', $factoryDefinition);

$definition = new Definition();
$definition->setFactoryService('barFactory');
$definition->setFactoryMethod('createBarClass');
$container->setDefinition('bar', $definition);

return $container;

class BarClass
{
    public $foo;

    public function setBar($foo)
    {
        $this->foo = $foo;
    }
}

class BarClassFactory
{
    public function createBarClass()
    {
        return new BarClass();
    }
}
PKU1[4h���bDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container8.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

$container = new ContainerBuilder(new ParameterBag(array(
    'FOO'    => '%baz%',
    'baz'    => 'bar',
    'bar'    => 'foo is %%foo bar',
    'escape' => '@escapeme',
    'values' => array(true, false, null, 0, 1000.3, 'true', 'false', 'null'),
)));

return $container;
PKU1[�	Z��bDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.phpnu�[���<?php

require_once __DIR__.'/../includes/classes.php';

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\ExpressionLanguage\Expression;

$container = new ContainerBuilder();
$container->
    register('foo', 'FooClass')->
    addTag('foo', array('foo' => 'foo'))->
    addTag('foo', array('bar' => 'bar'))->
    setFactoryClass('FooClass')->
    setFactoryMethod('getInstance')->
    setArguments(array('foo', new Reference('foo.baz'), array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%'), true, new Reference('service_container')))->
    setProperties(array('foo' => 'bar', 'moo' => new Reference('foo.baz'), 'qux' => array('%foo%' => 'foo is %foo%', 'foobar' => '%foo%')))->
    addMethodCall('setBar', array(new Reference('bar')))->
    addMethodCall('initialize')->
    setConfigurator('sc_configure')
;
$container->
    register('bar', 'FooClass')->
    setArguments(array('foo', new Reference('foo.baz'), new Parameter('foo_bar')))->
    setScope('container')->
    setConfigurator(array(new Reference('foo.baz'), 'configure'))
;
$container->
    register('foo.baz', '%baz_class%')->
    setFactoryClass('%baz_class%')->
    setFactoryMethod('getInstance')->
    setConfigurator(array('%baz_class%', 'configureStatic1'))
;
$container->
    register('foo_bar', '%foo_class%')->
    setScope('prototype')
;
$container->getParameterBag()->clear();
$container->getParameterBag()->add(array(
    'baz_class' => 'BazClass',
    'foo_class' => 'FooClass',
    'foo' => 'bar',
));
$container->setAlias('alias_for_foo', 'foo');
$container->setAlias('alias_for_alias', 'alias_for_foo');
$container->
    register('method_call1', 'FooClass')->
    setFile(realpath(__DIR__.'/../includes/foo.php'))->
    addMethodCall('setBar', array(new Reference('foo')))->
    addMethodCall('setBar', array(new Reference('foo2', ContainerInterface::NULL_ON_INVALID_REFERENCE)))->
    addMethodCall('setBar', array(new Reference('foo3', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
    addMethodCall('setBar', array(new Reference('foobaz', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))->
    addMethodCall('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))
;
$container->
    register('factory_service', 'Bar')->
    setFactoryService('foo.baz')->
    setFactoryMethod('getInstance')
;

$container
    ->register('foo_with_inline', 'Foo')
    ->addMethodCall('setBar', array(new Reference('inlined')))
;
$container
    ->register('inlined', 'Bar')
    ->setProperty('pub', 'pub')
    ->addMethodCall('setBaz', array(new Reference('baz')))
    ->setPublic(false)
;
$container
    ->register('baz', 'Baz')
    ->addMethodCall('setFoo', array(new Reference('foo_with_inline')))
;
$container
    ->register('request', 'Request')
    ->setSynthetic(true)
    ->setSynchronized(true)
;
$container
    ->register('depends_on_request', 'stdClass')
    ->addMethodCall('setRequest', array(new Reference('request', ContainerInterface::NULL_ON_INVALID_REFERENCE, false)))
;

return $container;
PKU1[���33cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container11.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

$container = new ContainerBuilder();
$container->
    register('foo', 'FooClass')->
    addArgument(new Definition('BarClass', array(new Definition('BazClass'))))
;

return $container;
PKU1[��|cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/interfaces1.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

$container = new ContainerBuilder();
$container->setParameter('cla', 'Fo');
$container->setParameter('ss', 'Class');

$definition = new Definition('%cla%o%ss%');
$container->setDefinition('foo', $definition);

return $container;

if (!class_exists('FooClass')) {
    class FooClass
    {
        public $bar;

        public function setBar($bar)
        {
            $this->bar = $bar;
        }
    }
}
PKU1[C�ݲ;;cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container10.phpnu�[���<?php

require_once __DIR__.'/../includes/classes.php';

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

$container = new ContainerBuilder();
$container->
    register('foo', 'FooClass')->
    addArgument(new Reference('bar'))
;

return $container;
PKU1[BreOOcDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container13.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

$container = new ContainerBuilder();
$container->
    register('foo', 'FooClass')->
    addArgument(new Reference('bar'))
;
$container->
    register('bar', 'BarClass')
;
$container->compile();

return $container;
PKU1[�*�EEcDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container12.phpnu�[���<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

$container = new ContainerBuilder();
$container->
    register('foo', 'FooClass\\Foo')->
    addArgument('foo<>&bar')->
    addTag('foo"bar\\bar', array('foo' => 'foo"barřž€'))
;

return $container;
PKU1[�1�v��cDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container14.phpnu�[���<?php

namespace Container14;

use Symfony\Component\DependencyInjection\ContainerBuilder;

class ProjectServiceContainer extends ContainerBuilder
{
}

return new ProjectServiceContainer();
PKU1[
�^��gDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\ParameterBag;

use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;

class FrozenParameterBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::__construct
     */
    public function testConstructor()
    {
        $parameters = array(
            'foo' => 'foo',
            'bar' => 'bar',
        );
        $bag = new FrozenParameterBag($parameters);
        $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::clear
     * @expectedException \LogicException
     */
    public function testClear()
    {
        $bag = new FrozenParameterBag(array());
        $bag->clear();
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::set
     * @expectedException \LogicException
     */
    public function testSet()
    {
        $bag = new FrozenParameterBag(array());
        $bag->set('foo', 'bar');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag::add
     * @expectedException \LogicException
     */
    public function testAdd()
    {
        $bag = new FrozenParameterBag(array());
        $bag->add(array());
    }
}
PKU1[$����9�9aDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterBag/ParameterBagTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\ParameterBag;

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

class ParameterBagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::__construct
     */
    public function testConstructor()
    {
        $bag = new ParameterBag($parameters = array(
            'foo' => 'foo',
            'bar' => 'bar',
        ));
        $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::clear
     */
    public function testClear()
    {
        $bag = new ParameterBag($parameters = array(
            'foo' => 'foo',
            'bar' => 'bar',
        ));
        $bag->clear();
        $this->assertEquals(array(), $bag->all(), '->clear() removes all parameters');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::remove
     */
    public function testRemove()
    {
        $bag = new ParameterBag(array(
            'foo' => 'foo',
            'bar' => 'bar',
        ));
        $bag->remove('foo');
        $this->assertEquals(array('bar' => 'bar'), $bag->all(), '->remove() removes a parameter');
        $bag->remove('BAR');
        $this->assertEquals(array(), $bag->all(), '->remove() converts key to lowercase before removing');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::get
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::set
     */
    public function testGetSet()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $bag->set('bar', 'foo');
        $this->assertEquals('foo', $bag->get('bar'), '->set() sets the value of a new parameter');

        $bag->set('foo', 'baz');
        $this->assertEquals('baz', $bag->get('foo'), '->set() overrides previously set parameter');

        $bag->set('Foo', 'baz1');
        $this->assertEquals('baz1', $bag->get('foo'), '->set() converts the key to lowercase');
        $this->assertEquals('baz1', $bag->get('FOO'), '->get() converts the key to lowercase');

        try {
            $bag->get('baba');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent parameter "baba".', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
        }
    }

    public function testGetThrowParameterNotFoundException()
    {
        $bag = new ParameterBag(array(
            'foo' => 'foo',
            'bar' => 'bar',
            'baz' => 'baz',
        ));

        try {
            $bag->get('foo1');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent parameter "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices');
        }

        try {
            $bag->get('bag');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent parameter "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices');
        }

        try {
            $bag->get('');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent parameter "".', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException with some advices');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::has
     */
    public function testHas()
    {
        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertTrue($bag->has('foo'), '->has() returns true if a parameter is defined');
        $this->assertTrue($bag->has('Foo'), '->has() converts the key to lowercase');
        $this->assertFalse($bag->has('bar'), '->has() returns false if a parameter is not defined');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolveValue
     */
    public function testResolveValue()
    {
        $bag = new ParameterBag(array());
        $this->assertEquals('foo', $bag->resolveValue('foo'), '->resolveValue() returns its argument unmodified if no placeholders are found');

        $bag = new ParameterBag(array('foo' => 'bar'));
        $this->assertEquals('I\'m a bar', $bag->resolveValue('I\'m a %foo%'), '->resolveValue() replaces placeholders by their values');
        $this->assertEquals(array('bar' => 'bar'), $bag->resolveValue(array('%foo%' => '%foo%')), '->resolveValue() replaces placeholders in keys and values of arrays');
        $this->assertEquals(array('bar' => array('bar' => array('bar' => 'bar'))), $bag->resolveValue(array('%foo%' => array('%foo%' => array('%foo%' => '%foo%')))), '->resolveValue() replaces placeholders in nested arrays');
        $this->assertEquals('I\'m a %%foo%%', $bag->resolveValue('I\'m a %%foo%%'), '->resolveValue() supports % escaping by doubling it');
        $this->assertEquals('I\'m a bar %%foo bar', $bag->resolveValue('I\'m a %foo% %%foo %foo%'), '->resolveValue() supports % escaping by doubling it');
        $this->assertEquals(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar'))), $bag->resolveValue(array('foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')))), '->resolveValue() supports % escaping by doubling it');

        $bag = new ParameterBag(array('foo' => true));
        $this->assertTrue($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings');
        $bag = new ParameterBag(array('foo' => null));
        $this->assertNull($bag->resolveValue('%foo%'), '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings');

        $bag = new ParameterBag(array('foo' => 'bar', 'baz' => '%%%foo% %foo%%% %%foo%% %%%foo%%%'));
        $this->assertEquals('%%bar bar%% %%foo%% %%bar%%', $bag->resolveValue('%baz%'), '->resolveValue() replaces params placed besides escaped %');

        $bag = new ParameterBag(array('baz' => '%%s?%%s'));
        $this->assertEquals('%%s?%%s', $bag->resolveValue('%baz%'), '->resolveValue() is not replacing greedily');

        $bag = new ParameterBag(array());
        try {
            $bag->resolveValue('%foobar%');
            $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existent parameter');
        } catch (ParameterNotFoundException $e) {
            $this->assertEquals('You have requested a non-existent parameter "foobar".', $e->getMessage(), '->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter');
        }

        try {
            $bag->resolveValue('foo %foobar% bar');
            $this->fail('->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter');
        } catch (ParameterNotFoundException $e) {
            $this->assertEquals('You have requested a non-existent parameter "foobar".', $e->getMessage(), '->resolveValue() throws a ParameterNotFoundException if a placeholder references a non-existent parameter');
        }

        $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => array()));
        try {
            $bag->resolveValue('%foo%');
            $this->fail('->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter');
        } catch (RuntimeException $e) {
            $this->assertEquals('A string value must be composed of strings and/or numbers, but found parameter "bar" of type array inside string value "a %bar%".', $e->getMessage(), '->resolveValue() throws a RuntimeException when a parameter embeds another non-string parameter');
        }

        $bag = new ParameterBag(array('foo' => '%bar%', 'bar' => '%foobar%', 'foobar' => '%foo%'));
        try {
            $bag->resolveValue('%foo%');
            $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference');
        } catch (ParameterCircularReferenceException $e) {
            $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference');
        }

        $bag = new ParameterBag(array('foo' => 'a %bar%', 'bar' => 'a %foobar%', 'foobar' => 'a %foo%'));
        try {
            $bag->resolveValue('%foo%');
            $this->fail('->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference');
        } catch (ParameterCircularReferenceException $e) {
            $this->assertEquals('Circular reference detected for parameter "foo" ("foo" > "bar" > "foobar" > "foo").', $e->getMessage(), '->resolveValue() throws a ParameterCircularReferenceException when a parameter has a circular reference');
        }

        $bag = new ParameterBag(array('host' => 'foo.bar', 'port' => 1337));
        $this->assertEquals('foo.bar:1337', $bag->resolveValue('%host%:%port%'));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve
     */
    public function testResolveIndicatesWhyAParameterIsNeeded()
    {
        $bag = new ParameterBag(array('foo' => '%bar%'));

        try {
            $bag->resolve();
        } catch (ParameterNotFoundException $e) {
            $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage());
        }

        $bag = new ParameterBag(array('foo' => '%bar%'));

        try {
            $bag->resolve();
        } catch (ParameterNotFoundException $e) {
            $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage());
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve
     */
    public function testResolveUnescapesValue()
    {
        $bag = new ParameterBag(array(
            'foo' => array('bar' => array('ding' => 'I\'m a bar %%foo %%bar')),
            'bar' => 'I\'m a %%foo%%',
        ));

        $bag->resolve();

        $this->assertEquals('I\'m a %foo%', $bag->get('bar'), '->resolveValue() supports % escaping by doubling it');
        $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %foo %bar')), $bag->get('foo'), '->resolveValue() supports % escaping by doubling it');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::escapeValue
     */
    public function testEscapeValue()
    {
        $bag = new ParameterBag();

        $bag->add(array(
            'foo' => $bag->escapeValue(array('bar' => array('ding' => 'I\'m a bar %foo %bar', 'zero' => null))),
            'bar' => $bag->escapeValue('I\'m a %foo%'),
        ));

        $this->assertEquals('I\'m a %%foo%%', $bag->get('bar'), '->escapeValue() escapes % by doubling it');
        $this->assertEquals(array('bar' => array('ding' => 'I\'m a bar %%foo %%bar', 'zero' => null)), $bag->get('foo'), '->escapeValue() escapes % by doubling it');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve
     * @dataProvider stringsWithSpacesProvider
     */
    public function testResolveStringWithSpacesReturnsString($expected, $test, $description)
    {
        $bag = new ParameterBag(array('foo' => 'bar'));

        try {
            $this->assertEquals($expected, $bag->resolveString($test), $description);
        } catch (ParameterNotFoundException $e) {
            $this->fail(sprintf('%s - "%s"', $description, $expected));
        }
    }

    public function stringsWithSpacesProvider()
    {
        return array(
            array('bar', '%foo%', 'Parameters must be wrapped by %.'),
            array('% foo %', '% foo %', 'Parameters should not have spaces.'),
            array('{% set my_template = "foo" %}', '{% set my_template = "foo" %}', 'Twig-like strings are not parameters.'),
            array('50% is less than 100%', '50% is less than 100%', 'Text between % signs is allowed, if there are spaces.'),
        );
    }
}
PKU1[��
�
RDependencyInjection/Symfony/Component/DependencyInjection/Tests/CrossCheckTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;

class CrossCheckTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = __DIR__.'/Fixtures/';

        require_once self::$fixturesPath.'/includes/classes.php';
        require_once self::$fixturesPath.'/includes/foo.php';
    }

    /**
     * @dataProvider crossCheckLoadersDumpers
     */
    public function testCrossCheck($fixture, $type)
    {
        $loaderClass = 'Symfony\\Component\\DependencyInjection\\Loader\\'.ucfirst($type).'FileLoader';
        $dumperClass = 'Symfony\\Component\\DependencyInjection\\Dumper\\'.ucfirst($type).'Dumper';

        $tmp = tempnam('sf_service_container', 'sf');

        file_put_contents($tmp, file_get_contents(self::$fixturesPath.'/'.$type.'/'.$fixture));

        $container1 = new ContainerBuilder();
        $loader1 = new $loaderClass($container1, new FileLocator());
        $loader1->load($tmp);

        $dumper = new $dumperClass($container1);
        file_put_contents($tmp, $dumper->dump());

        $container2 = new ContainerBuilder();
        $loader2 = new $loaderClass($container2, new FileLocator());
        $loader2->load($tmp);

        unlink($tmp);

        $this->assertEquals($container2->getAliases(), $container1->getAliases(), 'loading a dump from a previously loaded container returns the same container');
        $this->assertEquals($container2->getDefinitions(), $container1->getDefinitions(), 'loading a dump from a previously loaded container returns the same container');
        $this->assertEquals($container2->getParameterBag()->all(), $container1->getParameterBag()->all(), '->getParameterBag() returns the same value for both containers');

        $this->assertEquals(serialize($container2), serialize($container1), 'loading a dump from a previously loaded container returns the same container');

        $services1 = array();
        foreach ($container1 as $id => $service) {
            $services1[$id] = serialize($service);
        }
        $services2 = array();
        foreach ($container2 as $id => $service) {
            $services2[$id] = serialize($service);
        }

        unset($services1['service_container'], $services2['service_container']);

        $this->assertEquals($services2, $services1, 'Iterator on the containers returns the same services');
    }

    public function crossCheckLoadersDumpers()
    {
        $tests = array(
            array('services1.xml', 'xml'),
            array('services2.xml', 'xml'),
            array('services6.xml', 'xml'),
            array('services8.xml', 'xml'),
            array('services9.xml', 'xml'),
        );

        if (class_exists('Symfony\Component\Yaml\Yaml')) {
            $tests = array_merge($tests, array(
                array('services1.yml', 'yaml'),
                array('services2.yml', 'yaml'),
                array('services6.yml', 'yaml'),
                array('services8.yml', 'yaml'),
                array('services9.yml', 'yaml'),
            ));
        }

        return $tests;
    }
}
PKU1[2+`��	�	YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/YamlDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Dumper;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\YamlDumper;

class YamlDumperTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    public function testDump()
    {
        $dumper = new YamlDumper($container = new ContainerBuilder());

        $this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services1.yml', $dumper->dump(), '->dump() dumps an empty container as an empty YAML file');

        $container = new ContainerBuilder();
        $dumper = new YamlDumper($container);
    }

    public function testAddParameters()
    {
        $container = include self::$fixturesPath.'/containers/container8.php';
        $dumper = new YamlDumper($container);
        $this->assertStringEqualsFile(self::$fixturesPath.'/yaml/services8.yml', $dumper->dump(), '->dump() dumps parameters');
    }

    public function testAddService()
    {
        $container = include self::$fixturesPath.'/containers/container9.php';
        $dumper = new YamlDumper($container);
        $this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/yaml/services9.yml')), $dumper->dump(), '->dump() dumps services');

        $dumper = new YamlDumper($container = new ContainerBuilder());
        $container->register('foo', 'FooClass')->addArgument(new \stdClass());
        try {
            $dumper->dump();
            $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
            $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        }
    }
}
PKU1[v��]DependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/GraphvizDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Dumper;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\GraphvizDumper;

class GraphvizDumperTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = __DIR__.'/../Fixtures/';
    }

    public function testDump()
    {
        $dumper = new GraphvizDumper($container = new ContainerBuilder());

        $this->assertStringEqualsFile(self::$fixturesPath.'/graphviz/services1.dot', $dumper->dump(), '->dump() dumps an empty container as an empty dot file');

        $container = include self::$fixturesPath.'/containers/container9.php';
        $dumper = new GraphvizDumper($container);
        $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services9.dot')), $dumper->dump(), '->dump() dumps services');

        $container = include self::$fixturesPath.'/containers/container10.php';
        $dumper = new GraphvizDumper($container);
        $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10.dot')), $dumper->dump(), '->dump() dumps services');

        $container = include self::$fixturesPath.'/containers/container10.php';
        $dumper = new GraphvizDumper($container);
        $this->assertEquals($dumper->dump(array(
            'graph' => array('ratio' => 'normal'),
            'node'  => array('fontsize' => 13, 'fontname' => 'Verdana', 'shape' => 'square'),
            'edge'  => array('fontsize' => 12, 'fontname' => 'Verdana', 'color' => 'white', 'arrowhead' => 'closed', 'arrowsize' => 1),
            'node.instance' => array('fillcolor' => 'green', 'style' => 'empty'),
            'node.definition' => array('fillcolor' => 'grey'),
            'node.missing' => array('fillcolor' => 'red', 'style' => 'empty'),
        )), str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services10-1.dot')), '->dump() dumps services');
    }

    public function testDumpWithFrozenContainer()
    {
        $container = include self::$fixturesPath.'/containers/container13.php';
        $dumper = new GraphvizDumper($container);
        $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services13.dot')), $dumper->dump(), '->dump() dumps services');
    }

    public function testDumpWithFrozenCustomClassContainer()
    {
        $container = include self::$fixturesPath.'/containers/container14.php';
        $dumper = new GraphvizDumper($container);
        $this->assertEquals(str_replace('%path%', __DIR__, file_get_contents(self::$fixturesPath.'/graphviz/services14.dot')), $dumper->dump(), '->dump() dumps services');
    }
}
PKU1[�)���XDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/XmlDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Dumper;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\XmlDumper;

class XmlDumperTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    public function testDump()
    {
        $dumper = new XmlDumper($container = new ContainerBuilder());

        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services1.xml', $dumper->dump(), '->dump() dumps an empty container as an empty XML file');

        $container = new ContainerBuilder();
        $dumper = new XmlDumper($container);
    }

    public function testExportParameters()
    {
        $container = include self::$fixturesPath.'//containers/container8.php';
        $dumper = new XmlDumper($container);
        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services8.xml', $dumper->dump(), '->dump() dumps parameters');
    }

    public function testAddParameters()
    {
        $container = include self::$fixturesPath.'//containers/container8.php';
        $dumper = new XmlDumper($container);
        $this->assertXmlStringEqualsXmlFile(self::$fixturesPath.'/xml/services8.xml', $dumper->dump(), '->dump() dumps parameters');
    }

    public function testAddService()
    {
        $container = include self::$fixturesPath.'/containers/container9.php';
        $dumper = new XmlDumper($container);
        $this->assertEquals(str_replace('%path%', self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR, file_get_contents(self::$fixturesPath.'/xml/services9.xml')), $dumper->dump(), '->dump() dumps services');

        $dumper = new XmlDumper($container = new ContainerBuilder());
        $container->register('foo', 'FooClass')->addArgument(new \stdClass());
        try {
            $dumper->dump();
            $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
            $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        }
    }

    public function testDumpAnonymousServices()
    {
        include self::$fixturesPath.'/containers/container11.php';
        $dumper = new XmlDumper($container);
        $this->assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\"?>
<container xmlns=\"http://symfony.com/schema/dic/services\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd\">
  <services>
    <service id=\"foo\" class=\"FooClass\">
      <argument type=\"service\">
        <service class=\"BarClass\">
          <argument type=\"service\">
            <service class=\"BazClass\"/>
          </argument>
        </service>
      </argument>
    </service>
  </services>
</container>
", $dumper->dump());
    }

    public function testDumpEntities()
    {
        include self::$fixturesPath.'/containers/container12.php';
        $dumper = new XmlDumper($container);
        $this->assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\"?>
<container xmlns=\"http://symfony.com/schema/dic/services\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd\">
  <services>
    <service id=\"foo\" class=\"FooClass\Foo\">
      <tag name=\"foo&quot;bar\bar\" foo=\"foo&quot;barřž€\"/>
      <argument>foo&lt;&gt;&amp;bar</argument>
    </service>
  </services>
</container>
", $dumper->dump());
    }
}
PKU1[�"��."."XDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Dumper;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;

class PhpDumperTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    public function testDump()
    {
        $dumper = new PhpDumper($container = new ContainerBuilder());

        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services1-1.php', $dumper->dump(array('class' => 'Container', 'base_class' => 'AbstractContainer', 'namespace' => 'Symfony\Component\DependencyInjection\Dump')), '->dump() takes a class and a base_class options');

        $container = new ContainerBuilder();
        new PhpDumper($container);
    }

    public function testDumpFrozenContainerWithNoParameter()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->register('foo', 'stdClass');

        $container->compile();

        $dumper = new PhpDumper($container);

        $dumpedString = $dumper->dump();
        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services11.php', $dumpedString, '->dump() does not add getDefaultParameters() method call if container have no parameters.');
        $this->assertNotRegexp("/function getDefaultParameters\(/", $dumpedString, '->dump() does not add getDefaultParameters() method definition.');
    }

    public function testDumpOptimizationString()
    {
        $definition = new Definition();
        $definition->setClass('stdClass');
        $definition->addArgument(array(
            'only dot' => '.',
            'concatenation as value' => '.\'\'.',
            'concatenation from the start value' => '\'\'.',
            '.' => 'dot as a key',
            '.\'\'.' => 'concatenation as a key',
            '\'\'.' =>'concatenation from the start key',
            'optimize concatenation' => "string1%some_string%string2",
            'optimize concatenation with empty string' => "string1%empty_value%string2",
            'optimize concatenation from the start' => '%empty_value%start',
            'optimize concatenation at the end' => 'end%empty_value%',
        ));

        $container = new ContainerBuilder();
        $container->setResourceTracking(false);
        $container->setDefinition('test', $definition);
        $container->setParameter('empty_value', '');
        $container->setParameter('some_string', '-');
        $container->compile();

        $dumper = new PhpDumper($container);
        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services10.php', $dumper->dump(), '->dump() dumps an empty container as an empty PHP class');
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testExportParameters()
    {
        $dumper = new PhpDumper(new ContainerBuilder(new ParameterBag(array('foo' => new Reference('foo')))));
        $dumper->dump();
    }

    public function testAddParameters()
    {
        $container = include self::$fixturesPath.'/containers/container8.php';
        $dumper = new PhpDumper($container);
        $this->assertStringEqualsFile(self::$fixturesPath.'/php/services8.php', $dumper->dump(), '->dump() dumps parameters');
    }

    public function testAddService()
    {
        // without compilation
        $container = include self::$fixturesPath.'/containers/container9.php';
        $dumper = new PhpDumper($container);
        $this->assertEquals(str_replace('%path%', str_replace('\\','\\\\',self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9.php')), $dumper->dump(), '->dump() dumps services');

        // with compilation
        $container = include self::$fixturesPath.'/containers/container9.php';
        $container->compile();
        $dumper = new PhpDumper($container);
        $this->assertEquals(str_replace('%path%', str_replace('\\','\\\\',self::$fixturesPath.DIRECTORY_SEPARATOR.'includes'.DIRECTORY_SEPARATOR), file_get_contents(self::$fixturesPath.'/php/services9_compiled.php')), $dumper->dump(), '->dump() dumps services');

        $dumper = new PhpDumper($container = new ContainerBuilder());
        $container->register('foo', 'FooClass')->addArgument(new \stdClass());
        try {
            $dumper->dump();
            $this->fail('->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\RuntimeException', $e, '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
            $this->assertEquals('Unable to dump a service container if a parameter is an object or a resource.', $e->getMessage(), '->dump() throws a RuntimeException if the container to be dumped has reference to objects or resources');
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     * @expectedExceptionMessage Service id "bar$" cannot be converted to a valid PHP method name.
     */
    public function testAddServiceInvalidServiceId()
    {
        $container = new ContainerBuilder();
        $container->register('bar$', 'FooClass');
        $dumper = new PhpDumper($container);
        $dumper->dump();
    }

    public function testAliases()
    {
        $container = include self::$fixturesPath.'/containers/container9.php';
        $container->compile();
        $dumper = new PhpDumper($container);
        eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Aliases')));

        $container = new \Symfony_DI_PhpDumper_Test_Aliases();
        $container->set('foo', $foo = new \stdClass);
        $this->assertSame($foo, $container->get('foo'));
        $this->assertSame($foo, $container->get('alias_for_foo'));
        $this->assertSame($foo, $container->get('alias_for_alias'));
    }

    public function testFrozenContainerWithoutAliases()
    {
        $container = new ContainerBuilder();
        $container->compile();

        $dumper = new PhpDumper($container);
        eval('?>'.$dumper->dump(array('class' => 'Symfony_DI_PhpDumper_Test_Frozen_No_Aliases')));

        $container = new \Symfony_DI_PhpDumper_Test_Frozen_No_Aliases();
        $this->assertFalse($container->has('foo'));
    }

    public function testOverrideServiceWhenUsingADumpedContainer()
    {
        require_once self::$fixturesPath.'/php/services9.php';
        require_once self::$fixturesPath.'/includes/foo.php';

        $container = new \ProjectServiceContainer();
        $container->set('bar', $bar = new \stdClass());
        $container->setParameter('foo_bar', 'foo_bar');

        $this->assertEquals($bar, $container->get('bar'), '->set() overrides an already defined service');
    }

    public function testOverrideServiceWhenUsingADumpedContainerAndServiceIsUsedFromAnotherOne()
    {
        require_once self::$fixturesPath.'/php/services9.php';
        require_once self::$fixturesPath.'/includes/foo.php';
        require_once self::$fixturesPath.'/includes/classes.php';

        $container = new \ProjectServiceContainer();
        $container->set('bar', $bar = new \stdClass());

        $this->assertSame($bar, $container->get('foo')->bar, '->set() overrides an already defined service');
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
     */
    public function testCircularReference()
    {
        $container = new ContainerBuilder();
        $container->register('foo', 'stdClass')->addArgument(new Reference('bar'));
        $container->register('bar', 'stdClass')->setPublic(false)->addMethodCall('setA', array(new Reference('baz')));
        $container->register('baz', 'stdClass')->addMethodCall('setA', array(new Reference('foo')));
        $container->compile();

        $dumper = new PhpDumper($container);
        $dumper->dump();
    }
}
PKU1[����QDependencyInjection/Symfony/Component/DependencyInjection/Tests/ReferenceTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\Reference;

class ReferenceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Reference::__construct
     */
    public function testConstructor()
    {
        $ref = new Reference('foo');
        $this->assertEquals('foo', (string) $ref, '__construct() sets the id of the reference, which is used for the __toString() method');
    }

    public function testCaseInsensitive()
    {
        $ref = new Reference('FooBar');
        $this->assertEquals('foobar', (string) $ref, 'the id is lowercased as the container is case insensitive');
    }
}
PKU1[ł``\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/ClosureLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Loader;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;

class ClosureLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::supports
     */
    public function testSupports()
    {
        $loader = new ClosureLoader(new ContainerBuilder());

        $this->assertTrue($loader->supports(function ($container) {}), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\ClosureLoader::load
     */
    public function testLoad()
    {
        $loader = new ClosureLoader($container = new ContainerBuilder());

        $loader->load(function ($container) {
            $container->setParameter('foo', 'foo');
        });

        $this->assertEquals('foo', $container->getParameter('foo'), '->load() loads a \Closure resource');
    }
}
PKU1[SR���\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Loader;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\Config\FileLocator;

class PhpFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::supports
     */
    public function testSupports()
    {
        $loader = new PhpFileLoader(new ContainerBuilder(), new FileLocator());

        $this->assertTrue($loader->supports('foo.php'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\PhpFileLoader::load
     */
    public function testLoad()
    {
        $loader = new PhpFileLoader($container = new ContainerBuilder(), new FileLocator());

        $loader->load(__DIR__.'/../Fixtures/php/simple.php');

        $this->assertEquals('foo', $container->getParameter('foo'), '->load() loads a PHP file resource');
    }
}
PKU1[�kV�0�0]DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Loader;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;

class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
        require_once self::$fixturesPath.'/includes/foo.php';
        require_once self::$fixturesPath.'/includes/ProjectExtension.php';
    }

    public function testLoadFile()
    {
        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
        $r = new \ReflectionObject($loader);
        $m = $r->getMethod('loadFile');
        $m->setAccessible(true);

        try {
            $m->invoke($loader, 'foo.yml');
            $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
            $this->assertEquals('The service file "foo.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
        }

        try {
            $m->invoke($loader, 'parameters.ini');
            $this->fail('->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file');
            $this->assertEquals('The service file "parameters.ini" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file is not a valid YAML file');
        }

        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));

        foreach (array('nonvalid1', 'nonvalid2') as $fixture) {
            try {
                $m->invoke($loader, $fixture.'.yml');
                $this->fail('->load() throws an InvalidArgumentException if the loaded file does not validate');
            } catch (\Exception $e) {
                $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not validate');
                $this->assertStringMatchesFormat('The service file "nonvalid%d.yml" is not valid.', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not validate');
            }
        }
    }

    public function testLoadParameters()
    {
        $container = new ContainerBuilder();
        $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
        $loader->load('services2.yml');
        $this->assertEquals(array('foo' => 'bar', 'mixedcase' => array('MixedCaseKey' => 'value'), 'values' => array(true, false, 0, 1000.3), 'bar' => 'foo', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar')), $container->getParameterBag()->all(), '->load() converts YAML keys to lowercase');
    }

    public function testLoadImports()
    {
        $container = new ContainerBuilder();
        $resolver = new LoaderResolver(array(
            new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')),
            new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')),
            new PhpFileLoader($container, new FileLocator(self::$fixturesPath.'/php')),
            $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')),
        ));
        $loader->setResolver($resolver);
        $loader->load('services4.yml');

        $actual = $container->getParameterBag()->all();
        $expected = array('foo' => 'bar', 'values' => array(true, false), 'bar' => '%foo%', 'escape' => '@escapeme', 'foo_bar' => new Reference('foo_bar'), 'mixedcase' => array('MixedCaseKey' => 'value'), 'imported_from_ini' => true, 'imported_from_xml' => true);
        $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');

        // Bad import throws no exception due to ignore_errors value.
        $loader->load('services4_bad_import.yml');
    }

    public function testLoadServices()
    {
        $container = new ContainerBuilder();
        $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
        $loader->load('services6.yml');
        $services = $container->getDefinitions();
        $this->assertTrue(isset($services['foo']), '->load() parses service elements');
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts service element to Definition instances');
        $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
        $this->assertEquals('container', $services['scope.container']->getScope());
        $this->assertEquals('custom', $services['scope.custom']->getScope());
        $this->assertEquals('prototype', $services['scope.prototype']->getScope());
        $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory_method attribute');
        $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
        $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
        $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array(new Reference('baz'), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array(array('setBar', array()), array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());

        $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag');
        $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag');
        $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag');

        $aliases = $container->getAliases();
        $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses aliases');
        $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
        $this->assertTrue($aliases['alias_for_foo']->isPublic());
        $this->assertTrue(isset($aliases['another_alias_for_foo']));
        $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
        $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
    }

    public function testExtensions()
    {
        $container = new ContainerBuilder();
        $container->registerExtension(new \ProjectExtension());
        $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml'));
        $loader->load('services10.yml');
        $container->compile();
        $services = $container->getDefinitions();
        $parameters = $container->getParameterBag()->all();

        $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
        $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements');

        $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
        $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');

        try {
            $loader->load('services11.yml');
            $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
            $this->assertStringStartsWith('There is no extension able to load the configuration for "foobarfoobar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\YamlFileLoader::supports
     */
    public function testSupports()
    {
        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator());

        $this->assertTrue($loader->supports('foo.yml'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }

    public function testNonArrayTagThrowsException()
    {
        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
        try {
            $loader->load('badtag1.yml');
            $this->fail('->load() should throw an exception when the tags key of a service is not an array');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tags key is not an array');
            $this->assertStringStartsWith('Parameter "tags" must be an array for service', $e->getMessage(), '->load() throws an InvalidArgumentException if the tags key is not an array');
        }
    }

    public function testTagWithoutNameThrowsException()
    {
        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
        try {
            $loader->load('badtag2.yml');
            $this->fail('->load() should throw an exception when a tag is missing the name key');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag is missing the name key');
            $this->assertStringStartsWith('A "tags" entry is missing a "name" key for service ', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag is missing the name key');
        }
    }

    public function testTagWithAttributeArrayThrowsException()
    {
        $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml'));
        try {
            $loader->load('badtag3.yml');
            $this->fail('->load() should throw an exception when a tag-attribute is not a scalar');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
            $this->assertStringStartsWith('A "tags" attribute must be of a scalar-type for service "foo_service", tag "foo", attribute "bar"', $e->getMessage(), '->load() throws an InvalidArgumentException if a tag-attribute is not a scalar');
        }
    }
}
PKU1[Q&I�8a8a\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Loader;

use Symfony\Component\DependencyInjection\ContainerInterface;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\Config\Loader\LoaderResolver;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\ExpressionLanguage\Expression;

class XmlFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
        require_once self::$fixturesPath.'/includes/foo.php';
        require_once self::$fixturesPath.'/includes/ProjectExtension.php';
        require_once self::$fixturesPath.'/includes/ProjectWithXsdExtension.php';
    }

    public function testLoad()
    {
        $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));

        try {
            $loader->load('foo.xml');
            $this->fail('->load() throws an InvalidArgumentException if the loaded file does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the loaded file does not exist');
            $this->assertStringStartsWith('The file "foo.xml" does not exist (in:', $e->getMessage(), '->load() throws an InvalidArgumentException if the loaded file does not exist');
        }
    }

    public function testParseFile()
    {
        $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini'));
        $r = new \ReflectionObject($loader);
        $m = $r->getMethod('parseFile');
        $m->setAccessible(true);

        try {
            $m->invoke($loader, self::$fixturesPath.'/ini/parameters.ini');
            $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
            $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'parameters.ini'), $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');

            $e = $e->getPrevious();
            $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
            $this->assertStringStartsWith('[ERROR 4] Start tag expected, \'<\' not found (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');
        }

        $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/xml'));

        try {
            $m->invoke($loader, self::$fixturesPath.'/xml/nonvalid.xml');
            $this->fail('->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
            $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'nonvalid.xml'), $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file is not a valid XML file');

            $e = $e->getPrevious();
            $this->assertInstanceOf('InvalidArgumentException', $e, '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
            $this->assertStringStartsWith('[ERROR 1845] Element \'nonvalid\': No matching global declaration available for the validation root. (in', $e->getMessage(), '->parseFile() throws an InvalidArgumentException if the loaded file does not validate the XSD');
        }

        $xml = $m->invoke($loader, self::$fixturesPath.'/xml/services1.xml');
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\SimpleXMLElement', $xml, '->parseFile() returns an SimpleXMLElement object');
    }

    public function testLoadParameters()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services2.xml');

        $actual = $container->getParameterBag()->all();
        $expected = array(
            'a string',
            'foo' => 'bar',
            'values' => array(
                0,
                'integer' => 4,
                100 => null,
                'true',
                true,
                false,
                'on',
                'off',
                'float' => 1.3,
                1000.3,
                'a string',
                array('foo', 'bar'),
            ),
            'foo_bar' => new Reference('foo_bar'),
            'mixedcase' => array('MixedCaseKey' => 'value'),
            'constant' => PHP_EOL,
        );

        $this->assertEquals($expected, $actual, '->load() converts XML values to PHP ones');
    }

    public function testLoadImports()
    {
        $container = new ContainerBuilder();
        $resolver = new LoaderResolver(array(
            new IniFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
            new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
            $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')),
        ));
        $loader->setResolver($resolver);
        $loader->load('services4.xml');

        $actual = $container->getParameterBag()->all();
        $expected = array(
            'a string',
            'foo' => 'bar',
            'values' => array(
                0,
                'integer' => 4,
                100 => null,
                'true',
                true,
                false,
                'on',
                'off',
                'float' => 1.3,
                1000.3,
                'a string',
                array('foo', 'bar'),
            ),
            'foo_bar' => new Reference('foo_bar'),
            'mixedcase' => array('MixedCaseKey' => 'value'),
            'constant' => PHP_EOL,
            'bar' => '%foo%',
            'imported_from_ini' => true,
            'imported_from_yaml' => true
        );

        $this->assertEquals(array_keys($expected), array_keys($actual), '->load() imports and merges imported files');

        // Bad import throws no exception due to ignore_errors value.
        $loader->load('services4_bad_import.xml');
    }

    public function testLoadAnonymousServices()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services5.xml');
        $services = $container->getDefinitions();
        $this->assertCount(4, $services, '->load() attributes unique ids to anonymous services');

        // anonymous service as an argument
        $args = $services['foo']->getArguments();
        $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
        $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones');
        $inner = $services[(string) $args[0]];
        $this->assertEquals('BarClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');

        // inner anonymous services
        $args = $inner->getArguments();
        $this->assertCount(1, $args, '->load() references anonymous services as "normal" ones');
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $args[0], '->load() converts anonymous services to references to "normal" services');
        $this->assertTrue(isset($services[(string) $args[0]]), '->load() makes a reference to the created ones');
        $inner = $services[(string) $args[0]];
        $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');

        // anonymous service as a property
        $properties = $services['foo']->getProperties();
        $property = $properties['p'];
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Reference', $property, '->load() converts anonymous services to references to "normal" services');
        $this->assertTrue(isset($services[(string) $property]), '->load() makes a reference to the created ones');
        $inner = $services[(string) $property];
        $this->assertEquals('BazClass', $inner->getClass(), '->load() uses the same configuration as for the anonymous ones');
    }

    public function testLoadServices()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services6.xml');
        $services = $container->getDefinitions();
        $this->assertTrue(isset($services['foo']), '->load() parses <service> elements');
        $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Definition', $services['foo'], '->load() converts <service> element to Definition instances');
        $this->assertEquals('FooClass', $services['foo']->getClass(), '->load() parses the class attribute');
        $this->assertEquals('container', $services['scope.container']->getScope());
        $this->assertEquals('custom', $services['scope.custom']->getScope());
        $this->assertEquals('prototype', $services['scope.prototype']->getScope());
        $this->assertEquals('getInstance', $services['constructor']->getFactoryMethod(), '->load() parses the factory-method attribute');
        $this->assertEquals('%path%/foo.php', $services['file']->getFile(), '->load() parses the file tag');
        $this->assertEquals(array('foo', new Reference('foo'), array(true, false)), $services['arguments']->getArguments(), '->load() parses the argument tags');
        $this->assertEquals('sc_configure', $services['configurator1']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array(new Reference('baz', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false), 'configure'), $services['configurator2']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array('BazClass', 'configureStatic'), $services['configurator3']->getConfigurator(), '->load() parses the configurator tag');
        $this->assertEquals(array(array('setBar', array()), array('setBar', array(new Expression('service("foo").foo() ~ parameter("foo")')))), $services['method_call1']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertEquals(array(array('setBar', array('foo', new Reference('foo'), array(true, false)))), $services['method_call2']->getMethodCalls(), '->load() parses the method_call tag');
        $this->assertNull($services['factory_service']->getClass());
        $this->assertEquals('getInstance', $services['factory_service']->getFactoryMethod());
        $this->assertEquals('baz_factory', $services['factory_service']->getFactoryService());

        $this->assertTrue($services['request']->isSynthetic(), '->load() parses the synthetic flag');
        $this->assertTrue($services['request']->isSynchronized(), '->load() parses the synchronized flag');
        $this->assertTrue($services['request']->isLazy(), '->load() parses the lazy flag');

        $aliases = $container->getAliases();
        $this->assertTrue(isset($aliases['alias_for_foo']), '->load() parses <service> elements');
        $this->assertEquals('foo', (string) $aliases['alias_for_foo'], '->load() parses aliases');
        $this->assertTrue($aliases['alias_for_foo']->isPublic());
        $this->assertTrue(isset($aliases['another_alias_for_foo']));
        $this->assertEquals('foo', (string) $aliases['another_alias_for_foo']);
        $this->assertFalse($aliases['another_alias_for_foo']->isPublic());
    }

    public function testParsesTags()
    {
        $container = new ContainerBuilder();
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('services10.xml');

        $services = $container->findTaggedServiceIds('foo_tag');
        $this->assertCount(1, $services);

        foreach ($services as $id => $tagAttributes) {
            foreach ($tagAttributes as $attributes) {
                $this->assertArrayHasKey('other_option', $attributes);
                $this->assertEquals('lorem', $attributes['other_option']);
                $this->assertArrayHasKey('other-option', $attributes, 'unnormalized tag attributes should not be removed');

                $this->assertEquals('ciz', $attributes['some_option'], 'no overriding should be done when normalizing');
                $this->assertEquals('cat', $attributes['some-option']);

                $this->assertArrayNotHasKey('an_other_option', $attributes, 'normalization should not be done when an underscore is already found');
            }
        }
    }

    public function testConvertDomElementToArray()
    {
        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo>bar</foo>');
        $this->assertEquals('bar', XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo foo="bar" />');
        $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo><foo>bar</foo></foo>');
        $this->assertEquals(array('foo' => 'bar'), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo><foo>bar<foo>bar</foo></foo></foo>');
        $this->assertEquals(array('foo' => array('value' => 'bar', 'foo' => 'bar')), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo><foo></foo></foo>');
        $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo><foo><!-- foo --></foo></foo>');
        $this->assertEquals(array('foo' => null), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');

        $doc = new \DOMDocument("1.0");
        $doc->loadXML('<foo><foo foo="bar"/><foo foo="bar"/></foo>');
        $this->assertEquals(array('foo' => array(array('foo' => 'bar'), array('foo' => 'bar'))), XmlFileLoader::convertDomElementToArray($doc->documentElement), '::convertDomElementToArray() converts a \DomElement to an array');
    }

    public function testExtensions()
    {
        $container = new ContainerBuilder();
        $container->registerExtension(new \ProjectExtension());
        $container->registerExtension(new \ProjectWithXsdExtension());
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));

        // extension without an XSD
        $loader->load('extensions/services1.xml');
        $container->compile();
        $services = $container->getDefinitions();
        $parameters = $container->getParameterBag()->all();

        $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
        $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements');

        $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
        $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');

        // extension with an XSD
        $container = new ContainerBuilder();
        $container->registerExtension(new \ProjectExtension());
        $container->registerExtension(new \ProjectWithXsdExtension());
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('extensions/services2.xml');
        $container->compile();
        $services = $container->getDefinitions();
        $parameters = $container->getParameterBag()->all();

        $this->assertTrue(isset($services['project.service.bar']), '->load() parses extension elements');
        $this->assertTrue(isset($parameters['project.parameter.bar']), '->load() parses extension elements');

        $this->assertEquals('BAR', $services['project.service.foo']->getClass(), '->load() parses extension elements');
        $this->assertEquals('BAR', $parameters['project.parameter.foo'], '->load() parses extension elements');

        $container = new ContainerBuilder();
        $container->registerExtension(new \ProjectExtension());
        $container->registerExtension(new \ProjectWithXsdExtension());
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));

        // extension with an XSD (does not validate)
        try {
            $loader->load('extensions/services3.xml');
            $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
            $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services3.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');

            $e = $e->getPrevious();
            $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
            $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
        }

        // non-registered extension
        try {
            $loader->load('extensions/services4.xml');
            $this->fail('->load() throws an InvalidArgumentException if the tag is not valid');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the tag is not valid');
            $this->assertStringStartsWith('There is no extension able to load the configuration for "project:bar" (in', $e->getMessage(), '->load() throws an InvalidArgumentException if the tag is not valid');
        }
    }

    public function testExtensionInPhar()
    {
        if (extension_loaded('suhosin') && false === strpos(ini_get('suhosin.executor.include.whitelist'), 'phar')) {
            $this->markTestSkipped('To run this test, add "phar" to the "suhosin.executor.include.whitelist" settings in your php.ini file.');
        }

        require_once self::$fixturesPath.'/includes/ProjectWithXsdExtensionInPhar.phar';

        // extension with an XSD in PHAR archive
        $container = new ContainerBuilder();
        $container->registerExtension(new \ProjectWithXsdExtensionInPhar());
        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));
        $loader->load('extensions/services6.xml');

        // extension with an XSD in PHAR archive (does not validate)
        try {
            $loader->load('extensions/services7.xml');
            $this->fail('->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
            $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'services7.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');

            $e = $e->getPrevious();
            $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
            $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\XmlFileLoader::supports
     */
    public function testSupports()
    {
        $loader = new XmlFileLoader(new ContainerBuilder(), new FileLocator());

        $this->assertTrue($loader->supports('foo.xml'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }

    public function testNoNamingConflictsForAnonymousServices()
    {
        $container = new ContainerBuilder();

        $loader1 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension1'));
        $loader1->load('services.xml');
        $services = $container->getDefinitions();
        $this->assertCount(2, $services, '->load() attributes unique ids to anonymous services');
        $loader2 = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml/extension2'));
        $loader2->load('services.xml');
        $services = $container->getDefinitions();
        $this->assertCount(4, $services, '->load() attributes unique ids to anonymous services');

        $services = $container->getDefinitions();
        $args1 = $services['extension1.foo']->getArguments();
        $inner1 = $services[(string) $args1[0]];
        $this->assertEquals('BarClass1', $inner1->getClass(), '->load() uses the same configuration as for the anonymous ones');
        $args2 = $services['extension2.foo']->getArguments();
        $inner2 = $services[(string) $args2[0]];
        $this->assertEquals('BarClass2', $inner2->getClass(), '->load() uses the same configuration as for the anonymous ones');
    }

    public function testDocTypeIsNotAllowed()
    {
        $container = new ContainerBuilder();

        $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml'));

        // document types are not allowed.
        try {
            $loader->load('withdoctype.xml');
            $this->fail('->load() throws an InvalidArgumentException if the configuration contains a document type');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\\Component\\DependencyInjection\\Exception\\InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
            $this->assertRegExp(sprintf('#^Unable to parse file ".+%s".$#', 'withdoctype.xml'), $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');

            $e = $e->getPrevious();
            $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration contains a document type');
            $this->assertSame('Document types are not allowed.', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration contains a document type');
        }
    }
}
PKU1[���
�
\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Loader;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\Config\FileLocator;

class IniFileLoaderTest extends \PHPUnit_Framework_TestCase
{
    protected static $fixturesPath;

    protected $container;
    protected $loader;

    public static function setUpBeforeClass()
    {
        self::$fixturesPath = realpath(__DIR__.'/../Fixtures/');
    }

    protected function setUp()
    {
        $this->container = new ContainerBuilder();
        $this->loader    = new IniFileLoader($this->container, new FileLocator(self::$fixturesPath.'/ini'));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load
     */
    public function testIniFileCanBeLoaded()
    {
        $this->loader->load('parameters.ini');
        $this->assertEquals(array('foo' => 'bar', 'bar' => '%foo%'), $this->container->getParameterBag()->all(), '->load() takes a single file name as its first argument');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load
     *
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The file "foo.ini" does not exist (in:
     */
    public function testExceptionIsRaisedWhenIniFileDoesNotExist()
    {
        $this->loader->load('foo.ini');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::__construct
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::load
     *
     * @expectedException        \InvalidArgumentException
     * @expectedExceptionMessage The "nonvalid.ini" file is not valid.
     */
    public function testExceptionIsRaisedWhenIniFileCannotBeParsed()
    {
        @$this->loader->load('nonvalid.ini');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Loader\IniFileLoader::supports
     */
    public function testSupports()
    {
        $loader = new IniFileLoader(new ContainerBuilder(), new FileLocator());

        $this->assertTrue($loader->supports('foo.ini'), '->supports() returns true if the resource is loadable');
        $this->assertFalse($loader->supports('foo.foo'), '->supports() returns true if the resource is loadable');
    }
}
PKU1['����	�	mDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInvalidReferencesPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Compiler\ResolveInvalidReferencesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class ResolveInvalidReferencesPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $def = $container
            ->register('foo')
            ->setArguments(array(new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE)))
            ->addMethodCall('foo', array(new Reference('moo', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)))
        ;

        $this->process($container);

        $arguments = $def->getArguments();
        $this->assertNull($arguments[0]);
        $this->assertCount(0, $def->getMethodCalls());
    }

    public function testProcessIgnoreNonExistentServices()
    {
        $container = new ContainerBuilder();
        $def = $container
            ->register('foo')
            ->setArguments(array(new Reference('bar')))
        ;

        $this->process($container);

        $arguments = $def->getArguments();
        $this->assertEquals('bar', (string) $arguments[0]);
    }

    public function testProcessRemovesPropertiesOnInvalid()
    {
        $container = new ContainerBuilder();
        $def = $container
            ->register('foo')
            ->setProperty('foo', new Reference('bar', ContainerInterface::IGNORE_ON_INVALID_REFERENCE))
        ;

        $this->process($container);

        $this->assertEquals(array(), $def->getProperties());
    }

    public function testStrictFlagIsPreserved()
    {
        $container = new ContainerBuilder();
        $container->register('bar');
        $def = $container
            ->register('foo')
            ->addArgument(new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE, false))
        ;

        $this->process($container);

        $this->assertFalse($def->getArgument(0)->isStrict());
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new ResolveInvalidReferencesPass();
        $pass->process($container);
    }
}
PKV1[��'{{lDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Reference;

use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass;

use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;

use Symfony\Component\DependencyInjection\Compiler\Compiler;

use Symfony\Component\DependencyInjection\ContainerBuilder;

class CheckCircularReferencesPassTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
     */
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b')->addArgument(new Reference('a'));

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
     */
    public function testProcessWithAliases()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->setAlias('b', 'c');
        $container->setAlias('c', 'a');

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
     */
    public function testProcessDetectsIndirectCircularReference()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b')->addArgument(new Reference('c'));
        $container->register('c')->addArgument(new Reference('a'));

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
     */
    public function testDeepCircularReference()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b')->addArgument(new Reference('c'));
        $container->register('c')->addArgument(new Reference('b'));

        $this->process($container);
    }

    public function testProcessIgnoresMethodCalls()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b')->addMethodCall('setA', array(new Reference('a')));

        $this->process($container);
    }

    protected function process(ContainerBuilder $container)
    {
        $compiler = new Compiler();
        $passConfig = $compiler->getPassConfig();
        $passConfig->setOptimizationPasses(array(
            new AnalyzeServiceReferencesPass(true),
            new CheckCircularReferencesPass(),
        ));
        $passConfig->setRemovingPasses(array());

        $compiler->compile($container);
    }
}
PKV1[>�"��kDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Scope;

use Symfony\Component\DependencyInjection\Compiler\CheckReferenceValidityPass;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class CheckReferenceValidityPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcessIgnoresScopeWideningIfNonStrictReference()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false));
        $container->register('b')->setScope('prototype');

        $this->process($container);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testProcessDetectsScopeWidening()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b')->setScope('prototype');

        $this->process($container);
    }

    public function testProcessIgnoresCrossScopeHierarchyReferenceIfNotStrict()
    {
        $container = new ContainerBuilder();
        $container->addScope(new Scope('a'));
        $container->addScope(new Scope('b'));

        $container->register('a')->setScope('a')->addArgument(new Reference('b', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false));
        $container->register('b')->setScope('b');

        $this->process($container);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testProcessDetectsCrossScopeHierarchyReference()
    {
        $container = new ContainerBuilder();
        $container->addScope(new Scope('a'));
        $container->addScope(new Scope('b'));

        $container->register('a')->setScope('a')->addArgument(new Reference('b'));
        $container->register('b')->setScope('b');

        $this->process($container);
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testProcessDetectsReferenceToAbstractDefinition()
    {
        $container = new ContainerBuilder();

        $container->register('a')->setAbstract(true);
        $container->register('b')->addArgument(new Reference('a'));

        $this->process($container);
    }

    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('a')->addArgument(new Reference('b'));
        $container->register('b');

        $this->process($container);
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new CheckReferenceValidityPass();
        $pass->process($container);
    }
}
PKV1[]����oDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class ResolveDefinitionTemplatesPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('parent', 'foo')->setArguments(array('moo', 'b'))->setProperty('foo', 'moo');
        $container->setDefinition('child', new DefinitionDecorator('parent'))
            ->replaceArgument(0, 'a')
            ->setProperty('foo', 'bar')
            ->setClass('bar')
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertNotInstanceOf('Symfony\Component\DependencyInjection\DefinitionDecorator', $def);
        $this->assertEquals('bar', $def->getClass());
        $this->assertEquals(array('a', 'b'), $def->getArguments());
        $this->assertEquals(array('foo' => 'bar'), $def->getProperties());
    }

    public function testProcessAppendsMethodCallsAlways()
    {
        $container = new ContainerBuilder();

        $container
            ->register('parent')
            ->addMethodCall('foo', array('bar'))
        ;

        $container
            ->setDefinition('child', new DefinitionDecorator('parent'))
            ->addMethodCall('bar', array('foo'))
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertEquals(array(
            array('foo', array('bar')),
            array('bar', array('foo')),
        ), $def->getMethodCalls());
    }

    public function testProcessDoesNotCopyAbstract()
    {
        $container = new ContainerBuilder();

        $container
            ->register('parent')
            ->setAbstract(true)
        ;

        $container
            ->setDefinition('child', new DefinitionDecorator('parent'))
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertFalse($def->isAbstract());
    }

    public function testProcessDoesNotCopyScope()
    {
        $container = new ContainerBuilder();

        $container
            ->register('parent')
            ->setScope('foo')
        ;

        $container
            ->setDefinition('child', new DefinitionDecorator('parent'))
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertEquals(ContainerInterface::SCOPE_CONTAINER, $def->getScope());
    }

    public function testProcessDoesNotCopyTags()
    {
        $container = new ContainerBuilder();

        $container
            ->register('parent')
            ->addTag('foo')
        ;

        $container
            ->setDefinition('child', new DefinitionDecorator('parent'))
        ;

        $this->process($container);

        $def = $container->getDefinition('child');
        $this->assertEquals(array(), $def->getTags());
    }

    public function testProcessHandlesMultipleInheritance()
    {
        $container = new ContainerBuilder();

        $container
            ->register('parent', 'foo')
            ->setArguments(array('foo', 'bar', 'c'))
        ;

        $container
            ->setDefinition('child2', new DefinitionDecorator('child1'))
            ->replaceArgument(1, 'b')
        ;

        $container
            ->setDefinition('child1', new DefinitionDecorator('parent'))
            ->replaceArgument(0, 'a')
        ;

        $this->process($container);

        $def = $container->getDefinition('child2');
        $this->assertEquals(array('a', 'b', 'c'), $def->getArguments());
        $this->assertEquals('foo', $def->getClass());
    }

    public function testSetLazyOnServiceHasParent()
    {
        $container = new ContainerBuilder();

        $container->register('parent','stdClass');

        $container->setDefinition('child1',new DefinitionDecorator('parent'))
            ->setLazy(true)
        ;

        $this->process($container);

        $this->assertTrue($container->getDefinition('child1')->isLazy());
    }

    public function testSetLazyOnServiceIsParent()
    {
        $container = new ContainerBuilder();

        $container->register('parent','stdClass')
            ->setLazy(true)
        ;

        $container->setDefinition('child1',new DefinitionDecorator('parent'));

        $this->process($container);

        $this->assertTrue($container->getDefinition('child1')->isLazy());
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new ResolveDefinitionTemplatesPass();
        $pass->process($container);
    }
}
PKV1[}1H@@sDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Compiler\ReplaceAliasByActualDefinitionPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;

class ReplaceAliasByActualDefinitionPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();

        $container->register('a', '\stdClass');

        $bDefinition = new Definition('\stdClass');
        $bDefinition->setPublic(false);
        $container->setDefinition('b', $bDefinition);

        $container->setAlias('a_alias', 'a');
        $container->setAlias('b_alias', 'b');

        $this->process($container);

        $this->assertTrue($container->has('a'), '->process() does nothing to public definitions.');
        $this->assertTrue($container->hasAlias('a_alias'));
        $this->assertFalse($container->has('b'), '->process() removes non-public definitions.');
        $this->assertTrue(
            $container->has('b_alias') && !$container->hasAlias('b_alias'),
            '->process() replaces alias to actual.'
        );
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testProcessWithInvalidAlias()
    {
        $container = new ContainerBuilder();
        $container->setAlias('a_alias', 'a');
        $this->process($container);
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new ReplaceAliasByActualDefinitionPass();
        $pass->process($container);
    }
}
PKV1[��f00mDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
use Symfony\Component\DependencyInjection\Compiler\RepeatedPass;
use Symfony\Component\DependencyInjection\Compiler\InlineServiceDefinitionsPass;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class InlineServiceDefinitionsPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container
            ->register('inlinable.service')
            ->setPublic(false)
        ;

        $container
            ->register('service')
            ->setArguments(array(new Reference('inlinable.service')))
        ;

        $this->process($container);

        $arguments = $container->getDefinition('service')->getArguments();
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Definition', $arguments[0]);
        $this->assertSame($container->getDefinition('inlinable.service'), $arguments[0]);
    }

    public function testProcessDoesNotInlineWhenAliasedServiceIsNotOfPrototypeScope()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
        ;
        $container->setAlias('moo', 'foo');

        $container
            ->register('service')
            ->setArguments(array($ref = new Reference('foo')))
        ;

        $this->process($container);

        $arguments = $container->getDefinition('service')->getArguments();
        $this->assertSame($ref, $arguments[0]);
    }

    public function testProcessDoesInlineServiceOfPrototypeScope()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setScope('prototype')
        ;
        $container
            ->register('bar')
            ->setPublic(false)
            ->setScope('prototype')
        ;
        $container->setAlias('moo', 'bar');

        $container
            ->register('service')
            ->setArguments(array(new Reference('foo'), $ref = new Reference('moo'), new Reference('bar')))
        ;

        $this->process($container);

        $arguments = $container->getDefinition('service')->getArguments();
        $this->assertEquals($container->getDefinition('foo'), $arguments[0]);
        $this->assertNotSame($container->getDefinition('foo'), $arguments[0]);
        $this->assertSame($ref, $arguments[1]);
        $this->assertEquals($container->getDefinition('bar'), $arguments[2]);
        $this->assertNotSame($container->getDefinition('bar'), $arguments[2]);
    }

    public function testProcessInlinesIfMultipleReferencesButAllFromTheSameDefinition()
    {
        $container = new ContainerBuilder();

        $a = $container->register('a')->setPublic(false);
        $b = $container
            ->register('b')
            ->addArgument(new Reference('a'))
            ->addArgument(new Definition(null, array(new Reference('a'))))
        ;

        $this->process($container);

        $arguments = $b->getArguments();
        $this->assertSame($a, $arguments[0]);

        $inlinedArguments = $arguments[1]->getArguments();
        $this->assertSame($a, $inlinedArguments[0]);
    }

    public function testProcessInlinesOnlyIfSameScope()
    {
        $container = new ContainerBuilder();

        $container->addScope(new Scope('foo'));
        $a = $container->register('a')->setPublic(false)->setScope('foo');
        $b = $container->register('b')->addArgument(new Reference('a'));

        $this->process($container);
        $arguments = $b->getArguments();
        $this->assertEquals(new Reference('a'), $arguments[0]);
        $this->assertTrue($container->hasDefinition('a'));
    }

    public function testProcessDoesNotInlineWhenServiceIsPrivateButLazy()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
            ->setLazy(true)
        ;

        $container
            ->register('service')
            ->setArguments(array($ref = new Reference('foo')))
        ;

        $this->process($container);

        $arguments = $container->getDefinition('service')->getArguments();
        $this->assertSame($ref, $arguments[0]);
    }

    public function testProcessDoesNotInlineWhenServiceReferencesItself()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
            ->addMethodCall('foo', array($ref = new Reference('foo')))
        ;

        $this->process($container);

        $calls = $container->getDefinition('foo')->getMethodCalls();
        $this->assertSame($ref, $calls[0][1][0]);
    }

    protected function process(ContainerBuilder $container)
    {
        $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new InlineServiceDefinitionsPass()));
        $repeatedPass->process($container);
    }
}
PKV1[O����\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/IntegrationTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * This class tests the integration of the different compiler passes
 */
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * This tests that the following dependencies are correctly processed:
     *
     * A is public, B/C are private
     * A -> C
     * B -> C
     */
    public function testProcessRemovesAndInlinesRecursively()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);

        $a = $container
            ->register('a', '\stdClass')
            ->addArgument(new Reference('c'))
        ;

        $b = $container
            ->register('b', '\stdClass')
            ->addArgument(new Reference('c'))
            ->setPublic(false)
        ;

        $c = $container
            ->register('c', '\stdClass')
            ->setPublic(false)
        ;

        $container->compile();

        $this->assertTrue($container->hasDefinition('a'));
        $arguments = $a->getArguments();
        $this->assertSame($c, $arguments[0]);
        $this->assertFalse($container->hasDefinition('b'));
        $this->assertFalse($container->hasDefinition('c'));
    }

    public function testProcessInlinesReferencesToAliases()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);

        $a = $container
            ->register('a', '\stdClass')
            ->addArgument(new Reference('b'))
        ;

        $container->setAlias('b', new Alias('c', false));

        $c = $container
            ->register('c', '\stdClass')
            ->setPublic(false)
        ;

        $container->compile();

        $this->assertTrue($container->hasDefinition('a'));
        $arguments = $a->getArguments();
        $this->assertSame($c, $arguments[0]);
        $this->assertFalse($container->hasAlias('b'));
        $this->assertFalse($container->hasDefinition('c'));
    }

    public function testProcessInlinesWhenThereAreMultipleReferencesButFromTheSameDefinition()
    {
        $container = new ContainerBuilder();
        $container->setResourceTracking(false);

        $container
            ->register('a', '\stdClass')
            ->addArgument(new Reference('b'))
            ->addMethodCall('setC', array(new Reference('c')))
        ;

        $container
            ->register('b', '\stdClass')
            ->addArgument(new Reference('c'))
            ->setPublic(false)
        ;

        $container
            ->register('c', '\stdClass')
            ->setPublic(false)
        ;

        $container->compile();

        $this->assertTrue($container->hasDefinition('a'));
        $this->assertFalse($container->hasDefinition('b'));
        $this->assertFalse($container->hasDefinition('c'), 'Service C was not inlined.');
    }
}
PKV1[@|޵�}DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Definition;

use Symfony\Component\DependencyInjection\Compiler\CheckExceptionOnInvalidReferenceBehaviorPass;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class CheckExceptionOnInvalidReferenceBehaviorPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();

        $container
            ->register('a', '\stdClass')
            ->addArgument(new Reference('b'))
        ;
        $container->register('b', '\stdClass');
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
     */
    public function testProcessThrowsExceptionOnInvalidReference()
    {
        $container = new ContainerBuilder();

        $container
            ->register('a', '\stdClass')
            ->addArgument(new Reference('b'))
        ;

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
     */
    public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition()
    {
        $container = new ContainerBuilder();

        $def = new Definition();
        $def->addArgument(new Reference('b'));

        $container
            ->register('a', '\stdClass')
            ->addArgument($def)
        ;

        $this->process($container);
    }

    private function process(ContainerBuilder $container)
    {
        $pass = new CheckExceptionOnInvalidReferenceBehaviorPass();
        $pass->process($container);
    }
}
PKV1[@�w��lDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CheckDefinitionValidityPass;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class CheckDefinitionValidityPassTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
     */
    public function testProcessDetectsSyntheticNonPublicDefinitions()
    {
        $container = new ContainerBuilder();
        $container->register('a')->setSynthetic(true)->setPublic(false);

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
     */
    public function testProcessDetectsSyntheticPrototypeDefinitions()
    {
        $container = new ContainerBuilder();
        $container->register('a')->setSynthetic(true)->setScope(ContainerInterface::SCOPE_PROTOTYPE);

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
     */
    public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass()
    {
        $container = new ContainerBuilder();
        $container->register('a')->setSynthetic(false)->setAbstract(false);

        $this->process($container);
    }

    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->register('a', 'class');
        $container->register('b', 'class')->setSynthetic(true)->setPublic(true);
        $container->register('c', 'class')->setAbstract(true);
        $container->register('d', 'class')->setSynthetic(true);

        $this->process($container);
    }

    public function testValidTags()
    {
        $container = new ContainerBuilder();
        $container->register('a', 'class')->addTag('foo', array('bar' => 'baz'));
        $container->register('b', 'class')->addTag('foo', array('bar' => null));
        $container->register('c', 'class')->addTag('foo', array('bar' => 1));
        $container->register('d', 'class')->addTag('foo', array('bar' => 1.1));

        $this->process($container);
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
     */
    public function testInvalidTags()
    {
        $container = new ContainerBuilder();
        $container->register('a', 'class')->addTag('foo', array('bar' => array('baz' => 'baz')));

        $this->process($container);
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new CheckDefinitionValidityPass();
        $pass->process($container);
    }
}
PKV1[�~�``mDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Compiler\Compiler;
use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
use Symfony\Component\DependencyInjection\Compiler\RepeatedPass;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AnalyzeServiceReferencesPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();

        $a = $container
            ->register('a')
            ->addArgument($ref1 = new Reference('b'))
        ;

        $b = $container
            ->register('b')
            ->addMethodCall('setA', array($ref2 = new Reference('a')))
        ;

        $c = $container
            ->register('c')
            ->addArgument($ref3 = new Reference('a'))
            ->addArgument($ref4 = new Reference('b'))
        ;

        $d = $container
            ->register('d')
            ->setProperty('foo', $ref5 = new Reference('b'))
        ;

        $e = $container
            ->register('e')
            ->setConfigurator(array($ref6 = new Reference('b'), 'methodName'))
        ;

        $graph = $this->process($container);

        $this->assertCount(4, $edges = $graph->getNode('b')->getInEdges());

        $this->assertSame($ref1, $edges[0]->getValue());
        $this->assertSame($ref4, $edges[1]->getValue());
        $this->assertSame($ref5, $edges[2]->getValue());
        $this->assertSame($ref6, $edges[3]->getValue());
    }

    public function testProcessDetectsReferencesFromInlinedDefinitions()
    {
        $container = new ContainerBuilder();

        $container
            ->register('a')
        ;

        $container
            ->register('b')
            ->addArgument(new Definition(null, array($ref = new Reference('a'))))
        ;

        $graph = $this->process($container);

        $this->assertCount(1, $refs = $graph->getNode('a')->getInEdges());
        $this->assertSame($ref, $refs[0]->getValue());
    }

    public function testProcessDoesNotSaveDuplicateReferences()
    {
        $container = new ContainerBuilder();

        $container
            ->register('a')
        ;
        $container
            ->register('b')
            ->addArgument(new Definition(null, array($ref1 = new Reference('a'))))
            ->addArgument(new Definition(null, array($ref2 = new Reference('a'))))
        ;

        $graph = $this->process($container);

        $this->assertCount(2, $graph->getNode('a')->getInEdges());
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new RepeatedPass(array(new AnalyzeServiceReferencesPass()));
        $pass->process($container);

        return $container->getCompiler()->getServiceReferenceGraph();
    }
}
PKV1[��I�
�
lDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
use Symfony\Component\DependencyInjection\Compiler\Compiler;
use Symfony\Component\DependencyInjection\Compiler\RepeatedPass;
use Symfony\Component\DependencyInjection\Compiler\RemoveUnusedDefinitionsPass;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class RemoveUnusedDefinitionsPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
        ;
        $container
            ->register('bar')
            ->setPublic(false)
        ;
        $container
            ->register('moo')
            ->setArguments(array(new Reference('bar')))
        ;

        $this->process($container);

        $this->assertFalse($container->hasDefinition('foo'));
        $this->assertTrue($container->hasDefinition('bar'));
        $this->assertTrue($container->hasDefinition('moo'));
    }

    public function testProcessRemovesUnusedDefinitionsRecursively()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
        ;
        $container
            ->register('bar')
            ->setArguments(array(new Reference('foo')))
            ->setPublic(false)
        ;

        $this->process($container);

        $this->assertFalse($container->hasDefinition('foo'));
        $this->assertFalse($container->hasDefinition('bar'));
    }

    public function testProcessWorksWithInlinedDefinitions()
    {
        $container = new ContainerBuilder();
        $container
            ->register('foo')
            ->setPublic(false)
        ;
        $container
            ->register('bar')
            ->setArguments(array(new Definition(null, array(new Reference('foo')))))
        ;

        $this->process($container);

        $this->assertTrue($container->hasDefinition('foo'));
        $this->assertTrue($container->hasDefinition('bar'));
    }

    protected function process(ContainerBuilder $container)
    {
        $repeatedPass = new RepeatedPass(array(new AnalyzeServiceReferencesPass(), new RemoveUnusedDefinitionsPass()));
        $repeatedPass->process($container);
    }
}
PKV1[
T^�??oDependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Compiler;

use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Compiler\ResolveReferencesToAliasesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class ResolveReferencesToAliasesPassTest extends \PHPUnit_Framework_TestCase
{
    public function testProcess()
    {
        $container = new ContainerBuilder();
        $container->setAlias('bar', 'foo');
        $def = $container
            ->register('moo')
            ->setArguments(array(new Reference('bar')))
        ;

        $this->process($container);

        $arguments = $def->getArguments();
        $this->assertEquals('foo', (string) $arguments[0]);
    }

    public function testProcessRecursively()
    {
        $container = new ContainerBuilder();
        $container->setAlias('bar', 'foo');
        $container->setAlias('moo', 'bar');
        $def = $container
            ->register('foobar')
            ->setArguments(array(new Reference('moo')))
        ;

        $this->process($container);

        $arguments = $def->getArguments();
        $this->assertEquals('foo', (string) $arguments[0]);
    }

    protected function process(ContainerBuilder $container)
    {
        $pass = new ResolveReferencesToAliasesPass();
        $pass->process($container);
    }
}
PKV1[���e�5�5RDependencyInjection/Symfony/Component/DependencyInjection/Tests/DefinitionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\Definition;

class DefinitionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Definition::__construct
     */
    public function testConstructor()
    {
        $def = new Definition('stdClass');
        $this->assertEquals('stdClass', $def->getClass(), '__construct() takes the class name as its first argument');

        $def = new Definition('stdClass', array('foo'));
        $this->assertEquals(array('foo'), $def->getArguments(), '__construct() takes an optional array of arguments as its second argument');
    }

    public function testSetGetFactoryClass()
    {
        $def = new Definition('stdClass');
        $this->assertNull($def->getFactoryClass());
        $this->assertSame($def, $def->setFactoryClass('stdClass2'), "->setFactoryClass() implements a fluent interface.");
        $this->assertEquals('stdClass2', $def->getFactoryClass(), "->getFactoryClass() returns current class to construct this service.");
    }

    public function testSetGetFactoryMethod()
    {
        $def = new Definition('stdClass');
        $this->assertNull($def->getFactoryMethod());
        $this->assertSame($def, $def->setFactoryMethod('foo'), '->setFactoryMethod() implements a fluent interface');
        $this->assertEquals('foo', $def->getFactoryMethod(), '->getFactoryMethod() returns the factory method name');
    }

    public function testSetGetFactoryService()
    {
        $def = new Definition('stdClass');
        $this->assertNull($def->getFactoryService());
        $this->assertSame($def, $def->setFactoryService('foo.bar'), "->setFactoryService() implements a fluent interface.");
        $this->assertEquals('foo.bar', $def->getFactoryService(), "->getFactoryService() returns current service to construct this service.");
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setClass
     * @covers Symfony\Component\DependencyInjection\Definition::getClass
     */
    public function testSetGetClass()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->setClass('foo'), '->setClass() implements a fluent interface');
        $this->assertEquals('foo', $def->getClass(), '->getClass() returns the class name');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setArguments
     * @covers Symfony\Component\DependencyInjection\Definition::getArguments
     * @covers Symfony\Component\DependencyInjection\Definition::addArgument
     */
    public function testArguments()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->setArguments(array('foo')), '->setArguments() implements a fluent interface');
        $this->assertEquals(array('foo'), $def->getArguments(), '->getArguments() returns the arguments');
        $this->assertSame($def, $def->addArgument('bar'), '->addArgument() implements a fluent interface');
        $this->assertEquals(array('foo', 'bar'), $def->getArguments(), '->addArgument() adds an argument');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setMethodCalls
     * @covers Symfony\Component\DependencyInjection\Definition::addMethodCall
     * @covers Symfony\Component\DependencyInjection\Definition::hasMethodCall
     * @covers Symfony\Component\DependencyInjection\Definition::removeMethodCall
     */
    public function testMethodCalls()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->setMethodCalls(array(array('foo', array('foo')))), '->setMethodCalls() implements a fluent interface');
        $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->getMethodCalls() returns the methods to call');
        $this->assertSame($def, $def->addMethodCall('bar', array('bar')), '->addMethodCall() implements a fluent interface');
        $this->assertEquals(array(array('foo', array('foo')), array('bar', array('bar'))), $def->getMethodCalls(), '->addMethodCall() adds a method to call');
        $this->assertTrue($def->hasMethodCall('bar'), '->hasMethodCall() returns true if first argument is a method to call registered');
        $this->assertFalse($def->hasMethodCall('no_registered'), '->hasMethodCall() returns false if first argument is not a method to call registered');
        $this->assertSame($def, $def->removeMethodCall('bar'), '->removeMethodCall() implements a fluent interface');
        $this->assertEquals(array(array('foo', array('foo'))), $def->getMethodCalls(), '->removeMethodCall() removes a method to call');
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage Method name cannot be empty.
     */
    public function testExceptionOnEmptyMethodCall()
    {
        $def = new Definition('stdClass');
        $def->addMethodCall('');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setFile
     * @covers Symfony\Component\DependencyInjection\Definition::getFile
     */
    public function testSetGetFile()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->setFile('foo'), '->setFile() implements a fluent interface');
        $this->assertEquals('foo', $def->getFile(), '->getFile() returns the file to include');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setScope
     * @covers Symfony\Component\DependencyInjection\Definition::getScope
     */
    public function testSetGetScope()
    {
        $def = new Definition('stdClass');
        $this->assertEquals('container', $def->getScope());
        $this->assertSame($def, $def->setScope('foo'));
        $this->assertEquals('foo', $def->getScope());
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setPublic
     * @covers Symfony\Component\DependencyInjection\Definition::isPublic
     */
    public function testSetIsPublic()
    {
        $def = new Definition('stdClass');
        $this->assertTrue($def->isPublic(), '->isPublic() returns true by default');
        $this->assertSame($def, $def->setPublic(false), '->setPublic() implements a fluent interface');
        $this->assertFalse($def->isPublic(), '->isPublic() returns false if the instance must not be public.');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setSynthetic
     * @covers Symfony\Component\DependencyInjection\Definition::isSynthetic
     */
    public function testSetIsSynthetic()
    {
        $def = new Definition('stdClass');
        $this->assertFalse($def->isSynthetic(), '->isSynthetic() returns false by default');
        $this->assertSame($def, $def->setSynthetic(true), '->setSynthetic() implements a fluent interface');
        $this->assertTrue($def->isSynthetic(), '->isSynthetic() returns true if the service is synthetic.');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setSynchronized
     * @covers Symfony\Component\DependencyInjection\Definition::isSynchronized
     */
    public function testSetIsSynchronized()
    {
        $def = new Definition('stdClass');
        $this->assertFalse($def->isSynchronized(), '->isSynchronized() returns false by default');
        $this->assertSame($def, $def->setSynchronized(true), '->setSynchronized() implements a fluent interface');
        $this->assertTrue($def->isSynchronized(), '->isSynchronized() returns true if the service is synchronized.');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setLazy
     * @covers Symfony\Component\DependencyInjection\Definition::isLazy
     */
    public function testSetIsLazy()
    {
        $def = new Definition('stdClass');
        $this->assertFalse($def->isLazy(), '->isLazy() returns false by default');
        $this->assertSame($def, $def->setLazy(true), '->setLazy() implements a fluent interface');
        $this->assertTrue($def->isLazy(), '->isLazy() returns true if the service is lazy.');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setAbstract
     * @covers Symfony\Component\DependencyInjection\Definition::isAbstract
     */
    public function testSetIsAbstract()
    {
        $def = new Definition('stdClass');
        $this->assertFalse($def->isAbstract(), '->isAbstract() returns false by default');
        $this->assertSame($def, $def->setAbstract(true), '->setAbstract() implements a fluent interface');
        $this->assertTrue($def->isAbstract(), '->isAbstract() returns true if the instance must not be public.');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::setConfigurator
     * @covers Symfony\Component\DependencyInjection\Definition::getConfigurator
     */
    public function testSetGetConfigurator()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->setConfigurator('foo'), '->setConfigurator() implements a fluent interface');
        $this->assertEquals('foo', $def->getConfigurator(), '->getConfigurator() returns the configurator');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::clearTags
     */
    public function testClearTags()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface');
        $def->addTag('foo', array('foo' => 'bar'));
        $def->clearTags();
        $this->assertEquals(array(), $def->getTags(), '->clearTags() removes all current tags');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::clearTags
     */
    public function testClearTag()
    {
        $def = new Definition('stdClass');
        $this->assertSame($def, $def->clearTags(), '->clearTags() implements a fluent interface');
        $def->addTag('1foo1', array('foo1' => 'bar1'));
        $def->addTag('2foo2', array('foo2' => 'bar2'));
        $def->addTag('3foo3', array('foo3' => 'bar3'));
        $def->clearTag('2foo2');
        $this->assertTrue($def->hasTag('1foo1'));
        $this->assertFalse($def->hasTag('2foo2'));
        $this->assertTrue($def->hasTag('3foo3'));
        $def->clearTag('1foo1');
        $this->assertFalse($def->hasTag('1foo1'));
        $this->assertTrue($def->hasTag('3foo3'));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::addTag
     * @covers Symfony\Component\DependencyInjection\Definition::getTag
     * @covers Symfony\Component\DependencyInjection\Definition::getTags
     * @covers Symfony\Component\DependencyInjection\Definition::hasTag
     */
    public function testTags()
    {
        $def = new Definition('stdClass');
        $this->assertEquals(array(), $def->getTag('foo'), '->getTag() returns an empty array if the tag is not defined');
        $this->assertFalse($def->hasTag('foo'));
        $this->assertSame($def, $def->addTag('foo'), '->addTag() implements a fluent interface');
        $this->assertTrue($def->hasTag('foo'));
        $this->assertEquals(array(array()), $def->getTag('foo'), '->getTag() returns attributes for a tag name');
        $def->addTag('foo', array('foo' => 'bar'));
        $this->assertEquals(array(array(), array('foo' => 'bar')), $def->getTag('foo'), '->addTag() can adds the same tag several times');
        $def->addTag('bar', array('bar' => 'bar'));
        $this->assertEquals($def->getTags(), array(
            'foo' => array(array(), array('foo' => 'bar')),
            'bar' => array(array('bar' => 'bar')),
        ), '->getTags() returns all tags');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Definition::replaceArgument
     */
    public function testSetArgument()
    {
        $def = new Definition('stdClass');

        $def->addArgument('foo');
        $this->assertSame(array('foo'), $def->getArguments());

        $this->assertSame($def, $def->replaceArgument(0, 'moo'));
        $this->assertSame(array('moo'), $def->getArguments());

        $def->addArgument('moo');
        $def
            ->replaceArgument(0, 'foo')
            ->replaceArgument(1, 'bar')
        ;
        $this->assertSame(array('foo', 'bar'), $def->getArguments());
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetArgumentShouldCheckBounds()
    {
        $def = new Definition('stdClass');

        $def->addArgument('foo');
        $def->getArgument(1);
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testReplaceArgumentShouldCheckBounds()
    {
        $def = new Definition('stdClass');

        $def->addArgument('foo');
        $def->replaceArgument(1, 'bar');
    }

    public function testSetGetProperties()
    {
        $def = new Definition('stdClass');

        $this->assertEquals(array(), $def->getProperties());
        $this->assertSame($def, $def->setProperties(array('foo' => 'bar')));
        $this->assertEquals(array('foo' => 'bar'), $def->getProperties());
    }

    public function testSetProperty()
    {
        $def = new Definition('stdClass');

        $this->assertEquals(array(), $def->getProperties());
        $this->assertSame($def, $def->setProperty('foo', 'bar'));
        $this->assertEquals(array('foo' => 'bar'), $def->getProperties());
    }
}
PKV1[+��E�
�
[DependencyInjection/Symfony/Component/DependencyInjection/Tests/DefinitionDecoratorTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\DefinitionDecorator;

class DefinitionDecoratorTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $def = new DefinitionDecorator('foo');

        $this->assertEquals('foo', $def->getParent());
        $this->assertEquals(array(), $def->getChanges());
    }

    /**
     * @dataProvider getPropertyTests
     */
    public function testSetProperty($property, $changeKey)
    {
        $def = new DefinitionDecorator('foo');

        $getter = 'get'.ucfirst($property);
        $setter = 'set'.ucfirst($property);

        $this->assertNull($def->$getter());
        $this->assertSame($def, $def->$setter('foo'));
        $this->assertEquals('foo', $def->$getter());
        $this->assertEquals(array($changeKey => true), $def->getChanges());
    }

    public function getPropertyTests()
    {
        return array(
            array('class', 'class'),
            array('factoryClass', 'factory_class'),
            array('factoryMethod', 'factory_method'),
            array('factoryService', 'factory_service'),
            array('configurator', 'configurator'),
            array('file', 'file'),
        );
    }

    public function testSetPublic()
    {
        $def = new DefinitionDecorator('foo');

        $this->assertTrue($def->isPublic());
        $this->assertSame($def, $def->setPublic(false));
        $this->assertFalse($def->isPublic());
        $this->assertEquals(array('public' => true), $def->getChanges());
    }

    public function testSetLazy()
    {
        $def = new DefinitionDecorator('foo');

        $this->assertFalse($def->isLazy());
        $this->assertSame($def, $def->setLazy(false));
        $this->assertFalse($def->isLazy());
        $this->assertEquals(array('lazy' => true), $def->getChanges());
    }

    public function testSetArgument()
    {
        $def = new DefinitionDecorator('foo');

        $this->assertEquals(array(), $def->getArguments());
        $this->assertSame($def, $def->replaceArgument(0, 'foo'));
        $this->assertEquals(array('index_0' => 'foo'), $def->getArguments());
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testReplaceArgumentShouldRequireIntegerIndex()
    {
        $def = new DefinitionDecorator('foo');

        $def->replaceArgument('0', 'foo');
    }

    public function testReplaceArgument()
    {
        $def = new DefinitionDecorator('foo');

        $def->setArguments(array(0 => 'foo', 1 => 'bar'));
        $this->assertEquals('foo', $def->getArgument(0));
        $this->assertEquals('bar', $def->getArgument(1));

        $this->assertSame($def, $def->replaceArgument(1, 'baz'));
        $this->assertEquals('foo', $def->getArgument(0));
        $this->assertEquals('baz', $def->getArgument(1));

        $this->assertEquals(array(0 => 'foo', 1 => 'bar', 'index_1' => 'baz'), $def->getArguments());
    }

    /**
     * @expectedException \OutOfBoundsException
     */
    public function testGetArgumentShouldCheckBounds()
    {
        $def = new DefinitionDecorator('foo');

        $def->setArguments(array(0 => 'foo'));
        $def->replaceArgument(0, 'foo');

        $def->getArgument(1);
    }
}
PKV1[�K5��W�WQDependencyInjection/Symfony/Component/DependencyInjection/Tests/ContainerTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests;

use Symfony\Component\DependencyInjection\Scope;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;

class ContainerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @covers Symfony\Component\DependencyInjection\Container::__construct
     */
    public function testConstructor()
    {
        $sc = new Container();
        $this->assertSame($sc, $sc->get('service_container'), '__construct() automatically registers itself as a service');

        $sc = new Container(new ParameterBag(array('foo' => 'bar')));
        $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '__construct() takes an array of parameters as its first argument');
    }

    /**
     * @dataProvider dataForTestCamelize
     */
    public function testCamelize($id, $expected)
    {
        $this->assertEquals($expected, Container::camelize($id), sprintf('Container::camelize("%s")', $id));
    }

    public function dataForTestCamelize()
    {
        return array(
            array('foo_bar', 'FooBar'),
            array('foo.bar', 'Foo_Bar'),
            array('foo.bar_baz', 'Foo_BarBaz'),
            array('foo._bar', 'Foo_Bar'),
            array('foo_.bar', 'Foo_Bar'),
            array('_foo', 'Foo'),
            array('.foo', '_Foo'),
            array('foo_', 'Foo'),
            array('foo.', 'Foo_'),
            array('foo\bar', 'Foo_Bar'),
        );
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::compile
     */
    public function testCompile()
    {
        $sc = new Container(new ParameterBag(array('foo' => 'bar')));
        $sc->compile();
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag', $sc->getParameterBag(), '->compile() changes the parameter bag to a FrozenParameterBag instance');
        $this->assertEquals(array('foo' => 'bar'), $sc->getParameterBag()->all(), '->compile() copies the current parameters to the new parameter bag');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::isFrozen
     */
    public function testIsFrozen()
    {
        $sc = new Container(new ParameterBag(array('foo' => 'bar')));
        $this->assertFalse($sc->isFrozen(), '->isFrozen() returns false if the parameters are not frozen');
        $sc->compile();
        $this->assertTrue($sc->isFrozen(), '->isFrozen() returns true if the parameters are frozen');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::getParameterBag
     */
    public function testGetParameterBag()
    {
        $sc = new Container();
        $this->assertEquals(array(), $sc->getParameterBag()->all(), '->getParameterBag() returns an empty array if no parameter has been defined');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::setParameter
     * @covers Symfony\Component\DependencyInjection\Container::getParameter
     */
    public function testGetSetParameter()
    {
        $sc = new Container(new ParameterBag(array('foo' => 'bar')));
        $sc->setParameter('bar', 'foo');
        $this->assertEquals('foo', $sc->getParameter('bar'), '->setParameter() sets the value of a new parameter');

        $sc->setParameter('foo', 'baz');
        $this->assertEquals('baz', $sc->getParameter('foo'), '->setParameter() overrides previously set parameter');

        $sc->setParameter('Foo', 'baz1');
        $this->assertEquals('baz1', $sc->getParameter('foo'), '->setParameter() converts the key to lowercase');
        $this->assertEquals('baz1', $sc->getParameter('FOO'), '->getParameter() converts the key to lowercase');

        try {
            $sc->getParameter('baba');
            $this->fail('->getParameter() thrown an \InvalidArgumentException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\InvalidArgumentException', $e, '->getParameter() thrown an \InvalidArgumentException if the key does not exist');
            $this->assertEquals('You have requested a non-existent parameter "baba".', $e->getMessage(), '->getParameter() thrown an \InvalidArgumentException if the key does not exist');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::getServiceIds
     */
    public function testGetServiceIds()
    {
        $sc = new Container();
        $sc->set('foo', $obj = new \stdClass());
        $sc->set('bar', $obj = new \stdClass());
        $this->assertEquals(array('service_container', 'foo', 'bar'), $sc->getServiceIds(), '->getServiceIds() returns all defined service ids');

        $sc = new ProjectServiceContainer();
        $this->assertEquals(array('scoped', 'scoped_foo', 'inactive', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'service_container'), $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::set
     */
    public function testSet()
    {
        $sc = new Container();
        $sc->set('foo', $foo = new \stdClass());
        $this->assertEquals($foo, $sc->get('foo'), '->set() sets a service');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::set
     */
    public function testSetWithNullResetTheService()
    {
        $sc = new Container();
        $sc->set('foo', null);
        $this->assertFalse($sc->has('foo'));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testSetDoesNotAllowPrototypeScope()
    {
        $c = new Container();
        $c->set('foo', new \stdClass(), 'prototype');
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testSetDoesNotAllowInactiveScope()
    {
        $c = new Container();
        $c->addScope(new Scope('foo'));
        $c->set('foo', new \stdClass(), 'foo');
    }

    public function testSetAlsoSetsScopedService()
    {
        $c = new Container();
        $c->addScope(new Scope('foo'));
        $c->enterScope('foo');
        $c->set('foo', $foo = new \stdClass(), 'foo');

        $services = $this->getField($c, 'scopedServices');
        $this->assertTrue(isset($services['foo']['foo']));
        $this->assertSame($foo, $services['foo']['foo']);
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::get
     */
    public function testGet()
    {
        $sc = new ProjectServiceContainer();
        $sc->set('foo', $foo = new \stdClass());
        $this->assertEquals($foo, $sc->get('foo'), '->get() returns the service for the given id');
        $this->assertEquals($sc->__bar, $sc->get('bar'), '->get() returns the service for the given id');
        $this->assertEquals($sc->__foo_bar, $sc->get('foo_bar'), '->get() returns the service if a get*Method() is defined');
        $this->assertEquals($sc->__foo_baz, $sc->get('foo.baz'), '->get() returns the service if a get*Method() is defined');
        $this->assertEquals($sc->__foo_baz, $sc->get('foo\\baz'), '->get() returns the service if a get*Method() is defined');

        $sc->set('bar', $bar = new \stdClass());
        $this->assertEquals($bar, $sc->get('bar'), '->get() prefers to return a service defined with set() than one defined with a getXXXMethod()');

        try {
            $sc->get('');
            $this->fail('->get() throws a \InvalidArgumentException exception if the service is empty');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws a ServiceNotFoundException exception if the service is empty');
        }
        $this->assertNull($sc->get('', ContainerInterface::NULL_ON_INVALID_REFERENCE));
    }

    public function testGetThrowServiceNotFoundException()
    {
        $sc = new ProjectServiceContainer();
        $sc->set('foo', $foo = new \stdClass());
        $sc->set('bar', $foo = new \stdClass());
        $sc->set('baz', $foo = new \stdClass());

        try {
            $sc->get('foo1');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent service "foo1". Did you mean this: "foo"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices');
        }

        try {
            $sc->get('bag');
            $this->fail('->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException', $e, '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException if the key does not exist');
            $this->assertEquals('You have requested a non-existent service "bag". Did you mean one of these: "bar", "baz"?', $e->getMessage(), '->get() throws an Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException with some advices');
        }
    }

    public function testGetCircularReference()
    {

        $sc = new ProjectServiceContainer();
        try {
            $sc->get('circular');
            $this->fail('->get() throws a ServiceCircularReferenceException if it contains circular reference');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException', $e, '->get() throws a ServiceCircularReferenceException if it contains circular reference');
            $this->assertStringStartsWith('Circular reference detected for service "circular"', $e->getMessage(), '->get() throws a \LogicException if it contains circular reference');
        }
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::get
     */
    public function testGetReturnsNullOnInactiveScope()
    {
        $sc = new ProjectServiceContainer();
        $this->assertNull($sc->get('inactive', ContainerInterface::NULL_ON_INVALID_REFERENCE));
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::has
     */
    public function testHas()
    {
        $sc = new ProjectServiceContainer();
        $sc->set('foo', new \stdClass());
        $this->assertFalse($sc->has('foo1'), '->has() returns false if the service does not exist');
        $this->assertTrue($sc->has('foo'), '->has() returns true if the service exists');
        $this->assertTrue($sc->has('bar'), '->has() returns true if a get*Method() is defined');
        $this->assertTrue($sc->has('foo_bar'), '->has() returns true if a get*Method() is defined');
        $this->assertTrue($sc->has('foo.baz'), '->has() returns true if a get*Method() is defined');
        $this->assertTrue($sc->has('foo\\baz'), '->has() returns true if a get*Method() is defined');
    }

    /**
     * @covers Symfony\Component\DependencyInjection\Container::initialized
     */
    public function testInitialized()
    {
        $sc = new ProjectServiceContainer();
        $sc->set('foo', new \stdClass());
        $this->assertTrue($sc->initialized('foo'), '->initialized() returns true if service is loaded');
        $this->assertFalse($sc->initialized('foo1'), '->initialized() returns false if service is not loaded');
        $this->assertFalse($sc->initialized('bar'), '->initialized() returns false if a service is defined, but not currently loaded');
    }

    public function testEnterLeaveCurrentScope()
    {
        $container = new ProjectServiceContainer();
        $container->addScope(new Scope('foo'));

        $container->enterScope('foo');
        $scoped1 = $container->get('scoped');
        $scopedFoo1 = $container->get('scoped_foo');

        $container->enterScope('foo');
        $scoped2 = $container->get('scoped');
        $scoped3 = $container->get('scoped');
        $scopedFoo2 = $container->get('scoped_foo');

        $container->leaveScope('foo');
        $scoped4 = $container->get('scoped');
        $scopedFoo3 = $container->get('scoped_foo');

        $this->assertNotSame($scoped1, $scoped2);
        $this->assertSame($scoped2, $scoped3);
        $this->assertSame($scoped1, $scoped4);
        $this->assertNotSame($scopedFoo1, $scopedFoo2);
        $this->assertSame($scopedFoo1, $scopedFoo3);
    }

    public function testEnterLeaveScopeWithChildScopes()
    {
        $container = new Container();
        $container->addScope(new Scope('foo'));
        $container->addScope(new Scope('bar', 'foo'));

        $this->assertFalse($container->isScopeActive('foo'));

        $container->enterScope('foo');
        $container->enterScope('bar');

        $this->assertTrue($container->isScopeActive('foo'));
        $this->assertFalse($container->has('a'));

        $a = new \stdClass();
        $container->set('a', $a, 'bar');

        $services = $this->getField($container, 'scopedServices');
        $this->assertTrue(isset($services['bar']['a']));
        $this->assertSame($a, $services['bar']['a']);

        $this->assertTrue($container->has('a'));
        $container->leaveScope('foo');

        $services = $this->getField($container, 'scopedServices');
        $this->assertFalse(isset($services['bar']));

        $this->assertFalse($container->isScopeActive('foo'));
        $this->assertFalse($container->has('a'));
    }

    public function testEnterScopeRecursivelyWithInactiveChildScopes()
    {
        $container = new Container();
        $container->addScope(new Scope('foo'));
        $container->addScope(new Scope('bar', 'foo'));

        $this->assertFalse($container->isScopeActive('foo'));

        $container->enterScope('foo');

        $this->assertTrue($container->isScopeActive('foo'));
        $this->assertFalse($container->isScopeActive('bar'));
        $this->assertFalse($container->has('a'));

        $a = new \stdClass();
        $container->set('a', $a, 'foo');

        $services = $this->getField($container, 'scopedServices');
        $this->assertTrue(isset($services['foo']['a']));
        $this->assertSame($a, $services['foo']['a']);

        $this->assertTrue($container->has('a'));
        $container->enterScope('foo');

        $services = $this->getField($container, 'scopedServices');
        $this->assertFalse(isset($services['a']));

        $this->assertTrue($container->isScopeActive('foo'));
        $this->assertFalse($container->isScopeActive('bar'));
        $this->assertFalse($container->has('a'));
    }

    public function testLeaveScopeNotActive()
    {
        $container = new Container();
        $container->addScope(new Scope('foo'));

        try {
            $container->leaveScope('foo');
            $this->fail('->leaveScope() throws a \LogicException if the scope is not active yet');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope is not active yet');
            $this->assertEquals('The scope "foo" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope is not active yet');
        }

        try {
            $container->leaveScope('bar');
            $this->fail('->leaveScope() throws a \LogicException if the scope does not exist');
        } catch (\Exception $e) {
            $this->assertInstanceOf('\LogicException', $e, '->leaveScope() throws a \LogicException if the scope does not exist');
            $this->assertEquals('The scope "bar" is not active.', $e->getMessage(), '->leaveScope() throws a \LogicException if the scope does not exist');
        }
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getBuiltInScopes
     */
    public function testAddScopeDoesNotAllowBuiltInScopes($scope)
    {
        $container = new Container();
        $container->addScope(new Scope($scope));
    }

    /**
     * @expectedException \InvalidArgumentException
     */
    public function testAddScopeDoesNotAllowExistingScope()
    {
        $container = new Container();
        $container->addScope(new Scope('foo'));
        $container->addScope(new Scope('foo'));
    }

    /**
     * @expectedException \InvalidArgumentException
     * @dataProvider getInvalidParentScopes
     */
    public function testAddScopeDoesNotAllowInvalidParentScope($scope)
    {
        $c = new Container();
        $c->addScope(new Scope('foo', $scope));
    }

    public function testAddScope()
    {
        $c = new Container();
        $c->addScope(new Scope('foo'));
        $c->addScope(new Scope('bar', 'foo'));

        $this->assertSame(array('foo' => 'container', 'bar' => 'foo'), $this->getField($c, 'scopes'));
        $this->assertSame(array('foo' => array('bar'), 'bar' => array()), $this->getField($c, 'scopeChildren'));
    }

    public function testHasScope()
    {
        $c = new Container();

        $this->assertFalse($c->hasScope('foo'));
        $c->addScope(new Scope('foo'));
        $this->assertTrue($c->hasScope('foo'));
    }

    public function testIsScopeActive()
    {
        $c = new Container();

        $this->assertFalse($c->isScopeActive('foo'));
        $c->addScope(new Scope('foo'));

        $this->assertFalse($c->isScopeActive('foo'));
        $c->enterScope('foo');

        $this->assertTrue($c->isScopeActive('foo'));
        $c->leaveScope('foo');

        $this->assertFalse($c->isScopeActive('foo'));
    }

    public function testGetThrowsException()
    {
        $c = new ProjectServiceContainer();

        try {
            $c->get('throw_exception');
            $this->fail();
        } catch (\Exception $e) {
            $this->assertEquals('Something went terribly wrong!', $e->getMessage());
        }

        try {
            $c->get('throw_exception');
            $this->fail();
        } catch (\Exception $e) {
            $this->assertEquals('Something went terribly wrong!', $e->getMessage());
        }
    }

    public function testGetThrowsExceptionOnServiceConfiguration()
    {
        $c = new ProjectServiceContainer();

        try {
            $c->get('throws_exception_on_service_configuration');
            $this->fail('The container can not contain invalid service!');
        } catch (\Exception $e) {
            $this->assertEquals('Something was terribly wrong while trying to configure the service!', $e->getMessage());
        }
        $this->assertFalse($c->initialized('throws_exception_on_service_configuration'));

        try {
            $c->get('throws_exception_on_service_configuration');
            $this->fail('The container can not contain invalid service!');
        } catch (\Exception $e) {
            $this->assertEquals('Something was terribly wrong while trying to configure the service!', $e->getMessage());
        }
        $this->assertFalse($c->initialized('throws_exception_on_service_configuration'));
    }

    public function getInvalidParentScopes()
    {
        return array(
            array(ContainerInterface::SCOPE_PROTOTYPE),
            array('bar'),
        );
    }

    public function getBuiltInScopes()
    {
        return array(
            array(ContainerInterface::SCOPE_CONTAINER),
            array(ContainerInterface::SCOPE_PROTOTYPE),
        );
    }

    protected function getField($obj, $field)
    {
        $reflection = new \ReflectionProperty($obj, $field);
        $reflection->setAccessible(true);

        return $reflection->getValue($obj);
    }

    public function testAlias()
    {
        $c = new ProjectServiceContainer();

        $this->assertTrue($c->has('alias'));
        $this->assertSame($c->get('alias'), $c->get('bar'));
    }
}

class ProjectServiceContainer extends Container
{
    public $__bar, $__foo_bar, $__foo_baz;

    public function __construct()
    {
        parent::__construct();

        $this->__bar = new \stdClass();
        $this->__foo_bar = new \stdClass();
        $this->__foo_baz = new \stdClass();
        $this->aliases = array('alias' => 'bar');
    }

    protected function getScopedService()
    {
        if (!isset($this->scopedServices['foo'])) {
            throw new \RuntimeException('Invalid call');
        }

        return $this->services['scoped'] = $this->scopedServices['foo']['scoped'] = new \stdClass();
    }

    protected function getScopedFooService()
    {
        if (!isset($this->scopedServices['foo'])) {
            throw new \RuntimeException('invalid call');
        }

        return $this->services['scoped_foo'] = $this->scopedServices['foo']['scoped_foo'] = new \stdClass();
    }

    protected function getInactiveService()
    {
        throw new InactiveScopeException('request', 'request');
    }

    protected function getBarService()
    {
        return $this->__bar;
    }

    protected function getFooBarService()
    {
        return $this->__foo_bar;
    }

    protected function getFoo_BazService()
    {
        return $this->__foo_baz;
    }

    protected function getCircularService()
    {
        return $this->get('circular');
    }

    protected function getThrowExceptionService()
    {
        throw new \Exception('Something went terribly wrong!');
    }

    protected function getThrowsExceptionOnServiceConfigurationService()
    {
        $this->services['throws_exception_on_service_configuration'] = $instance = new \stdClass();

        throw new \Exception('Something was terribly wrong while trying to configure the service!');
    }
}
PKV1[`��=�	�	[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.phpnu�[���<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\DependencyInjection\Tests\Extension;

class ExtensionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getResolvedEnabledFixtures
     */
    public function testIsConfigEnabledReturnsTheResolvedValue($enabled)
    {
        $pb = $this->getMockBuilder('Symfony\Component\DependencyInjection\ParameterBag\ParameterBag')
            ->setMethods(array('resolveValue'))
            ->getMock()
        ;

        $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
            ->setMethods(array('getParameterBag'))
            ->getMock()
        ;

        $pb->expects($this->once())
            ->method('resolveValue')
            ->with($this->equalTo($enabled))
            ->will($this->returnValue($enabled))
        ;

        $container->expects($this->once())
            ->method('getParameterBag')
            ->will($this->returnValue($pb))
        ;

        $extension = $this->getMockBuilder('Symfony\Component\DependencyInjection\Extension\Extension')
            ->setMethods(array())
            ->getMockForAbstractClass()
        ;

        $r = new \ReflectionMethod('Symfony\Component\DependencyInjection\Extension\Extension', 'isConfigEnabled');
        $r->setAccessible(true);

        $r->invoke($extension, $container, array('enabled' => $enabled));
    }

    public function getResolvedEnabledFixtures()
    {
        return array(
            array(true),
            array(false)
        );
    }

    /**
     * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
     * @expectedExceptionMessage The config array has no 'enabled' key.
     */
    public function testIsConfigEnabledOnNonEnableableConfig()
    {
        $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')
            ->getMock()
        ;

        $extension = $this->getMockBuilder('Symfony\Component\DependencyInjection\Extension\Extension')
            ->setMethods(array())
            ->getMockForAbstractClass()
        ;

        $r = new \ReflectionMethod('Symfony\Component\DependencyInjection\Extension\Extension', 'isConfigEnabled');
        $r->setAccessible(true);

        $r->invoke($extension, $container, array());
    }
}
PKV1[���uuJDependencyInjection/Symfony/Component/DependencyInjection/phpunit.xml.distnu�[���<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         bootstrap="vendor/autoload.php"
>
    <testsuites>
        <testsuite name="Symfony DependencyInjection Component Test Suite">
            <directory>./Tests/</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist>
            <directory>./</directory>
            <exclude>
                <directory>./Resources</directory>
                <directory>./Tests</directory>
                <directory>./vendor</directory>
            </exclude>
        </whitelist>
    </filter>
</phpunit>
PK�R�Z�E[//__init__.pynu�[���PK�R�ZB�u�xx)j__pycache__/__init__.cpython-36.opt-2.pycnu�[���PK�R�ZB�u�xx#;__pycache__/__init__.cpython-36.pycnu�[���PK�R�ZB�u�xx)__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK�R�ZC敏.�.�support/__init__.pynu�[���PK�R�ZO?
�V�V�1�1support/__pycache__/__init__.cpython-36.opt-2.pycnu�[���PK�R�Z)$����6`support/__pycache__/script_helper.cpython-36.opt-2.pycnu�[���PK�R�Z� P

3�'support/__pycache__/testresult.cpython-36.opt-2.pycnu�[���PK�R�Z�N}���6)Fsupport/__pycache__/script_helper.cpython-36.opt-1.pycnu�[���PK�R�Z�N}���0Qbsupport/__pycache__/script_helper.cpython-36.pycnu�[���PK�R�Z�r�&XX-s~support/__pycache__/testresult.cpython-36.pycnu�[���PK�R�Z
�o��=�=+(�support/__pycache__/__init__.cpython-36.pycnu�[���PK�R�Z�r�&XX3F�support/__pycache__/testresult.cpython-36.opt-1.pycnu�[���PK�R�ZMhU-=-=1�support/__pycache__/__init__.cpython-36.opt-1.pycnu�[���PK�R�Z �~���7support/script_helper.pynu�[���PK�R�Z����

�Nsupport/testresult.pynu�[���PK�R�ZJ�[��htest_support.pyonu�[���PK�R�ZӨq�OOjtest_support.pynu�[���PK�R�Z�A?�||�j__init__.pyonu�[���PK�R�Z�GKF��ckscript_helper.pycnu�[���PK�R�Zg� 2))^lscript_helper.pynu�[���PK�R�Z��O�aa�lsupport/__init__.pyonu�[���PK�R�Z� �l�support/script_helper.pycnu�[���PK�R�Z�&�=��Ηsupport/__init__.pycnu�[���PK�R�Z;rq�##��support/script_helper.pyonu�[���PK�R�ZJ�[��test_support.pycnu�[���PK�R�Z�A?�||Q�__init__.pycnu�[���PK�R�Z�GKF��	�script_helper.pyonu�[���PK��Z����qtestroot/plugins.qmltypesnu�[���PK��Z�iU�33Q�qtestroot/qmldirnu�[���PK'/�Z��Mf}g}g��widget_tests.pyonu�[���PK'/�Z�T��++�1runtktests.pyonu�[���PK'/�Zש�mPmP�<widget_tests.pynu�[���PK'/�Z���66��READMEnu�[���PK'/�Z��Mf}g}g�widget_tests.pycnu�[���PK'/�Z�T��++��runtktests.pycnu�[���PK'/�Z�V�����(	test_ttk/test_widgets.pynu�[���PK'/�Z��	test_ttk/__init__.pynu�[���PK'/�Zž��'�'C�	test_ttk/test_extensions.pycnu�[���PK'/�Z�p���L
test_ttk/__init__.pyonu�[���PK'/�ZG����C�C
test_ttk/test_functions.pynu�[���PK'/�Z�d67�>�>&^
test_ttk/test_functions.pycnu�[���PK'/�Z@
S����
test_ttk/support.pycnu�[���PK'/�Zž��'�'3�
test_ttk/test_extensions.pyonu�[���PK'/�ZM,�7��<�
test_ttk/support.pynu�[���PK'/�Z�d67�>�>�
test_ttk/test_functions.pyonu�[���PK'/�ZB���,�,�'test_ttk/test_extensions.pynu�[���PK'/�Z@
S���Utest_ttk/support.pyonu�[���PK'/�Zܐ��bb>jtest_ttk/test_style.pynu�[���PK'/�Z8�����utest_ttk/test_widgets.pyonu�[���PK'/�ZM�3���gtest_ttk/test_style.pyonu�[���PK'/�Z�p����ttest_ttk/__init__.pycnu�[���PK'/�ZM�3���utest_ttk/test_style.pycnu�[���PK'/�Z8����߂test_ttk/test_widgets.pycnu�[���PK'/�Z�����
�t
runtktests.pynu�[���PK'/�Z�%��� � �}
test_tkinter/test_variables.pynu�[���PK(/�Z���*̞
test_tkinter/test_misc.pyonu�[���PK(/�Z���	�����
test_tkinter/test_widgets.pynu�[���PK(/�Z�ftest_tkinter/__init__.pynu�[���PK(/�Z0<4771gtest_tkinter/test_text.pycnu�[���PK(/�Z3��(4(4�ntest_tkinter/test_images.pynu�[���PK(/�ZT�D���%�test_tkinter/__init__.pyonu�[���PK(/�Z=���,�,��test_tkinter/test_variables.pyonu�[���PK(/�ZV�I����test_tkinter/test_font.pyonu�[���PK(/�ZV�I����test_tkinter/test_font.pycnu�[���PK(/�Z!=�޼��test_tkinter/test_text.pynu�[���PK(/�Z=���,�,��test_tkinter/test_variables.pycnu�[���PK(/�Z�K�w�w�&�+test_tkinter/test_geometry_managers.pynu�[���PK(/�Z�������test_tkinter/test_loadtk.pyonu�[���PK(/�Z6З����test_tkinter/test_loadtk.pynu�[���PK(/�Z�-�ԠԠ'��test_tkinter/test_geometry_managers.pycnu�[���PK(/�Zpr�����xtest_tkinter/test_font.pynu�[���PK(/�Z�3,O'>'>!�test_tkinter/test_images.pyonu�[���PK(/�Z�l����test_tkinter/test_widgets.pyonu�[���PK(/�Z������test_tkinter/test_loadtk.pycnu�[���PK(/�Z�-�ԠԠ'�test_tkinter/test_geometry_managers.pyonu�[���PK(/�Z�3,O'>'>6dtest_tkinter/test_images.pycnu�[���PK(/�Z��r����test_tkinter/test_misc.pynu�[���PK(/�Z���*��test_tkinter/test_misc.pycnu�[���PK(/�ZT�D�����test_tkinter/__init__.pycnu�[���PK(/�Z0<477��test_tkinter/test_text.pyonu�[���PK(/�Z�l��1�test_tkinter/test_widgets.pycnu�[���PK1[�1����0��Structures_LinkedList/tests/single_link_007.phptnu�[���PK1[�Z�x��0��Structures_LinkedList/tests/single_link_002.phptnu�[���PK1[(��  )��Structures_LinkedList/tests/link_004.phptnu�[���PK1[���|��0;�Structures_LinkedList/tests/SingleLinkTester.phpnu�[���PK1[髂[��0i�Structures_LinkedList/tests/single_link_006.phptnu�[���PK 1[s��DHH)��Structures_LinkedList/tests/link_007.phptnu�[���PK 1[�����)V�Structures_LinkedList/tests/link_005.phptnu�[���PK 1[�#,E��0��Structures_LinkedList/tests/single_link_005.phptnu�[���PK 1[����*��Structures_LinkedList/tests/LinkTester.phpnu�[���PK 1[� ���)�Structures_LinkedList/tests/link_001.phptnu�[���PK 1[骗���)F�Structures_LinkedList/tests/link_006.phptnu�[���PK 1[��)��)~�Structures_LinkedList/tests/link_002.phptnu�[���PK 1[�4����0z�Structures_LinkedList/tests/single_link_001.phptnu�[���PK 1[)�y--0��Structures_LinkedList/tests/single_link_004.phptnu�[���PK 1[�K��0O�Structures_LinkedList/tests/single_link_003.phptnu�[���PK 1[�o���)��Structures_LinkedList/tests/link_003.phptnu�[���PK 1[�x`(���Mail/tests/bug17317.phptnu�[���PK 1[��q/���Mail/tests/13659.phptnu�[���PK 1[�ó����Mail/tests/9137_2.phptnu�[���PK 1[w������Mail/tests/smtp_error.phptnu�[���PK 1[)f$�!!�
Mail/tests/rfc822.phptnu�[���PK 1[8x����TMail/tests/bug17178.phptnu�[���PK 1[*�����Mail/tests/9137.phptnu�[���PK 1[A�Finder/Symfony/Component/Finder/Tests/Fixtures/with space/foo.txtnu�[���PK!1[<Finder/Symfony/Component/Finder/Tests/Fixtures/A/B/C/abc.datnu�[���PK!1[9�Finder/Symfony/Component/Finder/Tests/Fixtures/A/B/ab.datnu�[���PK!1[6�Finder/Symfony/Component/Finder/Tests/Fixtures/A/a.datnu�[���PK!1[4YFinder/Symfony/Component/Finder/Tests/Fixtures/one/anu�[���PK!1[;�Finder/Symfony/Component/Finder/Tests/Fixtures/one/b/d.neonnu�[���PK!1[;(Finder/Symfony/Component/Finder/Tests/Fixtures/one/b/c.neonnu�[���PK!1[o�5|8�Finder/Symfony/Component/Finder/Tests/Fixtures/dolor.txtnu�[���PK!1['���))8Finder/Symfony/Component/Finder/Tests/Fixtures/ipsum.txtnu�[���PK!1[��558�Finder/Symfony/Component/Finder/Tests/Fixtures/lorem.txtnu�[���PK!1[@F Finder/Symfony/Component/Finder/Tests/Fixtures/copy/A/a.dat.copynu�[���PK!1[F� Finder/Symfony/Component/Finder/Tests/Fixtures/copy/A/B/C/abc.dat.copynu�[���PK!1[C,!Finder/Symfony/Component/Finder/Tests/Fixtures/copy/A/B/ab.dat.copynu�[���PK!1[˟�ׄ	�	G�!Finder/Symfony/Component/Finder/Tests/Comparator/DateComparatorTest.phpnu�[���PK!1[�W.�//I�+Finder/Symfony/Component/Finder/Tests/Comparator/NumberComparatorTest.phpnu�[���PK!1[��Ŗ�CB:Finder/Symfony/Component/Finder/Tests/Comparator/ComparatorTest.phpnu�[���PK!1[6G��mwmw4KBFinder/Symfony/Component/Finder/Tests/FinderTest.phpnu�[���PK!1[+드44G�Finder/Symfony/Component/Finder/Tests/Iterator/RealIteratorTestCase.phpnu�[���PK!1[:@���
�
H��Finder/Symfony/Component/Finder/Tests/Iterator/FilePathsIteratorTest.phpnu�[���PK!1[�qbe�
�
P&�Finder/Symfony/Component/Finder/Tests/Iterator/FilecontentFilterIteratorTest.phpnu�[���PK!1[Ybk�MMMA�Finder/Symfony/Component/Finder/Tests/Iterator/FileTypeFilterIteratorTest.phpnu�[���PK!1[���Ŋ�Q�Finder/Symfony/Component/Finder/Tests/Iterator/RecursiveDirectoryIteratorTest.phpnu�[���PK!1[4/aaU�Finder/Symfony/Component/Finder/Tests/Iterator/ExcludeDirectoryFilterIteratorTest.phpnu�[���PK!1[��nI��I��Finder/Symfony/Component/Finder/Tests/Iterator/PathFilterIteratorTest.phpnu�[���PK!1[��++QiFinder/Symfony/Component/Finder/Tests/Iterator/MultiplePcreFilterIteratorTest.phpnu�[���PK!1[�7Wa	a	G	Finder/Symfony/Component/Finder/Tests/Iterator/SortableIteratorTest.phpnu�[���PK!1[�7���M�Finder/Symfony/Component/Finder/Tests/Iterator/FilenameFilterIteratorTest.phpnu�[���PK!1[߫����KbFinder/Symfony/Component/Finder/Tests/Iterator/CustomFilterIteratorTest.phpnu�[���PK!1[��o�
�
B�Finder/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.phpnu�[���PK!1[Zo�*))O�,Finder/Symfony/Component/Finder/Tests/Iterator/DepthRangeFilterIteratorTest.phpnu�[���PK"1[�S�;�5Finder/Symfony/Component/Finder/Tests/Iterator/Iterator.phpnu�[���PK"1[���FN!:Finder/Symfony/Component/Finder/Tests/Iterator/SizeRangeFilterIteratorTest.phpnu�[���PK"1[-���66E�@Finder/Symfony/Component/Finder/Tests/Iterator/FilterIteratorTest.phpnu�[���PK"1[{�)\o	o	CJFFinder/Symfony/Component/Finder/Tests/Iterator/IteratorTestCase.phpnu�[���PK"1[�[+((G,PFinder/Symfony/Component/Finder/Tests/Iterator/MockFileListIterator.phpnu�[���PK"1[(��g==N�RFinder/Symfony/Component/Finder/Tests/Iterator/DateRangeFilterIteratorTest.phpnu�[���PK"1[�|ߐ�C�ZFinder/Symfony/Component/Finder/Tests/Expression/ExpressionTest.phpnu�[���PK"1[�9]��>�aFinder/Symfony/Component/Finder/Tests/Expression/RegexTest.phpnu�[���PK"1[7u��tt=�qFinder/Symfony/Component/Finder/Tests/Expression/GlobTest.phpnu�[���PK"1[`�2��ByxFinder/Symfony/Component/Finder/Tests/FakeAdapter/NamedAdapter.phpnu�[���PK"1[I����B�|Finder/Symfony/Component/Finder/Tests/FakeAdapter/DummyAdapter.phpnu�[���PK"1[/��00H#�Finder/Symfony/Component/Finder/Tests/FakeAdapter/UnsupportedAdapter.phpnu�[���PK"1[��mmD˄Finder/Symfony/Component/Finder/Tests/FakeAdapter/FailingAdapter.phpnu�[���PK"1[���550��Finder/Symfony/Component/Finder/phpunit.xml.distnu�[���PK"1[9���FA�TwigBridge/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.phpnu�[���PK#1[�O#�''J��TwigBridge/Symfony/Bridge/Twig/Tests/Node/SearchAndRenderBlockNodeTest.phpnu�[���PK#1[�h�H	H	;*�TwigBridge/Symfony/Bridge/Twig/Tests/Node/FormThemeTest.phpnu�[���PK#1[ͅi�997��TwigBridge/Symfony/Bridge/Twig/Tests/TwigEngineTest.phpnu�[���PK#1[k�K�\}�TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.phpnu�[���PK#1[¶
���O�TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.phpnu�[���PK#1[j|$		E��TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.phpnu�[���PK#1[�6��!!>��TwigBridge/Symfony/Bridge/Twig/Tests/NodeVisitor/ScopeTest.phpnu�[���PK#1[#�
�
M��TwigBridge/Symfony/Bridge/Twig/Tests/TokenParser/FormThemeTokenParserTest.phpnu�[���PK#1[��x��GTwigBridge/Symfony/Bridge/Twig/Tests/Extension/RoutingExtensionTest.phpnu�[���PK#1[:��WWODTwigBridge/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.phpnu�[���PK#1[t�9A
A
JTwigBridge/Symfony/Bridge/Twig/Tests/Extension/HttpKernelExtensionTest.phpnu�[���PK#1[�V�%33M�%TwigBridge/Symfony/Bridge/Twig/Tests/Extension/page_dynamic_extends.html.twignu�[���PK#1[�]��P�&TwigBridge/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.phpnu�[���PK#1[*��n**J)TwigBridge/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubTranslator.phpnu�[���PK#1[̙nsB�,TwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme_use.html.twignu�[���PK#1[�+����DI.TwigBridge/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.phpnu�[���PK#1[%o��	�	I�6TwigBridge/Symfony/Bridge/Twig/Tests/Extension/StopwatchExtensionTest.phpnu�[���PK#1[��ߋ��J�@TwigBridge/Symfony/Bridge/Twig/Tests/Extension/ExpressionExtensionTest.phpnu�[���PK#1[��,'KKE�DTwigBridge/Symfony/Bridge/Twig/Tests/Extension/parent_label.html.twignu�[���PK#1[�����K�ETwigBridge/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.phpnu�[���PK#1[(���>�cTwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme.html.twignu�[���PK$1[��i�!!M"eTwigBridge/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.phpnu�[���PK$1[Һ
�VVD�~TwigBridge/Symfony/Bridge/Twig/Tests/Extension/child_label.html.twignu�[���PK$1[�tdF�TwigBridge/Symfony/Bridge/Twig/Tests/Extension/theme_extends.html.twignu�[���PK$1[��b���G�TwigBridge/Symfony/Bridge/Twig/Tests/Extension/custom_widgets.html.twignu�[���PK$1[Pcc/5�TwigBridge/Symfony/Bridge/Twig/phpunit.xml.distnu�[���PK$1[h�9=UUJ��Translation/Symfony/Component/Translation/Tests/IdentityTranslatorTest.phpnu�[���PK$1[���*|1|1BƓTranslation/Symfony/Component/Translation/Tests/TranslatorTest.phpnu�[���PK$1[l.!���J��Translation/Symfony/Component/Translation/Tests/PluralizationRulesTest.phpnu�[���PK$1[�h�l��O�Translation/Symfony/Component/Translation/Tests/Catalogue/DiffOperationTest.phpnu�[���PK$1[$͒ϛ�P�Translation/Symfony/Component/Translation/Tests/Catalogue/MergeOperationTest.phpnu�[���PK$1[ײ�))S.�Translation/Symfony/Component/Translation/Tests/Catalogue/AbstractOperationTest.phpnu�[���PK$1[0�2��@��Translation/Symfony/Component/Translation/Tests/IntervalTest.phpnu�[���PK$1[��V��L��Translation/Symfony/Component/Translation/Tests/Dumper/IniFileDumperTest.phpnu�[���PK$1[`��׹�N	�Translation/Symfony/Component/Translation/Tests/Dumper/XliffFileDumperTest.phpnu�[���PK$1[����L@�Translation/Symfony/Component/Translation/Tests/Dumper/PhpFileDumperTest.phpnu�[���PK$1[����M\Translation/Symfony/Component/Translation/Tests/Dumper/YamlFileDumperTest.phpnu�[���PK$1[ub/��O|Translation/Symfony/Component/Translation/Tests/Dumper/IcuResFileDumperTest.phpnu�[���PK$1[�����L�	Translation/Symfony/Component/Translation/Tests/Dumper/CsvFileDumperTest.phpnu�[���PK%1[�����K�
Translation/Symfony/Component/Translation/Tests/Dumper/MoFileDumperTest.phpnu�[���PK%1[�BY���K�Translation/Symfony/Component/Translation/Tests/Dumper/QtFileDumperTest.phpnu�[���PK%1[��IIMTranslation/Symfony/Component/Translation/Tests/Dumper/JsonFileDumperTest.phpnu�[���PK%1[&��ݙ�K�Translation/Symfony/Component/Translation/Tests/Dumper/PoFileDumperTest.phpnu�[���PK%1[8^�k��N�Translation/Symfony/Component/Translation/Tests/Loader/XliffFileLoaderTest.phpnu�[���PK%1[��|=��K�.Translation/Symfony/Component/Translation/Tests/Loader/QtFileLoaderTest.phpnu�[���PK%1[���3L8Translation/Symfony/Component/Translation/Tests/Loader/LocalizedTestCase.phpnu�[���PK%1[���L�:Translation/Symfony/Component/Translation/Tests/Loader/PhpFileLoaderTest.phpnu�[���PK%1[~�		MCATranslation/Symfony/Component/Translation/Tests/Loader/YamlFileLoaderTest.phpnu�[���PK%1[�$X

K�JTranslation/Symfony/Component/Translation/Tests/Loader/PoFileLoaderTest.phpnu�[���PK%1[[����LjUTranslation/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.phpnu�[���PK%1[/�݂�L�]Translation/Symfony/Component/Translation/Tests/Loader/IniFileLoaderTest.phpnu�[���PK%1[��j��O�dTranslation/Symfony/Component/Translation/Tests/Loader/IcuResFileLoaderTest.phpnu�[���PK%1[P�e��M�kTranslation/Symfony/Component/Translation/Tests/Loader/JsonFileLoaderTest.phpnu�[���PK%1[����KQuTranslation/Symfony/Component/Translation/Tests/Loader/MoFileLoaderTest.phpnu�[���PK%1[�)�	�	�	O�}Translation/Symfony/Component/Translation/Tests/Loader/IcuDatFileLoaderTest.phpnu�[���PK%1[M��H�Translation/Symfony/Component/Translation/Tests/MessageCatalogueTest.phpnu�[���PK%1[���  G��Translation/Symfony/Component/Translation/Tests/MessageSelectorTest.phpnu�[���PK%1[��W44E6�Translation/Symfony/Component/Translation/Tests/fixtures/resources.monu�[���PK%1[!f����E߼Translation/Symfony/Component/Translation/Tests/fixtures/resources.ponu�[���PK%1[=BsM�Translation/Symfony/Component/Translation/Tests/fixtures/empty-translation.ponu�[���PK%1[Bu�Translation/Symfony/Component/Translation/Tests/fixtures/empty.ininu�[���PK%1[YڸCL�Translation/Symfony/Component/Translation/Tests/fixtures/resources-clean.xlfnu�[���PK%1[�:�++Ff�Translation/Symfony/Component/Translation/Tests/fixtures/resources.phpnu�[���PK%1[B�Translation/Symfony/Component/Translation/Tests/fixtures/empty.ymlnu�[���PK%1[Cy�Translation/Symfony/Component/Translation/Tests/fixtures/empty.jsonnu�[���PK%1[Y���44D��Translation/Symfony/Component/Translation/Tests/fixtures/resname.xlfnu�[���PK%1[B��Translation/Symfony/Component/Translation/Tests/fixtures/empty.xlfnu�[���PK%1[;.�BBC�Translation/Symfony/Component/Translation/Tests/fixtures/plurals.ponu�[���PK%1[�ߞG��Translation/Symfony/Component/Translation/Tests/fixtures/malformed.jsonnu�[���PK%1[�.�zzFH�Translation/Symfony/Component/Translation/Tests/fixtures/resources.xlfnu�[���PK%1[�e2~F8�Translation/Symfony/Component/Translation/Tests/fixtures/non-valid.ymlnu�[���PK%1[�'�F

F��Translation/Symfony/Component/Translation/Tests/fixtures/resources.ininu�[���PK%1[� TTF2�Translation/Symfony/Component/Translation/Tests/fixtures/non-valid.xlfnu�[���PK%1[A��Translation/Symfony/Component/Translation/Tests/fixtures/empty.ponu�[���PK%1[Bm�Translation/Symfony/Component/Translation/Tests/fixtures/empty.csvnu�[���PK%1[*֔�JJC��Translation/Symfony/Component/Translation/Tests/fixtures/plurals.monu�[���PK%1[+�L�TTR��Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/res/en.resnu�[���PK%1[w˦(||Rr�Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/fr.resnu�[���PK%1[X��**Rp�Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/fr.txtnu�[���PK%1[rQ�``Y�Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/resources.datnu�[���PK%1[�M�RxxR�Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/en.resnu�[���PK&1[�g.�[��Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/packagelist.txtnu�[���PK&1[�25�''R��Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/dat/en.txtnu�[���PK&1[��<�_A�Translation/Symfony/Component/Translation/Tests/fixtures/resourcebundle/corrupted/resources.datnu�[���PK&1[A��Translation/Symfony/Component/Translation/Tests/fixtures/empty.monu�[���PK&1[��jjHD�Translation/Symfony/Component/Translation/Tests/fixtures/withdoctype.xlfnu�[���PK&1[̉^2��E&�Translation/Symfony/Component/Translation/Tests/fixtures/encoding.xlfnu�[���PK&1[�B$$Bh�Translation/Symfony/Component/Translation/Tests/fixtures/valid.csvnu�[���PK&1[����G��Translation/Symfony/Component/Translation/Tests/fixtures/resources.jsonnu�[���PK&1[�C(���E��Translation/Symfony/Component/Translation/Tests/fixtures/resources.tsnu�[���PK&1[/�
��R��Translation/Symfony/Component/Translation/Tests/fixtures/invalid-xml-resources.xlfnu�[���PK&1[���		F0�Translation/Symfony/Component/Translation/Tests/fixtures/resources.ymlnu�[���PK&1[�D��``F��Translation/Symfony/Component/Translation/Tests/fixtures/resources.csvnu�[���PK&1[^C�	:::��Translation/Symfony/Component/Translation/phpunit.xml.distnu�[���PK&1[���LL@)�Routing/Symfony/Component/Routing/Tests/Annotation/RouteTest.phpnu�[���PK&1[�%��])])=��Routing/Symfony/Component/Routing/Tests/RouteCompilerTest.phpnu�[���PK&1[1�d	nnH�Routing/Symfony/Component/Routing/Tests/Fixtures/CustomXmlFileLoader.phpnu�[���PK&1[>�Routing/Symfony/Component/Routing/Tests/Fixtures/annotated.phpnu�[���PK&1[:Routing/Symfony/Component/Routing/Tests/Fixtures/empty.ymlnu�[���PK&1[�/���AmRouting/Symfony/Component/Routing/Tests/Fixtures/validpattern.ymlnu�[���PK&1[�M��A�Routing/Symfony/Component/Routing/Tests/Fixtures/validpattern.xmlnu�[���PK&1[�/�$>>Q�!Routing/Symfony/Component/Routing/Tests/Fixtures/nonesense_resource_plus_path.ymlnu�[���PK&1[��==A�"Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalidkeys.ymlnu�[���PK&1[�ie��DX#Routing/Symfony/Component/Routing/Tests/Fixtures/namespaceprefix.xmlnu�[���PK&1[#q��//?�&Routing/Symfony/Component/Routing/Tests/Fixtures/missing_id.xmlnu�[���PK&1[x'�	11@((Routing/Symfony/Component/Routing/Tests/Fixtures/withdoctype.xmlnu�[���PK&1[�;h�%%K�(Routing/Symfony/Component/Routing/Tests/Fixtures/RedirectableUrlMatcher.phpnu�[���PK&1[s��[//Ai,Routing/Symfony/Component/Routing/Tests/Fixtures/missing_path.xmlnu�[���PK'1[�e2~=	.Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid.ymlnu�[���PK'1[ix��77Az.Routing/Symfony/Component/Routing/Tests/Fixtures/validpattern.phpnu�[���PK'1[�G�V,+,+H"2Routing/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.phpnu�[���PK'1[T����H�]Routing/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher3.phpnu�[���PK'1[@4��K�cRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher1.apachenu�[���PK'1[Bx�6��KqzRouting/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.apachenu�[���PK'1[n�k�//H�{Routing/Symfony/Component/Routing/Tests/Fixtures/dumper/url_matcher2.phpnu�[���PK'1[�p��=0�Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid.xmlnu�[���PK'1[ͼ�n!!Ae�Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalidnode.xmlnu�[���PK'1[T��N��Routing/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/BarClass.phpnu�[���PK'1[���GGN!�Routing/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/FooClass.phpnu�[���PK'1[�zUUS�Routing/Symfony/Component/Routing/Tests/Fixtures/AnnotatedClasses/AbstractClass.phpnu�[���PK'1[�M�t>��Routing/Symfony/Component/Routing/Tests/Fixtures/nonvalid2.ymlnu�[���PK'1[�b�B:�Routing/Symfony/Component/Routing/Tests/Fixtures/validresource.xmlnu�[���PK'1[��q�BǷRouting/Symfony/Component/Routing/Tests/Fixtures/nonvalidroute.xmlnu�[���PK'1[��ϮBB?U�Routing/Symfony/Component/Routing/Tests/Fixtures/incomplete.ymlnu�[���PK'1[�J?�G�Routing/Symfony/Component/Routing/Tests/Fixtures/special_route_name.ymlnu�[���PK(1[�q�99T��Routing/Symfony/Component/Routing/Tests/Fixtures/nonesense_type_without_resource.ymlnu�[���PK(1[jX���BY�Routing/Symfony/Component/Routing/Tests/Fixtures/validresource.ymlnu�[���PK(1[9��Routing/Symfony/Component/Routing/Tests/Fixtures/foo1.xmlnu�[���PK(1[8'�Routing/Symfony/Component/Routing/Tests/Fixtures/foo.xmlnu�[���PK(1[��/��
�
>��Routing/Symfony/Component/Routing/Tests/RequestContextTest.phpnu�[���PK(1[���
�
K��Routing/Symfony/Component/Routing/Tests/Matcher/TraceableUrlMatcherTest.phpnu�[���PK(1[t�kT�B�BB��Routing/Symfony/Component/Routing/Tests/Matcher/UrlMatcherTest.phpnu�[���PK(1[ȁ@���UDRouting/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperPrefixCollectionTest.phpnu�[���PK(1[)�#0%%O�.Routing/Symfony/Component/Routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.phpnu�[���PK(1[U���OTRouting/Symfony/Component/Routing/Tests/Matcher/Dumper/DumperCollectionTest.phpnu�[���PK(1[�IQ��R^WRouting/Symfony/Component/Routing/Tests/Matcher/Dumper/ApacheMatcherDumperTest.phpnu�[���PK(1[�̼�aaH�qRouting/Symfony/Component/Routing/Tests/Matcher/ApacheUrlMatcherTest.phpnu�[���PK(1[A ���N��Routing/Symfony/Component/Routing/Tests/Matcher/RedirectableUrlMatcherTest.phpnu�[���PK(1[%"�?7?7?ÎRouting/Symfony/Component/Routing/Tests/RouteCollectionTest.phpnu�[���PK(1[ kl�g�gFq�Routing/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.phpnu�[���PK(1[������S�.Routing/Symfony/Component/Routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.phpnu�[���PK(1[8!!&GG=?Routing/Symfony/Component/Routing/Tests/CompiledRouteTest.phpnu�[���PK(1[���k��D�CRouting/Symfony/Component/Routing/Tests/Loader/ClosureLoaderTest.phpnu�[���PK(1[�����L�IRouting/Symfony/Component/Routing/Tests/Loader/AnnotationClassLoaderTest.phpnu�[���PK(1[g�U��D>]Routing/Symfony/Component/Routing/Tests/Loader/PhpFileLoaderTest.phpnu�[���PK(1[{��t��EjeRouting/Symfony/Component/Routing/Tests/Loader/YamlFileLoaderTest.phpnu�[���PK(1[6����P`wRouting/Symfony/Component/Routing/Tests/Loader/AnnotationDirectoryLoaderTest.phpnu�[���PK(1[M�~�##D�~Routing/Symfony/Component/Routing/Tests/Loader/XmlFileLoaderTest.phpnu�[���PK(1[|�C44O!�Routing/Symfony/Component/Routing/Tests/Loader/AbstractAnnotationLoaderTest.phpnu�[���PK(1[u��;KԖRouting/Symfony/Component/Routing/Tests/Loader/AnnotationFileLoaderTest.phpnu�[���PK(1[��6O�Routing/Symfony/Component/Routing/Tests/RouterTest.phpnu�[���PK(1[u��A�,�,5бRouting/Symfony/Component/Routing/Tests/RouteTest.phpnu�[���PK(1[~�662�Routing/Symfony/Component/Routing/phpunit.xml.distnu�[���PK)1[��W8j#j#)��Structures_Graph/tests/BasicGraphTest.phpnu�[���PK)1[6��:UU0qStructures_Graph/tests/TopologicalSorterTest.phpnu�[���PK)1[�V���#&Structures_Graph/tests/AllTests.phpnu�[���PK)1[���*5Structures_Graph/tests/AcyclicTestTest.phpnu�[���PK)1[a�[ii!�Structures_Graph/tests/helper.incnu�[���PK)1[��+\MMCeProcess/Symfony/Component/Process/Tests/PhpExecutableFinderTest.phpnu�[���PK)1[#�O%Process/Symfony/Component/Process/Tests/PipeStdinInStdoutStdErrStreamSelect.phpnu�[���PK)1[�WKo�
�
F�%Process/Symfony/Component/Process/Tests/ProcessFailedExceptionTest.phpnu�[���PK)1[C�u^UU<�0Process/Symfony/Component/Process/Tests/ProcessUtilsTest.phpnu�[���PK)1[[�VAChCh?t6Process/Symfony/Component/Process/Tests/AbstractProcessTest.phpnu�[���PK)1[=�,j��:&�Process/Symfony/Component/Process/Tests/SignalListener.phpnu�[���PK)1[���
��=��Process/Symfony/Component/Process/Tests/SimpleProcessTest.phpnu�[���PK)1[�+�v,,>�Process/Symfony/Component/Process/Tests/NonStopableProcess.phpnu�[���PK)1[m�����H��Process/Symfony/Component/Process/Tests/ProcessInSigchildEnvironment.phpnu�[���PK)1[����G˿Process/Symfony/Component/Process/Tests/SigchildDisabledProcessTest.phpnu�[���PK)1[H��spp>��Process/Symfony/Component/Process/Tests/ProcessBuilderTest.phpnu�[���PK)1[x[��:�Process/Symfony/Component/Process/Tests/PhpProcessTest.phpnu�[���PK)1[钊�\\F�Process/Symfony/Component/Process/Tests/SigchildEnabledProcessTest.phpnu�[���PK)1[p\H2�Process/Symfony/Component/Process/phpunit.xml.distnu�[���PK*1[2�c�$�$@Serializer/Symfony/Component/Serializer/Tests/SerializerTest.phpnu�[���PK*1[�m�))KF5Serializer/Symfony/Component/Serializer/Tests/Normalizer/TestNormalizer.phpnu�[���PK*1[$ѕ�Q�8Serializer/Symfony/Component/Serializer/Tests/Normalizer/CustomNormalizerTest.phpnu�[���PK*1[��P1!!W�ASerializer/Symfony/Component/Serializer/Tests/Normalizer/GetSetMethodNormalizerTest.phpnu�[���PK*1[�qBBMcSerializer/Symfony/Component/Serializer/Tests/Normalizer/TestDenormalizer.phpnu�[���PK*1[��K�__F�fSerializer/Symfony/Component/Serializer/Tests/Fixtures/ScalarDummy.phpnu�[���PK*1[��_��K�kSerializer/Symfony/Component/Serializer/Tests/Fixtures/TraversableDummy.phpnu�[���PK*1[G��5��W&nSerializer/Symfony/Component/Serializer/Tests/Fixtures/NormalizableTraversableDummy.phpnu�[���PK*1[�LY��@0sSerializer/Symfony/Component/Serializer/Tests/Fixtures/Dummy.phpnu�[���PK*1[Y["�uuN�xSerializer/Symfony/Component/Serializer/Tests/Fixtures/DenormalizableDummy.phpnu�[���PK*1[f|�B.B.H~{Serializer/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.phpnu�[���PK*1[F��		I8�Serializer/Symfony/Component/Serializer/Tests/Encoder/JsonEncoderTest.phpnu�[���PK*1[���998��Serializer/Symfony/Component/Serializer/phpunit.xml.distnu�[���PK+1[�Ǫ���4W�Locale/Symfony/Component/Locale/Tests/LocaleTest.phpnu�[���PK+1[<��=S�Locale/Symfony/Component/Locale/Tests/Stub/StubLocaleTest.phpnu�[���PK+1[+��hh0��Locale/Symfony/Component/Locale/phpunit.xml.distnu�[���PK+1[�;�D��Filesystem/Symfony/Component/Filesystem/Tests/FilesystemTestCase.phpnu�[���PK+1['B 0�o�o@�Filesystem/Symfony/Component/Filesystem/Tests/FilesystemTest.phpnu�[���PK+1[��í�?EGFilesystem/Symfony/Component/Filesystem/Tests/ExceptionTest.phpnu�[���PK+1[�Ejc		85MFilesystem/Symfony/Component/Filesystem/phpunit.xml.distnu�[���PK+1[�ag�@<@<=�PForm/Symfony/Component/Form/Tests/AbstractTableLayoutTest.phpnu�[���PK+1[���KK=S�Form/Symfony/Component/Form/Tests/FormPerformanceTestCase.phpnu�[���PK+1[@U���8�Form/Symfony/Component/Form/Tests/AbstractLayoutTest.phpnu�[���PK+1[����5xsForm/Symfony/Component/Form/Tests/Guess/GuessTest.phpnu�[���PK+1[�u@zwForm/Symfony/Component/Form/Tests/Fixtures/CustomArrayObject.phpnu�[���PK+1[�x���5~Form/Symfony/Component/Form/Tests/Fixtures/Author.phpnu�[���PK+1[.U�Form/Symfony/Component/Form/Tests/Fixtures/foonu�[���PK+1[[��َ�B��Form/Symfony/Component/Form/Tests/Fixtures/FooTypeBazExtension.phpnu�[���PK+1[���*��6��Form/Symfony/Component/Form/Tests/Fixtures/FooType.phpnu�[���PK+1[:�.z��A
�Form/Symfony/Component/Form/Tests/Fixtures/AlternatingRowType.phpnu�[���PK+1[֫�v��9z�Form/Symfony/Component/Form/Tests/Fixtures/AuthorType.phpnu�[���PK+1[#�o9��Form/Symfony/Component/Form/Tests/Fixtures/FooSubType.phpnu�[���PK+1[��8���<�Form/Symfony/Component/Form/Tests/Fixtures/TestExtension.phpnu�[���PK+1[��x�

B)�Form/Symfony/Component/Form/Tests/Fixtures/FooTypeBarExtension.phpnu�[���PK+1[m^�2++K��Form/Symfony/Component/Form/Tests/Fixtures/FooSubTypeWithParentInstance.phpnu�[���PK+1[��!u��BN�Form/Symfony/Component/Form/Tests/Fixtures/FixedFilterListener.phpnu�[���PK+1[Ų��UUCV�Form/Symfony/Component/Form/Tests/Fixtures/FixedDataTransformer.phpnu�[���PK+1[J����R�R5�Form/Symfony/Component/Form/Tests/FormFactoryTest.phpnu�[���PK+1[ȔfVA6A6=(Form/Symfony/Component/Form/Tests/Util/OrderedHashMapTest.phpnu�[���PK+1[�z�nznz6�7Form/Symfony/Component/Form/Tests/CompoundFormTest.phpnu�[���PK+1[���d<��Form/Symfony/Component/Form/Tests/FormFactoryBuilderTest.phpnu�[���PK+1[̈́����6�Form/Symfony/Component/Form/Tests/FormRegistryTest.phpnu�[���PK+1[]�9�}}4h�Form/Symfony/Component/Form/Tests/FormConfigTest.phpnu�[���PK+1[�>)�bb@I�Form/Symfony/Component/Form/Tests/AbstractRequestHandlerTest.phpnu�[���PK+1[ū@d22:
 Form/Symfony/Component/Form/Tests/ResolvedFormTypeTest.phpnu�[���PK+1[O� )KK=�< Form/Symfony/Component/Form/Tests/FormIntegrationTestCase.phpnu�[���PK+1[��K)ooAQ? Form/Symfony/Component/Form/Tests/CompoundFormPerformanceTest.phpnu�[���PK+1[tٴ��61E Form/Symfony/Component/Form/Tests/FormRendererTest.phpnu�[���PK+1[�d�!!>qH Form/Symfony/Component/Form/Tests/NativeRequestHandlerTest.phpnu�[���PK+1[�����5` Form/Symfony/Component/Form/Tests/FormBuilderTest.phpnu�[���PK+1[RmhZTZT;8| Form/Symfony/Component/Form/Tests/AbstractDivLayoutTest.phpnu�[���PK+1[k/66�� Form/Symfony/Component/Form/Tests/AbstractFormTest.phpnu�[���PK+1[rM�{�{4x� Form/Symfony/Component/Form/Tests/SimpleFormTest.phpnu�[���PK,1[ۿt��^�Y!Form/Symfony/Component/Form/Tests/Extension/Validator/EventListener/ValidationListenerTest.phpnu�[���PK,1[�EY޵�O�m!Form/Symfony/Component/Form/Tests/Extension/Validator/Util/ServerParamsTest.phpnu�[���PK,1[�l"�	�	R%t!Form/Symfony/Component/Form/Tests/Extension/Validator/ValidatorTypeGuesserTest.phpnu�[���PK,1[��
b8~!Form/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorPerformanceTest.phpnu�[���PK,1[ِ�GbGbW�!Form/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorTest.phpnu�[���PK,1[�$�Ǵ�[��!Form/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationPathTest.phpnu�[���PK,1[�@1�,�,]�"Form/Symfony/Component/Form/Tests/Extension/Validator/ViolationMapper/ViolationMapperTest.phpnu�[���PK,1[`f�[��K2$Form/Symfony/Component/Form/Tests/Extension/Validator/Type/TypeTestCase.phpnu�[���PK,1[Y��
xxYN8$Form/Symfony/Component/Form/Tests/Extension/Validator/Type/BaseValidatorExtensionTest.phpnu�[���PK,1[S�m�_OA$Form/Symfony/Component/Form/Tests/Extension/Validator/Type/SubmitTypeValidatorExtensionTest.phpnu�[���PK,1[7>lˉ�]�C$Form/Symfony/Component/Form/Tests/Extension/Validator/Type/FormTypeValidatorExtensionTest.phpnu�[���PK,1[1���� � d�H$Form/Symfony/Component/Form/Tests/Extension/HttpFoundation/EventListener/BindRequestListenerTest.phpnu�[���PK,1[f͍ff_?j$Form/Symfony/Component/Form/Tests/Extension/HttpFoundation/HttpFoundationRequestHandlerTest.phpnu�[���PK,1[%u����Y4q$Form/Symfony/Component/Form/Tests/Extension/Csrf/CsrfProvider/SessionCsrfProviderTest.phpnu�[���PK,1[_Nn���YAy$Form/Symfony/Component/Form/Tests/Extension/Csrf/CsrfProvider/DefaultCsrfProviderTest.phpnu�[���PK,1[�A��]��$Form/Symfony/Component/Form/Tests/Extension/Csrf/EventListener/CsrfValidationListenerTest.phpnu�[���PK,1[�L?��.�.S�$Form/Symfony/Component/Form/Tests/Extension/Csrf/Type/FormTypeCsrfExtensionTest.phpnu�[���PK-1[��܏##Ro�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/Fixtures/randomhashnu�[���PK-1[��**\�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/FixRadioInputListenerTest.phpnu�[���PK-1[��!��$�$Y��$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.phpnu�[���PK-1[fk5s3	3	S;�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/TrimListenerTest.phpnu�[���PK-1[B+�K��i�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayObjectTest.phpnu�[���PK-1[�@ڦo5�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerCustomArrayObjectTest.phpnu�[���PK-1[Э
���c�$Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerArrayTest.phpnu�[���PK-1[��gg]%Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/FixUrlProtocolListenerTest.phpnu�[���PK-1[�O�&^%Form/Symfony/Component/Form/Tests/Extension/Core/EventListener/MergeCollectionListenerTest.phpnu�[���PK-1[���� � T�&%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/ObjectChoiceListTest.phpnu�[���PK-1[�.�p))N+H%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/ChoiceListTest.phpnu�[���PK-1[�![���V�\%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/AbstractChoiceListTest.phpnu�[���PK-1[�gUI��R/|%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/LazyChoiceListTest.phpnu�[���PK-1[R��
�
TV�%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/SimpleChoiceListTest.phpnu�[���PK-1[��x��[\�%Form/Symfony/Component/Form/Tests/Extension/Core/ChoiceList/SimpleNumericChoiceListTest.phpnu�[���PK-1[?�R8�.�.V��%Form/Symfony/Component/Form/Tests/Extension/Core/DataMapper/PropertyPathMapperTest.phpnu�[���PK-1[���4��a�%Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoiceToValueTransformerTest.phpnu�[���PK-1[�����lD�%Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/PercentToLocalizedStringTransformerTest.phpnu�[���PK-1[Ws�**m�%Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToLocalizedStringTransformerTest.phpnu�[���PK-1[�Ub,,U1&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeTestCase.phpnu�[���PK-1[�}��!
!
g�&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToTimestampTransformerTest.phpnu�[���PK-1[��=�C?C?c�!&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToArrayTransformerTest.phpnu�[���PK-1[���`pa&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ArrayToPartsTransformerTest.phpnu�[���PK-1[\R��]p&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DataTransformerChainTest.phpnu�[���PK-1[�6���cy&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BooleanToStringTransformerTest.phpnu�[���PK-1[Y@zjjjO�&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/MoneyToLocalizedStringTransformerTest.phpnu�[���PK-1[]e"��eS�&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToRfc3339TransformerTest.phpnu�[���PK-1[N�z.z.lt�&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/IntegerToLocalizedStringTransformerTest.phpnu�[���PK-1[��`nonok��&Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/NumberToLocalizedStringTransformerTest.phpnu�[���PK-1[�?+�<<e�;'Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ValueToDuplicatesTransformerTest.phpnu�[���PK-1[fJ��`dG'Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/BaseDateTimeTransformerTest.phpnu�[���PK-1[�.bc))c�L'Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/ChoicesToValuesTransformerTest.phpnu�[���PK-1[JW����d�U'Form/Symfony/Component/Form/Tests/Extension/Core/DataTransformer/DateTimeToStringTransformerTest.phpnu�[���PK-1[��W@@J;p'Form/Symfony/Component/Form/Tests/Extension/Core/Type/LanguageTypeTest.phpnu�[���PK.1[x���aaH�v'Form/Symfony/Component/Form/Tests/Extension/Core/Type/LocaleTypeTest.phpnu�[���PK.1[�C���H�{'Form/Symfony/Component/Form/Tests/Extension/Core/Type/ButtonTypeTest.phpnu�[���PK.1[�'�\�\F�~'Form/Symfony/Component/Form/Tests/Extension/Core/Type/DateTypeTest.phpnu�[���PK.1[vzw�LLL��'Form/Symfony/Component/Form/Tests/Extension/Core/Type/CollectionTypeTest.phpnu�[���PK.1[�(��__J��'Form/Symfony/Component/Form/Tests/Extension/Core/Type/PasswordTypeTest.phpnu�[���PK.1[x�=�t=t=J`�'Form/Symfony/Component/Form/Tests/Extension/Core/Type/DateTimeTypeTest.phpnu�[���PK.1[P�!���EN:(Form/Symfony/Component/Form/Tests/Extension/Core/Type/UrlTypeTest.phpnu�[���PK.1[X�:::F�A(Form/Symfony/Component/Form/Tests/Extension/Core/Type/TypeTestCase.phpnu�[���PK.1[����I3D(Form/Symfony/Component/Form/Tests/Extension/Core/Type/CountryTypeTest.phpnu�[���PK.1[�_*G��SDK(Form/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypePerformanceTest.phpnu�[���PK.1[�{MK��F�O(Form/Symfony/Component/Form/Tests/Extension/Core/Type/BaseTypeTest.phpnu�[���PK.1[ސ/���J�a(Form/Symfony/Component/Form/Tests/Extension/Core/Type/TimezoneTypeTest.phpnu�[���PK.1[dwҢSJSJFf(Form/Symfony/Component/Form/Tests/Extension/Core/Type/TimeTypeTest.phpnu�[���PK.1[/����Gٰ(Form/Symfony/Component/Form/Tests/Extension/Core/Type/MoneyTypeTest.phpnu�[���PK.1[���J��H$�(Form/Symfony/Component/Form/Tests/Extension/Core/Type/NumberTypeTest.phpnu�[���PK.1[�}�C%%H��(Form/Symfony/Component/Form/Tests/Extension/Core/Type/SubmitTypeTest.phpnu�[���PK.1[�!]i00J-�(Form/Symfony/Component/Form/Tests/Extension/Core/Type/CurrencyTypeTest.phpnu�[���PK.1[�IJ��J��(Form/Symfony/Component/Form/Tests/Extension/Core/Type/CheckboxTypeTest.phpnu�[���PK/1[�ñI��J�(Form/Symfony/Component/Form/Tests/Extension/Core/Type/RepeatedTypeTest.phpnu�[���PK/1[k�ƅ��I<�(Form/Symfony/Component/Form/Tests/Extension/Core/Type/IntegerTypeTest.phpnu�[���PK/1[I��E����H��(Form/Symfony/Component/Form/Tests/Extension/Core/Type/ChoiceTypeTest.phpnu�[���PK/1[�jGgJgJF֙)Form/Symfony/Component/Form/Tests/Extension/Core/Type/FormTypeTest.phpnu�[���PK/1[&����F��)Form/Symfony/Component/Form/Tests/Extension/Core/Type/FileTypeTest.phpnu�[���PK/1[����>�>S�)Form/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataCollectorTest.phpnu�[���PK/1[b�,�<<X�-*Form/Symfony/Component/Form/Tests/Extension/DataCollector/DataCollectorExtensionTest.phpnu�[���PK/1[�{�(�,�,SN3*Form/Symfony/Component/Form/Tests/Extension/DataCollector/FormDataExtractorTest.phpnu�[���PK/1[��q��a�`*Form/Symfony/Component/Form/Tests/Extension/DataCollector/Type/DataCollectorTypeExtensionTest.phpnu�[���PK/1[�'�;�f*Form/Symfony/Component/Form/Tests/AbstractExtensionTest.phpnu�[���PK/1[�g	�33,Mk*Form/Symfony/Component/Form/phpunit.xml.distnu�[���PK/1[�ԍZP5P5D�n*Security/Symfony/Component/Security/Acl/Tests/Voter/AclVoterTest.phpnu�[���PK/1[�޻>�Q�QM��*Security/Symfony/Component/Security/Acl/Tests/Dbal/MutableAclProviderTest.phpnu�[���PK/1[�
�� � O��*Security/Symfony/Component/Security/Acl/Tests/Dbal/AclProviderBenchmarkTest.phpnu�[���PK/1[�'(��'�'F�+Security/Symfony/Component/Security/Acl/Tests/Dbal/AclProviderTest.phpnu�[���PK01[�ˆ5H@+Security/Symfony/Component/Security/Acl/Tests/Domain/AuditLoggerTest.phpnu�[���PK01[6x�}&&G�H+Security/Symfony/Component/Security/Acl/Tests/Domain/FieldEntryTest.phpnu�[���PK01[��+&K6Q+Security/Symfony/Component/Security/Acl/Tests/Domain/ObjectIdentityTest.phpnu�[���PK01[_�~��\�`+Security/Symfony/Component/Security/Acl/Tests/Domain/ObjectIdentityRetrievalStrategyTest.phpnu�[���PK01[��HHM�e+Security/Symfony/Component/Security/Acl/Tests/Domain/DoctrineAclCacheTest.phpnu�[���PK01[��v��W�r+Security/Symfony/Component/Security/Acl/Tests/Domain/PermissionGrantingStrategyTest.phpnu�[���PK01[/bAbA@#�+Security/Symfony/Component/Security/Acl/Tests/Domain/AclTest.phpnu�[���PK01[5�Q��+Security/Symfony/Component/Security/Acl/Tests/Domain/RoleSecurityIdentityTest.phpnu�[���PK01[��a((Q��+Security/Symfony/Component/Security/Acl/Tests/Domain/UserSecurityIdentityTest.phpnu�[���PK01[�am��^��+Security/Symfony/Component/Security/Acl/Tests/Domain/SecurityIdentityRetrievalStrategyTest.phpnu�[���PK01[F��@�
�
B��+Security/Symfony/Component/Security/Acl/Tests/Domain/EntryTest.phpnu�[���PK01[���yyS�,Security/Symfony/Component/Security/Acl/Tests/Permission/BasicPermissionMapTest.phpnu�[���PK01[eE���L�,Security/Symfony/Component/Security/Acl/Tests/Permission/MaskBuilderTest.phpnu�[���PK01[ܲ#&;;8",Security/Symfony/Component/Security/Acl/phpunit.xml.distnu�[���PK01[C��)!"!"Q�,Security/Symfony/Component/Security/Tests/Http/Firewall/ExceptionListenerTest.phpnu�[���PK01[s�f�[[GgB,Security/Symfony/Component/Security/Tests/Core/User/UserCheckerTest.phpnu�[���PK01[����!!P9R,Security/Symfony/Component/Security/Tests/Core/User/InMemoryUserProviderTest.phpnu�[���PK01[2�nBB[�Y,Security/Symfony/Component/Security/Tests/Core/Authentication/Token/RememberMeTokenTest.phpnu�[���PK01[9�#�		4�b,Security/Symfony/Component/Security/phpunit.xml.distnu�[���PK01[g3�%%?g,Security/Symfony/Component/Security/Http/Tests/FirewallTest.phpnu�[���PK11[��+MbbB�v,Security/Symfony/Component/Security/Http/Tests/FirewallMapTest.phpnu�[���PK11[����%�%@|�,Security/Symfony/Component/Security/Http/Tests/HttpUtilsTest.phpnu�[���PK11[�ck�~
~
^m�,Security/Symfony/Component/Security/Http/Tests/EntryPoint/FormAuthenticationEntryPointTest.phpnu�[���PK11[e���_y�,Security/Symfony/Component/Security/Http/Tests/EntryPoint/BasicAuthenticationEntryPointTest.phpnu�[���PK11[-Ɔ��_˾,Security/Symfony/Component/Security/Http/Tests/EntryPoint/RetryAuthenticationEntryPointTest.phpnu�[���PK11[GrT�		`��,Security/Symfony/Component/Security/Http/Tests/EntryPoint/DigestAuthenticationEntryPointTest.phpnu�[���PK11[Ғ)��R��,Security/Symfony/Component/Security/Http/Tests/Firewall/RememberMeListenerTest.phpnu�[���PK11[�G��

O��,Security/Symfony/Component/Security/Http/Tests/Firewall/ChannelListenerTest.phpnu�[���PK11[�e��
�
_��,Security/Symfony/Component/Security/Http/Tests/Firewall/AnonymousAuthenticationListenerTest.phpnu�[���PK11[��K�$$[�	-Security/Symfony/Component/Security/Http/Tests/Firewall/BasicAuthenticationListenerTest.phpnu�[���PK11[��l���J-.-Security/Symfony/Component/Security/Http/Tests/Firewall/DigestDataTest.phpnu�[���PK11[j�z9�"�"OzJ-Security/Symfony/Component/Security/Http/Tests/Firewall/ContextListenerTest.phpnu�[���PK11[<��%%`�m-Security/Symfony/Component/Security/Http/Tests/Firewall/AbstractPreAuthenticatedListenerTest.phpnu�[���PK11[q���NR�-Security/Symfony/Component/Security/Http/Tests/Firewall/AccessListenerTest.phpnu�[���PK11[�V�k��Nر-Security/Symfony/Component/Security/Http/Tests/Firewall/LogoutListenerTest.phpnu�[���PK11[���@&@&R��-Security/Symfony/Component/Security/Http/Tests/Firewall/SwitchUserListenerTest.phpnu�[���PK11[�LMMZ��-Security/Symfony/Component/Security/Http/Tests/Firewall/X509AuthenticationListenerTest.phpnu�[���PK11[x��W��@�.Security/Symfony/Component/Security/Http/Tests/AccessMapTest.phpnu�[���PK11[���F8F8h�.Security/Symfony/Component/Security/Http/Tests/RememberMe/PersistentTokenBasedRememberMeServicesTest.phpnu�[���PK11[�䗥1#1#\qD.Security/Symfony/Component/Security/Http/Tests/RememberMe/AbstractRememberMeServicesTest.phpnu�[���PK11[�gZ)Z)^.h.Security/Symfony/Component/Security/Http/Tests/RememberMe/TokenBasedRememberMeServicesTest.phpnu�[���PK11[��ʅ
�
R�.Security/Symfony/Component/Security/Http/Tests/RememberMe/ResponseListenerTest.phpnu�[���PK11[Y�Ң	�	\�.Security/Symfony/Component/Security/Http/Tests/Session/SessionAuthenticationStrategyTest.phpnu�[���PK11[�
{{YK�.Security/Symfony/Component/Security/Http/Tests/Logout/DefaultLogoutSuccessHandlerTest.phpnu�[���PK11[]�ͷ��RO�.Security/Symfony/Component/Security/Http/Tests/Logout/SessionLogoutHandlerTest.phpnu�[���PK11[k��Yt�.Security/Symfony/Component/Security/Http/Tests/Logout/CookieClearingLogoutHandlerTest.phpnu�[���PK11[$a��i	�.Security/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationFailureHandlerTest.phpnu�[���PK11[/w!w!ac�.Security/Symfony/Component/Security/Http/Tests/Authentication/SimpleAuthenticationHandlerTest.phpnu�[���PK11[id]z��ik�.Security/Symfony/Component/Security/Http/Tests/Authentication/DefaultAuthenticationSuccessHandlerTest.phpnu�[���PK11[?k,.<<9�/Security/Symfony/Component/Security/Http/phpunit.xml.distnu�[���PK11[�|G

]�/Security/Symfony/Component/Security/Csrf/Tests/TokenStorage/NativeSessionTokenStorageTest.phpnu�[���PK11[���WWWH /Security/Symfony/Component/Security/Csrf/Tests/TokenStorage/SessionTokenStorageTest.phpnu�[���PK11[�-�kkG&@/Security/Symfony/Component/Security/Csrf/Tests/CsrfTokenManagerTest.phpnu�[���PK11[�3�z(([T/Security/Symfony/Component/Security/Csrf/Tests/TokenGenerator/UriSafeTokenGeneratorTest.phpnu�[���PK11[��*�<<9�[/Security/Symfony/Component/Security/Csrf/phpunit.xml.distnu�[���PK11[ׄHAnnF`_/Security/Symfony/Component/Security/Core/Tests/SecurityContextTest.phpnu�[���PK11[xF�@Do/Security/Symfony/Component/Security/Core/Tests/Role/RoleTest.phpnu�[���PK11[t�S��I�q/Security/Symfony/Component/Security/Core/Tests/Role/RoleHierarchyTest.phpnu�[���PK11[��{{J�w/Security/Symfony/Component/Security/Core/Tests/Role/SwitchUserRoleTest.phpnu�[���PK11[r��nnT�{/Security/Symfony/Component/Security/Core/Tests/Encoder/Pbkdf2PasswordEncoderTest.phpnu�[���PK11[6���W„/Security/Symfony/Component/Security/Core/Tests/Encoder/PlaintextPasswordEncoderTest.phpnu�[���PK11[L�'��R��/Security/Symfony/Component/Security/Core/Tests/Encoder/BasePasswordEncoderTest.phpnu�[���PK21[%�s�M^�/Security/Symfony/Component/Security/Core/Tests/Encoder/EncoderFactoryTest.phpnu�[���PK21[e5���[ܧ/Security/Symfony/Component/Security/Core/Tests/Encoder/MessageDigestPasswordEncoderTest.phpnu�[���PK21[!�?��	�	Tb�/Security/Symfony/Component/Security/Core/Tests/Encoder/BCryptPasswordEncoderTest.phpnu�[���PK21[�����b��/Security/Symfony/Component/Security/Core/Tests/Validator/Constraints/UserPasswordValidatorTest.phpnu�[���PK21[�KN��H��/Security/Symfony/Component/Security/Core/Tests/Util/SecureRandomTest.phpnu�[���PK21[n�;�SSG?�/Security/Symfony/Component/Security/Core/Tests/Util/StringUtilsTest.phpnu�[���PK21[�����F	�/Security/Symfony/Component/Security/Core/Tests/Util/ClassUtilsTest.phpnu�[���PK21[I-���Zg�/Security/Symfony/Component/Security/Core/Tests/Authorization/AccessDecisionManagerTest.phpnu�[���PK21[�bdw�
�
W�0Security/Symfony/Component/Security/Core/Tests/Authorization/ExpressionLanguageTest.phpnu�[���PK21[�Ƕ'�
�
Z30Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/ExpressionVoterTest.phpnu�[���PK21[jq�o��TV!0Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleVoterTest.phpnu�[���PK21[�R�MM])0Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/RoleHierarchyVoterTest.phpnu�[���PK21[��� ,
,
]Y.0Security/Symfony/Component/Security/Core/Tests/Authorization/Voter/AuthenticatedVoterTest.phpnu�[���PK21[LS�(��@<0Security/Symfony/Component/Security/Core/Tests/User/UserTest.phpnu�[���PK21[��qMBK0Security/Symfony/Component/Security/Core/Tests/User/ChainUserProviderTest.phpnu�[���PK21[�$��n�b0Security/Symfony/Component/Security/Core/Tests/Authentication/Provider/AnonymousAuthenticationProviderTest.phpnu�[���PK21[P��[.[.h�k0Security/Symfony/Component/Security/Core/Tests/Authentication/Provider/DaoAuthenticationProviderTest.phpnu�[���PK21[ו�Gi&i&iu�0Security/Symfony/Component/Security/Core/Tests/Authentication/Provider/UserAuthenticationProviderTest.phpnu�[���PK21[�75ttow�0Security/Symfony/Component/Security/Core/Tests/Authentication/Provider/RememberMeAuthenticationProviderTest.phpnu�[���PK21[���ZZu��0Security/Symfony/Component/Security/Core/Tests/Authentication/Provider/PreAuthenticatedAuthenticationProviderTest.phpnu�[���PK21[�����c��0Security/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationProviderManagerTest.phpnu�[���PK21[ ����f�0Security/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/InMemoryTokenProviderTest.phpnu�[���PK31[B�����`�1Security/Symfony/Component/Security/Core/Tests/Authentication/RememberMe/PersistentTokenTest.phpnu�[���PK31[I?��

a�1Security/Symfony/Component/Security/Core/Tests/Authentication/AuthenticationTrustResolverTest.phpnu�[���PK31[�B3��$�$Y�1Security/Symfony/Component/Security/Core/Tests/Authentication/Token/AbstractTokenTest.phpnu�[���PK31[�j��KKa
91Security/Symfony/Component/Security/Core/Tests/Authentication/Token/UsernamePasswordTokenTest.phpnu�[���PK31[d���a�@1Security/Symfony/Component/Security/Core/Tests/Authentication/Token/PreAuthenticatedTokenTest.phpnu�[���PK31[��ۛ��ZiG1Security/Symfony/Component/Security/Core/Tests/Authentication/Token/AnonymousTokenTest.phpnu�[���PK31[]�P�<<9�L1Security/Symfony/Component/Security/Core/phpunit.xml.distnu�[���PK31[���n��G�P1Validator/Symfony/Component/Validator/Tests/ConstraintViolationTest.phpnu�[���PK31[zJ.4�
�
K�U1Validator/Symfony/Component/Validator/Tests/ConstraintViolationListTest.phpnu�[���PK31[�p��ggSMd1Validator/Symfony/Component/Validator/Tests/Fixtures/FailingConstraintValidator.phpnu�[���PK31[5*�D7g1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintB.phpnu�[���PK31[]�qqD�i1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintC.phpnu�[���PK31[���&��D�l1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintA.phpnu�[���PK31[ߛ��[[?�o1Validator/Symfony/Component/Validator/Tests/Fixtures/Entity.phpnu�[���PK31[p�Tq��UUw1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintWithValueAsDefault.phpnu�[���PK31[@��w��Lez1Validator/Symfony/Component/Validator/Tests/Fixtures/FakeMetadataFactory.phpnu�[���PK31[��a�CCH��1Validator/Symfony/Component/Validator/Tests/Fixtures/EntityInterface.phpnu�[���PK31[?>��M?�1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintAValidator.phpnu�[���PK31[^t��Hf�1Validator/Symfony/Component/Validator/Tests/Fixtures/ClassConstraint.phpnu�[���PK41[��88E��1Validator/Symfony/Component/Validator/Tests/Fixtures/EntityParent.phpnu�[���PK41[�h��T^�1Validator/Symfony/Component/Validator/Tests/Fixtures/GroupSequenceProviderEntity.phpnu�[���PK41[�5>��L�1Validator/Symfony/Component/Validator/Tests/Fixtures/ConstraintWithValue.phpnu�[���PK41[=�2J�1Validator/Symfony/Component/Validator/Tests/Fixtures/FailingConstraint.phpnu�[���PK41[O��l99B��1Validator/Symfony/Component/Validator/Tests/Fixtures/Reference.phpnu�[���PK41[2�	���J,�1Validator/Symfony/Component/Validator/Tests/Fixtures/InvalidConstraint.phpnu�[���PK41[j�/���D'�1Validator/Symfony/Component/Validator/Tests/Fixtures/FilesLoader.phpnu�[���PK41[Y��/F+�1Validator/Symfony/Component/Validator/Tests/Fixtures/CallbackClass.phpnu�[���PK41[���JJS��1Validator/Symfony/Component/Validator/Tests/Fixtures/InvalidConstraintValidator.phpnu�[���PK41[G#i��K�1Validator/Symfony/Component/Validator/Tests/Fixtures/PropertyConstraint.phpnu�[���PK41[�Ε_))DӢ1Validator/Symfony/Component/Validator/Tests/ValidatorBuilderTest.phpnu�[���PK41[��>���Ip�1Validator/Symfony/Component/Validator/Tests/Mapping/ClassMetadataTest.phpnu�[���PK41[F���P��1Validator/Symfony/Component/Validator/Tests/Mapping/ClassMetadataFactoryTest.phpnu�[���PK41[)����K��1Validator/Symfony/Component/Validator/Tests/Mapping/ElementMetadataTest.phpnu�[���PK41[�D��J"�1Validator/Symfony/Component/Validator/Tests/Mapping/MemberMetadataTest.phpnu�[���PK41[W_Ϙ�JZ�1Validator/Symfony/Component/Validator/Tests/Mapping/GetterMetadataTest.phpnu�[���PK41["��,�	�	Jl�1Validator/Symfony/Component/Validator/Tests/Mapping/Cache/ApcCacheTest.phpnu�[���PK51[os%�eeTs2Validator/Symfony/Component/Validator/Tests/Mapping/BlackholeMetadataFactoryTest.phpnu�[���PK51[u��gN\	2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/LoaderChainTest.phpnu�[���PK51[�=����]�2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping-non-strings.xmlnu�[���PK51[�D�k��QD2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping.xmlnu�[���PK51[�-���Q�%2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/constraint-mapping.ymlnu�[���PK51[{�%uU�+2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/StaticMethodLoaderTest.phpnu�[���PK51[���mSp;2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/AnnotationLoaderTest.phpnu�[���PK51[��N��QW2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/YamlFileLoaderTest.phpnu�[���PK51[N�;��J"i2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/withdoctype.xmlnu�[���PK51[L:k2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/empty-mapping.ymlnu�[���PK51[�Qi���P�k2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/XmlFileLoaderTest.phpnu�[���PK51[�e2~O�2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/nonvalid-mapping.ymlnu�[���PK51[����Y@�2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/AbstractMethodStaticLoader.phpnu�[���PK51[F���<<N��2Validator/Symfony/Component/Validator/Tests/Mapping/Loader/FilesLoaderTest.phpnu�[���PK51[{�d���Lx�2Validator/Symfony/Component/Validator/Tests/Mapping/PropertyMetadataTest.phpnu�[���PK51[��~6�F�FE��2Validator/Symfony/Component/Validator/Tests/ValidationVisitorTest.phpnu�[���PK51[K��y'$'$=��2Validator/Symfony/Component/Validator/Tests/ValidatorTest.phpnu�[���PK51[�P�6�)�)Dj�2Validator/Symfony/Component/Validator/Tests/ExecutionContextTest.phpnu�[���PK51[����Lk$3Validator/Symfony/Component/Validator/Tests/Constraints/AllValidatorTest.phpnu�[���PK51[�ĀDDN�13Validator/Symfony/Component/Validator/Tests/Constraints/RegexValidatorTest.phpnu�[���PK51[�Q�XID3Validator/Symfony/Component/Validator/Tests/Constraints/LessThanOrEqualValidatorTest.phpnu�[���PK51[�;�55M�K3Validator/Symfony/Component/Validator/Tests/Constraints/IssnValidatorTest.phpnu�[���PK51[����K1K1K�a3Validator/Symfony/Component/Validator/Tests/Constraints/IpValidatorTest.phpnu�[���PK51[�rH���dY�3Validator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorCustomArrayObjectTest.phpnu�[���PK51[�GRf��PҚ3Validator/Symfony/Component/Validator/Tests/Constraints/NotNullValidatorTest.phpnu�[���PK51[���I��J�3Validator/Symfony/Component/Validator/Tests/Constraints/CollectionTest.phpnu�[���PK51[���W��S �3Validator/Symfony/Component/Validator/Tests/Constraints/FileValidatorObjectTest.phpnu�[���PK51[s{*pQQM��3Validator/Symfony/Component/Validator/Tests/Constraints/TrueValidatorTest.phpnu�[���PK51[�|�++R`�3Validator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_portrait.gifnu�[���PK51[J��++S
�3Validator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test_landscape.gifnu�[���PK51[Ѝ��!!I��3Validator/Symfony/Component/Validator/Tests/Constraints/Fixtures/test.gifnu�[���PK51[)m�ROU�3Validator/Symfony/Component/Validator/Tests/Constraints/LengthValidatorTest.phpnu�[���PK51[��̈́
�
O��3Validator/Symfony/Component/Validator/Tests/Constraints/LocaleValidatorTest.phpnu�[���PK51[�s�VVS��3Validator/Symfony/Component/Validator/Tests/Constraints/NotEqualToValidatorTest.phpnu�[���PK51[���8w
w
N��3Validator/Symfony/Component/Validator/Tests/Constraints/EmailValidatorTest.phpnu�[���PK61[�w88W��3Validator/Symfony/Component/Validator/Tests/Constraints/CountValidatorCountableTest.phpnu�[���PK61[];XwwNe�3Validator/Symfony/Component/Validator/Tests/Constraints/BlankValidatorTest.phpnu�[���PK61[3�ê�
�
_Z�3Validator/Symfony/Component/Validator/Tests/Constraints/AbstractComparisonValidatorTestCase.phpnu�[���PK61[7��a��O�4Validator/Symfony/Component/Validator/Tests/Constraints/ChoiceValidatorTest.phpnu�[���PK61[�2�(�(M�,4Validator/Symfony/Component/Validator/Tests/Constraints/FileValidatorTest.phpnu�[���PK61[�����S0V4Validator/Symfony/Component/Validator/Tests/Constraints/CardSchemeValidatorTest.phpnu�[���PK61[{r>K��MMi4Validator/Symfony/Component/Validator/Tests/Constraints/IsbnValidatorTest.phpnu�[���PK61[jTL�99Pu�4Validator/Symfony/Component/Validator/Tests/Constraints/EqualToValidatorTest.phpnu�[���PK61[�$&��T.�4Validator/Symfony/Component/Validator/Tests/Constraints/IdenticalToValidatorTest.phpnu�[���PK61[��|=��^��4Validator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorArrayObjectTest.phpnu�[���PK61[�z0���P��4Validator/Symfony/Component/Validator/Tests/Constraints/CountryValidatorTest.phpnu�[���PK61[�rZccW�4Validator/Symfony/Component/Validator/Tests/Constraints/NotIdenticalToValidatorTest.phpnu�[���PK61[�C��NNL�4Validator/Symfony/Component/Validator/Tests/Constraints/UrlValidatorTest.phpnu�[���PK61[(�3��E��4Validator/Symfony/Component/Validator/Tests/Constraints/ValidTest.phpnu�[���PK61[���A��QԽ4Validator/Symfony/Component/Validator/Tests/Constraints/CurrencyValidatorTest.phpnu�[���PK61[B����CO�4Validator/Symfony/Component/Validator/Tests/Constraints/AllTest.phpnu�[���PK61[�p�)D
D
M��4Validator/Symfony/Component/Validator/Tests/Constraints/LuhnValidatorTest.phpnu�[���PK61[��͸�NI�4Validator/Symfony/Component/Validator/Tests/Constraints/RangeValidatorTest.phpnu�[���PK61[Q��s(s(Q�4Validator/Symfony/Component/Validator/Tests/Constraints/CallbackValidatorTest.phpnu�[���PK61[@*�VHHMs5Validator/Symfony/Component/Validator/Tests/Constraints/DateValidatorTest.phpnu�[���PK61[�� BTTM8)5Validator/Symfony/Component/Validator/Tests/Constraints/TimeValidatorTest.phpnu�[���PK61[�i�KKN	55Validator/Symfony/Component/Validator/Tests/Constraints/FalseValidatorTest.phpnu�[���PK71[Ϗ�R��S�;5Validator/Symfony/Component/Validator/Tests/Constraints/CountValidatorArrayTest.phpnu�[���PK71[qC����QR>5Validator/Symfony/Component/Validator/Tests/Constraints/LanguageValidatorTest.phpnu�[���PK71[ֆ���N�J5Validator/Symfony/Component/Validator/Tests/Constraints/CountValidatorTest.phpnu�[���PK71[��LwwT�_5Validator/Symfony/Component/Validator/Tests/Constraints/GreaterThanValidatorTest.phpnu�[���PK71[���kkQ�g5Validator/Symfony/Component/Validator/Tests/Constraints/FileValidatorPathTest.phpnu�[���PK71[׫��[�k5Validator/Symfony/Component/Validator/Tests/Constraints/GreaterThanOrEqualValidatorTest.phpnu�[���PK71[W�@� � Mrr5Validator/Symfony/Component/Validator/Tests/Constraints/IbanValidatorTest.phpnu�[���PK71[�y7{==M��5Validator/Symfony/Component/Validator/Tests/Constraints/TypeValidatorTest.phpnu�[���PK71[\z?�+�+ST�5Validator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorTest.phpnu�[���PK71[C���77Q��5Validator/Symfony/Component/Validator/Tests/Constraints/LessThanValidatorTest.phpnu�[���PK71[b���ggQS�5Validator/Symfony/Component/Validator/Tests/Constraints/DateTimeValidatorTest.phpnu�[���PK71[;���,,S;�5Validator/Symfony/Component/Validator/Tests/Constraints/ExpressionValidatorTest.phpnu�[���PK71[�Zf^
^
Q�6Validator/Symfony/Component/Validator/Tests/Constraints/NotBlankValidatorTest.phpnu�[���PK71[}mW��X�6Validator/Symfony/Component/Validator/Tests/Constraints/CollectionValidatorArrayTest.phpnu�[���PK71[�r3UUM6Validator/Symfony/Component/Validator/Tests/Constraints/NullValidatorTest.phpnu�[���PK71[0�h'��N�6Validator/Symfony/Component/Validator/Tests/Constraints/ImageValidatorTest.phpnu�[���PK71[�d��..>I76Validator/Symfony/Component/Validator/Tests/ConstraintTest.phpnu�[���PK71[��,Q886�I6Validator/Symfony/Component/Validator/phpunit.xml.distnu�[���PK71[�����F�M6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Logger/DbalLoggerTest.phpnu�[���PK71[l;���:�^6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/bootstrap.phpnu�[���PK71[1g��K�`6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleIntIdEntity.phpnu�[���PK71[I>�[��Ud6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleIntIdNoToStringEntity.phpnu�[���PK71[�+�88N4g6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/CompositeIntIdEntity.phpnu�[���PK71[�ͭ��K�j6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/AssociationEntity.phpnu�[���PK71[��3IZo6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/GroupableEntity.phpnu�[���PK81[��!��N�r6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/SingleStringIdEntity.phpnu�[���PK81[6i+**O:v6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/ContainerAwareFixture.phpnu�[���PK81[И�m��J�y6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/DoubleNameEntity.phpnu�[���PK81[�%b�99QR}6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/CompositeStringIdEntity.phpnu�[���PK81[�'N|qq>�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Fixtures/User.phpnu�[���PK81[��.���D�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/DoctrineOrmTestCase.phpnu�[���PK81[��۵��P\�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/DoctrineOrmTypeGuesserTest.phpnu�[���PK81[��`Հ�k�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleStringIdTest.phpnu�[���PK81[�'�;�!�!\��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/GenericEntityChoiceListTest.phpnu�[���PK81[9&��{��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleStringIdWithQueryBuilderTest.phpnu�[���PK81[b#����hF�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListSingleIntIdTest.phpnu�[���PK81[AGA��x��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleIntIdWithQueryBuilderTest.phpnu�[���PK81[�~h���x.�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListCompositeIdWithQueryBuilderTest.phpnu�[���PK81[�'j��i��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListSingleStringIdTest.phpnu�[���PK81[�0�e��f&�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListSingleIntIdTest.phpnu�[���PK81[��V
zzh��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListCompositeIdTest.phpnu�[���PK81[��*��h��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListCompositeIdTest.phpnu�[���PK81[�n<-	-	Z�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.phpnu�[���PK81[�-��1
1
]��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListTest.phpnu�[���PK81[c�&zzhz�6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/UnloadedEntityChoiceListSingleIntIdTest.phpnu�[���PK81[�ǜ"��f��6DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/LoadedEntityChoiceListCompositeIdTest.phpnu�[���PK81[_UNF��k�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/AbstractEntityChoiceListSingleStringIdTest.phpnu�[���PK91[Yv�:B	B	fS7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/DataTransformer/CollectionToArrayTransformerTest.phpnu�[���PK91[��(iiI+7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.phpnu�[���PK91[�I�m��T�{7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypePerformanceTest.phpnu�[���PK91[�;��
�
U�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Security/User/EntityUserProviderTest.phpnu�[���PK91[}��u>u>ZI�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/Validator/Constraints/UniqueValidatorTest.phpnu�[���PK91[���,��[H�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/ExpressionLanguage/DoctrineParserCacheTest.phpnu�[���PK91[�$K�BBO��7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/ContainerAwareEventManagerTest.phpnu�[���PK91[�9qqV~�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/DataFixtures/ContainerAwareLoaderTest.phpnu�[���PK91[C�IIVu�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/HttpFoundation/DbalSessionHandlerTest.phpnu�[���PK91[�l��XD�7DoctrineBridge/Symfony/Bridge/Doctrine/Tests/DataCollector/DoctrineDataCollectorTest.phpnu�[���PK91[O���~�8DoctrineBridge/Symfony/Bridge/Doctrine/Tests/DependencyInjection/CompilerPass/RegisterEventListenersAndSubscribersPassTest.phpnu�[���PK91[�ޠ�777B8DoctrineBridge/Symfony/Bridge/Doctrine/phpunit.xml.distnu�[���PK:1[&�ǦGGI�8MonologBridge/Symfony/Bridge/Monolog/Tests/Handler/ConsoleHandlerTest.phpnu�[���PK:1[�o.���I�68MonologBridge/Symfony/Bridge/Monolog/Tests/Processor/WebProcessorTest.phpnu�[���PK:1[��Ki665@8MonologBridge/Symfony/Bridge/Monolog/phpunit.xml.distnu�[���PK:1[}/�66H�C8Templating/Symfony/Component/Templating/Tests/TemplateNameParserTest.phpnu�[���PK:1[���xxGQI8Templating/Symfony/Component/Templating/Tests/Fixtures/SimpleHelper.phpnu�[���PK:1[�`�2H@L8Templating/Symfony/Component/Templating/Tests/Fixtures/templates/foo.phpnu�[���PK;1[=D����I�L8Templating/Symfony/Component/Templating/Tests/Storage/FileStorageTest.phpnu�[���PK;1[`7�SSK�P8Templating/Symfony/Component/Templating/Tests/Storage/StringStorageTest.phpnu�[���PK;1[S	�٦�E�T8Templating/Symfony/Component/Templating/Tests/Storage/StorageTest.phpnu�[���PK;1[��7���C�W8Templating/Symfony/Component/Templating/Tests/Loader/LoaderTest.phpnu�[���PK;1[Wl�‡�M�]8Templating/Symfony/Component/Templating/Tests/Loader/FilesystemLoaderTest.phpnu�[���PK;1[���
�
H�n8Templating/Symfony/Component/Templating/Tests/Loader/CacheLoaderTest.phpnu�[���PK;1[ˡA`��H6z8Templating/Symfony/Component/Templating/Tests/Loader/ChainLoaderTest.phpnu�[���PK;1[�`n}�
�
I��8Templating/Symfony/Component/Templating/Tests/Helper/AssetsHelperTest.phpnu�[���PK;1[�q=R

Cϑ8Templating/Symfony/Component/Templating/Tests/Helper/HelperTest.phpnu�[���PK;1[M<��MO�8Templating/Symfony/Component/Templating/Tests/Helper/CoreAssetsHelperTest.phpnu�[���PK;1[0�nl

HК8Templating/Symfony/Component/Templating/Tests/Helper/SlotsHelperTest.phpnu�[���PK;1[��`#`#?X�8Templating/Symfony/Component/Templating/Tests/PhpEngineTest.phpnu�[���PK;1[�氵�F'�8Templating/Symfony/Component/Templating/Tests/DelegatingEngineTest.phpnu�[���PK;1[�%�D998R�8Templating/Symfony/Component/Templating/phpunit.xml.distnu�[���PK<1[��Q��0��8Yaml/Symfony/Component/Yaml/Tests/DumperTest.phpnu�[���PK<1[�����>�8Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBlockMapping.ymlnu�[���PK<1[��UU8�8Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfCompact.ymlnu�[���PK<1[�5�R[[=�	9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsAnchorAlias.ymlnu�[���PK<1[U���6s
9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfTests.ymlnu�[���PK<1[�@�UU9�9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfComments.ymlnu�[���PK<1[Ç��--D�9Yaml/Symfony/Component/Yaml/Tests/Fixtures/unindentedCollections.ymlnu�[���PK<1[�>;���A/"9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsNullsAndEmpties.ymlnu�[���PK<1[t��rqq<K%9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsErrorTests.ymlnu�[���PK<1[Z{k�XXA((9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFlowCollections.ymlnu�[���PK<1[�*���@�.9Yaml/Symfony/Component/Yaml/Tests/Fixtures/escapedCharacters.ymlnu�[���PK<1[֋�O��<V79Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsBasicTests.ymlnu�[���PK<1[ګغzz?�F9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsFoldedScalars.ymlnu�[���PK<1[���884�V9Yaml/Symfony/Component/Yaml/Tests/Fixtures/index.ymlnu�[���PK<1[%MC��C;X9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsDocumentSeparator.ymlnu�[���PK<1[;:�QJJ9�^9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfMergeKey.ymlnu�[���PK<1[Z��9[c9Yaml/Symfony/Component/Yaml/Tests/Fixtures/embededPhp.ymlnu�[���PK<1[�<�8�c9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfObjects.ymlnu�[���PK<1[�$R��?ge9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsTypeTransfers.ymlnu�[���PK<1[����7��9Yaml/Symfony/Component/Yaml/Tests/Fixtures/sfQuotes.ymlnu�[���PK<1[ܷU�1�1�G�9Yaml/Symfony/Component/Yaml/Tests/Fixtures/YtsSpecificationExamples.ymlnu�[���PK<1[~;�p2p20�&:Yaml/Symfony/Component/Yaml/Tests/ParserTest.phpnu�[���PK<1[=a�o[%[%0~Y:Yaml/Symfony/Component/Yaml/Tests/InlineTest.phpnu�[���PK<1[`�@ee.9:Yaml/Symfony/Component/Yaml/Tests/YamlTest.phpnu�[���PK<1[��?o��8��:Yaml/Symfony/Component/Yaml/Tests/ParseExceptionTest.phpnu�[���PK<1[�>[33,
�:Yaml/Symfony/Component/Yaml/phpunit.xml.distnu�[���PK<1[����$��:Console_Getopt/tests/001-getopt.phptnu�[���PK<1[��"��:Console_Getopt/tests/bug11068.phptnu�[���PK<1[���")�:Console_Getopt/tests/bug10557.phptnu�[���PK<1[��|EE"i�:Console_Getopt/tests/bug13140.phptnu�[���PK<1[��mg�
�
E�:HttpFoundation/Symfony/Component/HttpFoundation/Tests/IpUtilsTest.phpnu�[���PK<1[��Jb�:HttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestStackTest.phpnu�[���PK<1[��lOD
D
J�:HttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseTestCase.phpnu�[���PK<1[�F�9bbD��:HttpFoundation/Symfony/Component/HttpFoundation/Tests/CookieTest.phpnu�[���PK<1[�q�H��Nv�:HttpFoundation/Symfony/Component/HttpFoundation/Tests/RedirectResponseTest.phpnu�[���PK<1[qr��



V��:HttpFoundation/Symfony/Component/HttpFoundation/Tests/ExpressionRequestMatcherTest.phpnu�[���PK<1[_�|���Pd�:HttpFoundation/Symfony/Component/HttpFoundation/Tests/BinaryFileResponseTest.phpnu�[���PK<1[��@LLE�;HttpFoundation/Symfony/Component/HttpFoundation/Tests/FileBagTest.phpnu�[���PK<1[�m��..GN;HttpFoundation/Symfony/Component/HttpFoundation/Tests/HeaderBagTest.phpnu�[���PK<1[��܏##L�0;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/test.gifnu�[���PK<1[�+�vU�1;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/.unknownextensionnu�[���PK<1[T2;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/directory/.emptynu�[���PK<1[��܏##H�2;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/Fixtures/testnu�[���PK<1[~rM;;T73;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/MimeType/MimeTypeTest.phpnu�[���PK<1[��##G�B;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/FileTest.phpnu�[���PK<1[��t�AAO�X;HttpFoundation/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.phpnu�[���PK<1[�ʾV�
�
NPu;HttpFoundation/Symfony/Component/HttpFoundation/Tests/StreamedResponseTest.phpnu�[���PK<1[M�{��^��;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Flash/AutoExpireFlashBagTest.phpnu�[���PK<1[��ƒ��T��;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Flash/FlashBagTest.phpnu�[���PK=1[0�����\�;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Attribute/AttributeBagTest.phpnu�[���PK=1[)��f;�;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Attribute/NamespacedAttributeBagTest.phpnu�[���PK=1[��ppM��;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/SessionTest.phpnu�[���PK=1[>��*d��;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockFileSessionStorageTest.phpnu�[���PK=1[5�h���js�;HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeSessionHandlerTest.phpnu�[���PK=1[1�Mf
f
l�<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcacheSessionHandlerTest.phpnu�[���PK=1[�+?�

n�<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.phpnu�[���PK=1[>��$$k}<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.phpnu�[���PK=1[`����m<2<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/MemcachedSessionHandlerTest.phpnu�[���PK=1[�c=��n�?<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/WriteCheckSessionHandlerTest.phpnu�[���PK=1[�Qttg�K<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.phpnu�[���PK=1[+�ɠ��h�[<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.phpnu�[���PK=1[��x�..ec<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/PhpBridgeSessionStorageTest.phpnu�[���PK=1[�����e�r<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MockArraySessionStorageTest.phpnu�[���PK=1[t䪑�$�$b.<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.phpnu�[���PK=1[�@|B``_��<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/NativeProxyTest.phpnu�[���PK=1[F�++a��<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/AbstractProxyTest.phpnu�[���PK=1[Č#��g[�<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.phpnu�[���PK=1[T �S��Y��<HttpFoundation/Symfony/Component/HttpFoundation/Tests/Session/Storage/MetadataBagTest.phpnu�[���PK=1[��7�
�
N)�<HttpFoundation/Symfony/Component/HttpFoundation/Tests/AcceptHeaderItemTest.phpnu�[���PK=1[�`k J��<HttpFoundation/Symfony/Component/HttpFoundation/Tests/JsonResponseTest.phpnu�[���PK=1[�E����L=HttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestMatcherTest.phpnu�[���PK=1[����,�,OI=HttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseHeaderBagTest.phpnu�[���PK=1[k\B��r�rF�>=HttpFoundation/Symfony/Component/HttpFoundation/Tests/ResponseTest.phpnu�[���PK=1[Ak�B#B#J�=HttpFoundation/Symfony/Component/HttpFoundation/Tests/ParameterBagTest.phpnu�[���PK=1[��q��E��=HttpFoundation/Symfony/Component/HttpFoundation/Tests/RequestTest.phpnu�[���PK=1[%�bD�
�
K��>HttpFoundation/Symfony/Component/HttpFoundation/Tests/ApacheRequestTest.phpnu�[���PK=1[�1r�
�
J�>HttpFoundation/Symfony/Component/HttpFoundation/Tests/AcceptHeaderTest.phpnu�[���PK=1[��?�G?HttpFoundation/Symfony/Component/HttpFoundation/Tests/ServerBagTest.phpnu�[���PK=1[���bpp@�?HttpFoundation/Symfony/Component/HttpFoundation/phpunit.xml.distnu�[���PK=1[��J=�'�'?w?BrowserKit/Symfony/Component/BrowserKit/Tests/CookieJarTest.phpnu�[���PK=1[N�4Z�c�c<�>?BrowserKit/Symfony/Component/BrowserKit/Tests/ClientTest.phpnu�[���PK=1[�ɹ(RR<�?BrowserKit/Symfony/Component/BrowserKit/Tests/CookieTest.phpnu�[���PK=1[K����=Ͽ?BrowserKit/Symfony/Component/BrowserKit/Tests/HistoryTest.phpnu�[���PK=1[{2�w>+�?BrowserKit/Symfony/Component/BrowserKit/Tests/ResponseTest.phpnu�[���PK=1[|����=��?BrowserKit/Symfony/Component/BrowserKit/Tests/RequestTest.phpnu�[���PK@1[�p6ll8��?BrowserKit/Symfony/Component/BrowserKit/phpunit.xml.distnu�[���PK@1[?7��EE4��?Net_IDNA2/tests/draft-josefsson-idn-test-vectors.phpnu�[���PK@1[E��mm!6-@Net_IDNA2/tests/Net_IDNA2Test.phpnu�[���PK@1[.��
���5@XML_RPC/tests/extra-lines.phpnu�[���PK@1[|�E$
?@XML_RPC/tests/empty-value-struct.phpnu�[���PK@1[�3l�**iF@XML_RPC/tests/protoport.phpnu�[���PK@1[�B��p@XML_RPC/tests/allgot.incnu�[���PK@1[��̢�	�	v@XML_RPC/tests/types.phpnu�[���PK@1[J����A�@XML_RPC/tests/encode.phpnu�[���PK@1[���XXZ�@XML_RPC/tests/test_Dump.phpnu�[���PK@1[$]�����@XML_RPC/tests/empty-value.phpnu�[���PK@1[b��))) C�@XML_RPC/tests/actual-request.phpnu�[���PKA1[w�۴��H��@DomCrawler/Symfony/Component/DomCrawler/Tests/Fixtures/windows-1250.htmlnu�[���PKA1[�x�Cء@DomCrawler/Symfony/Component/DomCrawler/Tests/Fixtures/no-extensionnu�[���PKA1[l�#8��=P�@DomCrawler/Symfony/Component/DomCrawler/Tests/CrawlerTest.phpnu�[���PKA1[��Ջ==K�/ADomCrawler/Symfony/Component/DomCrawler/Tests/Field/ChoiceFormFieldTest.phpnu�[���PKA1[�n���M_mADomCrawler/Symfony/Component/DomCrawler/Tests/Field/TextareaFormFieldTest.phpnu�[���PKA1[�!
D��E�tADomCrawler/Symfony/Component/DomCrawler/Tests/Field/FormFieldTest.phpnu�[���PKA1[2$�G��I
zADomCrawler/Symfony/Component/DomCrawler/Tests/Field/FormFieldTestCase.phpnu�[���PKA1[���QQJ}ADomCrawler/Symfony/Component/DomCrawler/Tests/Field/InputFormFieldTest.phpnu�[���PKA1[�5�||I�ADomCrawler/Symfony/Component/DomCrawler/Tests/Field/FileFormFieldTest.phpnu�[���PKA1[�3��ʖʖ:ޖADomCrawler/Symfony/Component/DomCrawler/Tests/FormTest.phpnu�[���PKA1[m�Y���:.BDomCrawler/Symfony/Component/DomCrawler/Tests/LinkTest.phpnu�[���PKA1[)q0�ll8/FBDomCrawler/Symfony/Component/DomCrawler/phpunit.xml.distnu�[���PKB1[��H�77GJBCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/ids.htmlnu�[���PKB1[miĪ:�:N�PBCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/shakespear.htmlnu�[���PKB1[�B�==G��BCssSelector/Symfony/Component/CssSelector/Tests/XPath/Fixtures/lang.xmlnu�[���PKB1[1�HCHCHg�BCssSelector/Symfony/Component/CssSelector/Tests/XPath/TranslatorTest.phpnu�[���PKB1[o,q��H'�BCssSelector/Symfony/Component/CssSelector/Tests/Node/ElementNodeTest.phpnu�[���PKB1[�BնVVEa�BCssSelector/Symfony/Component/CssSelector/Tests/Node/HashNodeTest.phpnu�[���PKB1[V=��hhF,�BCssSelector/Symfony/Component/CssSelector/Tests/Node/ClassNodeTest.phpnu�[���PKB1[g$i���I
�BCssSelector/Symfony/Component/CssSelector/Tests/Node/NegationNodeTest.phpnu�[���PKB1[j�
��Q6�BCssSelector/Symfony/Component/CssSelector/Tests/Node/CombinedSelectorNodeTest.phpnu�[���PKB1[�(yآ�I��BCssSelector/Symfony/Component/CssSelector/Tests/Node/FunctionNodeTest.phpnu�[���PKB1[�Y���I��BCssSelector/Symfony/Component/CssSelector/Tests/Node/AbstractNodeTest.phpnu�[���PKB1[_�Ӵ�I��BCssSelector/Symfony/Component/CssSelector/Tests/Node/SelectorNodeTest.phpnu�[���PKB1[���uuH�BCssSelector/Symfony/Component/CssSelector/Tests/Node/SpecificityTest.phpnu�[���PKB1[� _ӽ�J	�BCssSelector/Symfony/Component/CssSelector/Tests/Node/AttributeNodeTest.phpnu�[���PKB1[�WDG@CCssSelector/Symfony/Component/CssSelector/Tests/Node/PseudoNodeTest.phpnu�[���PKB1[�/D�C�CCssSelector/Symfony/Component/CssSelector/Tests/CssSelectorTest.phpnu�[���PKB1[�u̱��UfCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/ElementParserTest.phpnu�[���PKB1[[�nы�S�CCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/ClassParserTest.phpnu�[���PKB1[>�]��Y�CCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/EmptyStringParserTest.phpnu�[���PKB1[[N�eeRL!CCssSelector/Symfony/Component/CssSelector/Tests/Parser/Shortcut/HashParserTest.phpnu�[���PKB1[^���2�2E3'CCssSelector/Symfony/Component/CssSelector/Tests/Parser/ParserTest.phpnu�[���PKB1[+��̭�TLZCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/NumberHandlerTest.phpnu�[���PKB1[��˶X}`CCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/IdentifierHandlerTest.phpnu�[���PKB1[��_/RRUgCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/CommentHandlerTest.phpnu�[���PKB1[Ĉ���V�mCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/AbstractHandlerTest.phpnu�[���PKB1[ ���X)wCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/WhitespaceHandlerTest.phpnu�[���PKB1[�쓱��Td|CCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/StringHandlerTest.phpnu�[���PKB1[C�U�rrRтCCssSelector/Symfony/Component/CssSelector/Tests/Parser/Handler/HashHandlerTest.phpnu�[���PKB1[%9�j~~EňCCssSelector/Symfony/Component/CssSelector/Tests/Parser/ReaderTest.phpnu�[���PKB1[�}��qqJ��CCssSelector/Symfony/Component/CssSelector/Tests/Parser/TokenStreamTest.phpnu�[���PKC1[���Hmm:��CCssSelector/Symfony/Component/CssSelector/phpunit.xml.distnu�[���PKC1[�X,�/�/Oz�CEventDispatcher/Symfony/Component/EventDispatcher/Tests/EventDispatcherTest.phpnu�[���PKC1[���aaX��CEventDispatcher/Symfony/Component/EventDispatcher/Tests/ImmutableEventDispatcherTest.phpnu�[���PKC1[YQ_AA]o�CEventDispatcher/Symfony/Component/EventDispatcher/Tests/ContainerAwareEventDispatcherTest.phpnu�[���PKC1[��nuE=�CEventDispatcher/Symfony/Component/EventDispatcher/Tests/EventTest.phpnu�[���PKC1[\2��
�
L�DEventDispatcher/Symfony/Component/EventDispatcher/Tests/GenericEventTest.phpnu�[���PKC1[�MqqB3DEventDispatcher/Symfony/Component/EventDispatcher/phpunit.xml.distnu�[���PKC1[��C	C	CDConsole/Symfony/Component/Console/Tests/Command/ListCommandTest.phpnu�[���PKC1[o�"�Z9Z9?�#DConsole/Symfony/Component/Console/Tests/Command/CommandTest.phpnu�[���PKC1[b�y�11C�]DConsole/Symfony/Component/Console/Tests/Command/HelpCommandTest.phpnu�[���PKC1[u��d��H9iDConsole/Symfony/Component/Console/Tests/Fixtures/application_astext1.txtnu�[���PKC1[��c��B^mDConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.mdnu�[���PKC1[���ooF~nDConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.jsonnu�[���PKC1[��f���EcoDConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.xmlnu�[���PKC1[9y�X��=�pDConsole/Symfony/Component/Console/Tests/Fixtures/command_1.mdnu�[���PKC1[�S��B�qDConsole/Symfony/Component/Console/Tests/Fixtures/command_asxml.txtnu�[���PKC1[�^t�^^G�xDConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.xmlnu�[���PKC1[P����B�yDConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.mdnu�[���PKC1[���B�zDConsole/Symfony/Component/Console/Tests/Fixtures/BarBucCommand.phpnu�[���PKC1[W'��G�{DConsole/Symfony/Component/Console/Tests/Fixtures/application_asxml2.txtnu�[���PKC1[&���Q�DConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception1.txtnu�[���PKC1[��XX��C
�DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.xmlnu�[���PKC1[��G��CR�DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.xmlnu�[���PKC1[Y'�A��Gw�DConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand1.phpnu�[���PKC1[CQu��Gt�DConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.xmlnu�[���PKC1[�!�"��E�DConsole/Symfony/Component/Console/Tests/Fixtures/application_run3.txtnu�[���PKC1[�e�d��@��DConsole/Symfony/Component/Console/Tests/Fixtures/Foo4Command.phpnu�[���PKC1[z�Ռ��D��DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.mdnu�[���PKC1[�t;�aaC��DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.txtnu�[���PKC1[ a���Dv�DConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.jsonnu�[���PKC1[�F:cG��DConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.xmlnu�[���PKC1[oY���C��DConsole/Symfony/Component/Console/Tests/Fixtures/application_1.jsonnu�[���PKC1[#��"��?R�DConsole/Symfony/Component/Console/Tests/Fixtures/command_2.jsonnu�[���PKC1[9�*A��@��DConsole/Symfony/Component/Console/Tests/Fixtures/TestCommand.phpnu�[���PKD1[�'�̒�>ŨDConsole/Symfony/Component/Console/Tests/Fixtures/command_1.txtnu�[���PKD1[<|�4UU@ũDConsole/Symfony/Component/Console/Tests/Fixtures/Foo1Command.phpnu�[���PKD1[G��DConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.txtnu�[���PKD1[��<]]F�DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.jsonnu�[���PKD1[۴�2��DԭDConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.jsonnu�[���PKD1[�q+��K�DConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication1.phpnu�[���PKD1[��[���F�DConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.mdnu�[���PKD1[��#��A�DConsole/Symfony/Component/Console/Tests/Fixtures/application_2.mdnu�[���PKD1[��$$H&�DConsole/Symfony/Component/Console/Tests/Fixtures/application_astext2.txtnu�[���PKD1[g��/11E��DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_2.txtnu�[���PKD1[[��%��?h�DConsole/Symfony/Component/Console/Tests/Fixtures/command_1.jsonnu�[���PKD1[�Z�o��A��DConsole/Symfony/Component/Console/Tests/Fixtures/application_1.mdnu�[���PKD1[ia����E��DConsole/Symfony/Component/Console/Tests/Fixtures/definition_asxml.txtnu�[���PKD1[�_�n��E�DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.xmlnu�[���PKD1[�: 8��E�DConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.xmlnu�[���PKD1[��-��Zn�DConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception3decorated.txtnu�[���PKD1[�@�]"]"B��DConsole/Symfony/Component/Console/Tests/Fixtures/application_2.xmlnu�[���PKD1[�K@�bbCXEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.txtnu�[���PKD1[p�����F-EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.mdnu�[���PKD1[�A�(ff>REConsole/Symfony/Component/Console/Tests/Fixtures/command_2.xmlnu�[���PKD1[��,���F&EConsole/Symfony/Component/Console/Tests/Fixtures/definition_astext.txtnu�[���PKD1[�I���CyEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_4.xmlnu�[���PKD1[u$´!!C�EConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.txtnu�[���PKD1[���$$HREConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.jsonnu�[���PKD1[3�P���G�EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.xmlnu�[���PKD1[Ѹ�;;GVEConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.txtnu�[���PKD1[��a66BEConsole/Symfony/Component/Console/Tests/Fixtures/application_1.txtnu�[���PKD1[����H�!EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.jsonnu�[���PKD1[X� �,,EF"EConsole/Symfony/Component/Console/Tests/Fixtures/application_run2.txtnu�[���PKD1[󚲱}}F�&EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.jsonnu�[���PKD1[1"8MMK�'EConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorApplication2.phpnu�[���PKD1[#ɤb��H�*EConsole/Symfony/Component/Console/Tests/Fixtures/application_gethelp.txtnu�[���PKD1[�(���B�-EConsole/Symfony/Component/Console/Tests/Fixtures/application_2.txtnu�[���PKD1[;`�MG�2EConsole/Symfony/Component/Console/Tests/Fixtures/application_asxml1.txtnu�[���PKD1[W��،�DZKEConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.mdnu�[���PKD1[��X��DZLEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.jsonnu�[���PKD1[�
c�?[MEConsole/Symfony/Component/Console/Tests/Fixtures/FooCommand.phpnu�[���PKD1[G u=��Q�PEConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception3.txtnu�[���PKD1[F�REConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_1.mdnu�[���PKD1[���==G\SEConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.txtnu�[���PKD1[�����CTEConsole/Symfony/Component/Console/Tests/Fixtures/command_astext.txtnu�[���PKD1[�J�2CvWEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.xmlnu�[���PKD1[l�T���B�XEConsole/Symfony/Component/Console/Tests/Fixtures/application_1.xmlnu�[���PKD1[�Y-͡�BlEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_1.mdnu�[���PKE1[(?hEmEConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.txtnu�[���PKE1[�e::E�mEConsole/Symfony/Component/Console/Tests/Fixtures/application_run1.txtnu�[���PKE1[��x�44CVpEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.txtnu�[���PKE1[6 �_AA@�pEConsole/Symfony/Component/Console/Tests/Fixtures/Foo3Command.phpnu�[���PKE1[��I��D�tEConsole/Symfony/Component/Console/Tests/Fixtures/input_option_3.jsonnu�[���PKE1[Xz�??G�uEConsole/Symfony/Component/Console/Tests/Fixtures/DescriptorCommand2.phpnu�[���PKE1[*[Ǿ44FtyEConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.mdnu�[���PKE1[	�Ӹ�B{EConsole/Symfony/Component/Console/Tests/Fixtures/input_option_2.mdnu�[���PKE1[��U���=H|EConsole/Symfony/Component/Console/Tests/Fixtures/command_2.mdnu�[���PKE1[8�UT

E�~EConsole/Symfony/Component/Console/Tests/Fixtures/application_run4.txtnu�[���PKE1[1G~"//BEConsole/Symfony/Component/Console/Tests/Fixtures/FoobarCommand.phpnu�[���PKE1[�/""��@��EConsole/Symfony/Component/Console/Tests/Fixtures/Foo5Command.phpnu�[���PKE1[�Xl��Q��EConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception4.txtnu�[���PKE1[*�q��H݃EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_3.jsonnu�[���PKE1[��EOO>
�EConsole/Symfony/Component/Console/Tests/Fixtures/command_1.xmlnu�[���PKE1[�NY__EʆEConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_3.txtnu�[���PKE1[�����H��EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_2.jsonnu�[���PKE1[h����>��EConsole/Symfony/Component/Console/Tests/Fixtures/command_2.txtnu�[���PKE1[�	���@�EConsole/Symfony/Component/Console/Tests/Fixtures/Foo2Command.phpnu�[���PKE1[,DŽ���Qe�EConsole/Symfony/Component/Console/Tests/Fixtures/application_renderexception2.txtnu�[���PKE1[.p�~~G��EConsole/Symfony/Component/Console/Tests/Fixtures/input_definition_4.txtnu�[���PKE1[��M��C��EConsole/Symfony/Component/Console/Tests/Fixtures/application_2.jsonnu�[���PKE1[��ttD�EConsole/Symfony/Component/Console/Tests/Fixtures/input_argument_1.mdnu�[���PKE1[Q��d	d	H��EConsole/Symfony/Component/Console/Tests/Tester/ApplicationTesterTest.phpnu�[���PKE1[�x0mBBD׵EConsole/Symfony/Component/Console/Tests/Tester/CommandTesterTest.phpnu�[���PKE1[�����A��EConsole/Symfony/Component/Console/Tests/Input/StringInputTest.phpnu�[���PKE1[��p���;��EConsole/Symfony/Component/Console/Tests/Input/InputTest.phpnu�[���PKE1[�9I;;?��EConsole/Symfony/Component/Console/Tests/Input/ArgvInputTest.phpnu�[���PKE1[��@�H�HE9&FConsole/Symfony/Component/Console/Tests/Input/InputDefinitionTest.phpnu�[���PKE1[1E��<<@NoFConsole/Symfony/Component/Console/Tests/Input/ArrayInputTest.phpnu�[���PKE1[KU�#�#A��FConsole/Symfony/Component/Console/Tests/Input/InputOptionTest.phpnu�[���PKE1[F�5��Cb�FConsole/Symfony/Component/Console/Tests/Input/InputArgumentTest.phpnu�[���PKE1[��Ĕ���;��FConsole/Symfony/Component/Console/Tests/ApplicationTest.phpnu�[���PKE1[�r�HwwN�\GConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleTest.phpnu�[���PKE1[� R�wwS�kGConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterStyleStackTest.phpnu�[���PKE1[]6\���IztGConsole/Symfony/Component/Console/Tests/Formatter/OutputFormatterTest.phpnu�[���PKE1[����CגGConsole/Symfony/Component/Console/Tests/Output/StreamOutputTest.phpnu�[���PKE1[;�!��AQ�GConsole/Symfony/Component/Console/Tests/Output/NullOutputTest.phpnu�[���PKE1[}�R��D��GConsole/Symfony/Component/Console/Tests/Output/ConsoleOutputTest.phpnu�[���PKF1[�����=�GConsole/Symfony/Component/Console/Tests/Output/OutputTest.phpnu�[���PKF1[gO��
�
FJ�GConsole/Symfony/Component/Console/Tests/Helper/FormatterHelperTest.phpnu�[���PKF1[�L��"�"C��GConsole/Symfony/Component/Console/Tests/Helper/DialogHelperTest.phpnu�[���PKF1[+��vv@��GConsole/Symfony/Component/Console/Tests/Helper/HelperSetTest.phpnu�[���PKF1[]_Դ3)3)B�GConsole/Symfony/Component/Console/Tests/Helper/TableHelperTest.phpnu�[���PKF1["
U���Ev)HConsole/Symfony/Component/Console/Tests/Helper/ProgressHelperTest.phpnu�[���PKF1[K� 99I�GHConsole/Symfony/Component/Console/Tests/Descriptor/TextDescriptorTest.phpnu�[���PKF1[1H�DDDMxJHConsole/Symfony/Component/Console/Tests/Descriptor/MarkdownDescriptorTest.phpnu�[���PKF1[oW��::I9MHConsole/Symfony/Component/Console/Tests/Descriptor/JsonDescriptorTest.phpnu�[���PKF1[���66H�OHConsole/Symfony/Component/Console/Tests/Descriptor/XmlDescriptorTest.phpnu�[���PKF1[�ž_JJF�RHConsole/Symfony/Component/Console/Tests/Descriptor/ObjectsProvider.phpnu�[���PKF1[}�
��MZ^HConsole/Symfony/Component/Console/Tests/Descriptor/AbstractDescriptorTest.phpnu�[���PKF1[?�UHii2�mHConsole/Symfony/Component/Console/phpunit.xml.distnu�[���PKF1[e�>��4�4*cqHXML_Util/tests/CreateTagFromArrayTests.phpnu�[���PKF1[�C���'q�HXML_Util/tests/ReplaceEntitiesTests.phpnu�[���PKF1[یu���"��HXML_Util/tests/ApiVersionTests.phpnu�[���PKF1[�Gs���ظHXML_Util/tests/Bug5392Tests.phpnu�[���PKF1[4e��jj*&�HXML_Util/tests/CreateCDataSectionTests.phpnu�[���PKF1[|�\5)�HXML_Util/tests/CollapseEmptyTagsTests.phpnu�[���PKF1[��GG*D�HXML_Util/tests/SplitQualifiedNameTests.phpnu�[���PKF1[Yq��� ��HXML_Util/tests/Bug21184Tests.phpnu�[���PKF1[>�M�����HXML_Util/tests/Bug4950Tests.phpnu�[���PKF1[�YR�""*�HXML_Util/tests/CreateStartElementTests.phpnu�[���PKF1[ܬ$���-��HXML_Util/tests/GetDocTypeDeclarationTests.phpnu�[���PKF1[��G ��HXML_Util/tests/Bug21177Tests.phpnu�[���PKF1[��۩�� Y�HXML_Util/tests/Bug18343Tests.phpnu�[���PKF1[z��t��'wIXML_Util/tests/ReverseEntitiesTests.phpnu�[���PKF1[~�$[ee(�IXML_Util/tests/CreateEndElementTests.phpnu�[���PKF1[���!��$aIXML_Util/tests/AbstractUnitTests.phpnu�[���PKF1[�m4�**!]IXML_Util/tests/CreateTagTests.phpnu�[���PKF1[Df:��)�5IXML_Util/tests/GetXmlDeclarationTests.phpnu�[���PKF1[Z�t�*�:IXML_Util/tests/AttributesToStringTests.phpnu�[���PKF1[ݑh���#-YIXML_Util/tests/IsValidNameTests.phpnu�[���PKF1[���TT%?aIXML_Util/tests/CreateCommentTests.phpnu�[���PKF1[�rv��"�bIXML_Util/tests/RaiseErrorTests.phpnu�[���PKG1[F1y��A�AO�dIOptionsResolver/Symfony/Component/OptionsResolver/Tests/OptionsResolverTest.phpnu�[���PKG1[ν�3;3;G
�IOptionsResolver/Symfony/Component/OptionsResolver/Tests/OptionsTest.phpnu�[���PKG1[��*/AAB��IOptionsResolver/Symfony/Component/OptionsResolver/phpunit.xml.distnu�[���PKG1[<ȸB!!g�INet_SMTP/tests/auth.phptnu�[���PKG1[�߁Q����INet_SMTP/tests/quotedata.phptnu�[���PKG1[�*�W����INet_SMTP/tests/basic.phptnu�[���PKG1[�6������INet_SMTP/tests/config.php.distnu�[���PKH1[�iH���A�IConfig/Symfony/Component/Config/Tests/Definition/EnumNodeTest.phpnu�[���PKH1[hͼ��F�IConfig/Symfony/Component/Config/Tests/Definition/NormalizationTest.phpnu�[���PKH1[�hE--BFJConfig/Symfony/Component/Config/Tests/Definition/ArrayNodeTest.phpnu�[���PKH1[����D�(JConfig/Symfony/Component/Config/Tests/Definition/IntegerNodeTest.phpnu�[���PKH1[&]��B�.JConfig/Symfony/Component/Config/Tests/Definition/FloatNodeTest.phpnu�[���PKH1[�-1��L}5JConfig/Symfony/Component/Config/Tests/Definition/Builder/ExprBuilderTest.phpnu�[���PKH1[<�C��S�NJConfig/Symfony/Component/Config/Tests/Definition/Builder/EnumNodeDefinitionTest.phpnu�[���PKH1[wX��TOTJConfig/Symfony/Component/Config/Tests/Definition/Builder/ArrayNodeDefinitionTest.phpnu�[���PKH1[
Kmޮ
�
L�oJConfig/Symfony/Component/Config/Tests/Definition/Builder/NodeBuilderTest.phpnu�[���PKH1[�����L�zJConfig/Symfony/Component/Config/Tests/Definition/Builder/TreeBuilderTest.phpnu�[���PKH1[Ej~�jjV>�JConfig/Symfony/Component/Config/Tests/Definition/Builder/NumericNodeDefinitionTest.phpnu�[���PKH1[jO灃�C.�JConfig/Symfony/Component/Config/Tests/Definition/ScalarNodeTest.phpnu�[���PKH1[�y���S$�JConfig/Symfony/Component/Config/Tests/Definition/Dumper/YamlReferenceDumperTest.phpnu�[���PKH1[~�P+R^�JConfig/Symfony/Component/Config/Tests/Definition/Dumper/XmlReferenceDumperTest.phpnu�[���PKH1[D�99>�JConfig/Symfony/Component/Config/Tests/Definition/MergeTest.phpnu�[���PKI1[A�RRE��JConfig/Symfony/Component/Config/Tests/Definition/FinalizationTest.phpnu�[���PKI1[{���DO�JConfig/Symfony/Component/Config/Tests/Definition/BooleanNodeTest.phpnu�[���PKI1[%Jbx��LJ�JConfig/Symfony/Component/Config/Tests/Definition/PrototypedArrayNodeTest.phpnu�[���PKI1[�b�..?��JConfig/Symfony/Component/Config/Tests/Fixtures/Util/invalid.xmlnu�[���PKI1[c=���EY�JConfig/Symfony/Component/Config/Tests/Fixtures/Util/document_type.xmlnu�[���PKI1[Gɩ�SSFm�JConfig/Symfony/Component/Config/Tests/Fixtures/Util/invalid_schema.xmlnu�[���PKI1[\�XX=6�JConfig/Symfony/Component/Config/Tests/Fixtures/Util/valid.xmlnu�[���PKI1[�&�>��JConfig/Symfony/Component/Config/Tests/Fixtures/Util/schema.xsdnu�[���PKI1[�r_���Lq�JConfig/Symfony/Component/Config/Tests/Fixtures/Builder/BarNodeDefinition.phpnu�[���PKI1[��@��Q��JConfig/Symfony/Component/Config/Tests/Fixtures/Builder/VariableNodeDefinition.phpnu�[���PKI1[�u�;ssF�JConfig/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.phpnu�[���PKI1[�����
�
U��JConfig/Symfony/Component/Config/Tests/Fixtures/Configuration/ExampleConfiguration.phpnu�[���PKI1[<KConfig/Symfony/Component/Config/Tests/Fixtures/Again/foo.xmlnu�[���PKI1[6~KConfig/Symfony/Component/Config/Tests/Fixtures/foo.xmlnu�[���PKI1[������H�KConfig/Symfony/Component/Config/Tests/Resource/DirectoryResourceTest.phpnu�[���PKI1[�D-��C7KConfig/Symfony/Component/Config/Tests/Resource/FileResourceTest.phpnu�[���PKI1[��s;n$KConfig/Symfony/Component/Config/Tests/Util/XmlUtilsTest.phpnu�[���PKI1[ Z��^^9�?KConfig/Symfony/Component/Config/Tests/ConfigCacheTest.phpnu�[���PKI1[K�OCC9�NKConfig/Symfony/Component/Config/Tests/FileLocatorTest.phpnu�[���PKI1[L��{?`]KConfig/Symfony/Component/Config/Tests/Loader/FileLoaderTest.phpnu�[���PKI1[5bc�@@;NmKConfig/Symfony/Component/Config/Tests/Loader/LoaderTest.phpnu�[���PKI1[oq*,��E�{KConfig/Symfony/Component/Config/Tests/Loader/DelegatingLoaderTest.phpnu�[���PKI1[�YC0�KConfig/Symfony/Component/Config/Tests/Loader/LoaderResolverTest.phpnu�[���PKI1[�Y�hh0��KConfig/Symfony/Component/Config/phpunit.xml.distnu�[���PKI1[����w�KNet_Sieve/tests/largescript.sivnu�[���PKI1[�g��-�-��NNet_Sieve/tests/SieveTest.phpnu�[���PKI1[�Y�npp��NNet_Sieve/tests/config.php.distnu�[���PKI1[ҵ3��9k�NMail_mimeDecode/tests/semicolon_content_type_bug1724.phptnu�[���PKJ1[s��%��-m�NMail_mimeDecode/tests/parse_header_value.phptnu�[���PKJ1[�?7|�f�f<^�NHttpKernel/Symfony/Component/HttpKernel/Tests/KernelTest.phpnu�[���PKJ1[6^P�T�UOHttpKernel/Symfony/Component/HttpKernel/Tests/CacheClearer/ChainCacheClearerTest.phpnu�[���PKJ1[32ET��N\OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/TestEventDispatcher.phpnu�[���PKJ1[g&��fQ_OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionAbsentBundle/ExtensionAbsentBundle.phpnu�[���PKJ1[x���d�aOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/BarCommand.phpnu�[���PKJ1[��W���d�cOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/Command/FooCommand.phpnu�[���PKJ1[`Aļ��hefOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/ExtensionPresentBundle.phpnu�[���PKJ1[O�g�VV�hOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionPresentBundle/DependencyInjection/ExtensionPresentExtension.phpnu�[���PKJ1[GQ�>`
`
d�kOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/MockObjectTestProjectContainer.phpnu�[���PKJ1[#��M�vOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/cache/test/classes.mapnu�[���PKJ1[L(wOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle2Bundle/foo.txtnu�[���PKJ1[q�}VffP�wOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/KernelForOverrideName.phpnu�[���PKJ1[T�zOHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/foo.txtnu�[���PKJ1[U{OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ChildBundle/Resources/hide.txtnu�[���PKJ1[L�{OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/foo.txtnu�[���PKJ1[L|OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/bar.txtnu�[���PKJ1[V�|OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Bundle1Bundle/Resources/foo.txtnu�[���PKJ1[R}OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/FooBundle/foo.txtnu�[���PKJ1[T�}OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/ChildBundle/foo.txtnu�[���PKJ1[V~OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/Bundle1Bundle/foo.txtnu�[���PKJ1[T�~OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/Resources/BaseBundle/hide.txtnu�[���PKJ1[S!OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/foo.txtnu�[���PKJ1[T�OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/BaseBundle/Resources/hide.txtnu�[���PKJ1[&#�E(�OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/TestClient.phpnu�[���PKJ1[y��h��H��OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/KernelForTest.phpnu�[���PKK1[�0����G�OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/FooBarBundle.phpnu�[���PKK1[��?ɜ�f]�OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/ExtensionLoadedBundle.phpnu�[���PKK1[��_�TT}��OHttpKernel/Symfony/Component/HttpKernel/Tests/Fixtures/ExtensionLoadedBundle/DependencyInjection/ExtensionLoadedExtension.phpnu�[���PKK1[���S��V��OHttpKernel/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerAggregateTest.phpnu�[���PKK1[���,%%M�OHttpKernel/Symfony/Component/HttpKernel/Tests/CacheWarmer/CacheWarmerTest.phpnu�[���PKK1[0��GG@��OHttpKernel/Symfony/Component/HttpKernel/Tests/TestHttpKernel.phpnu�[���PKK1[q��<H�OHttpKernel/Symfony/Component/HttpKernel/Tests/ClientTest.phpnu�[���PKK1[݂(�$�$T3�OHttpKernel/Symfony/Component/HttpKernel/Tests/Debug/TraceableEventDispatcherTest.phpnu�[���PKK1[���!/
/
T��OHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/FragmentListenerTest.phpnu�[���PKK1[�W:ttUI�OHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ExceptionListenerTest.phpnu�[���PKK1[(��kkTBPHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ProfilerListenerTest.phpnu�[���PKK1[=v?�
�
O1PHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/EsiListenerTest.phpnu�[���PKK1[p�66R�"PHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/RouterListenerTest.phpnu�[���PKK1[���uuWa7PHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/TestSessionListenerTest.phpnu�[���PKK1[�,ph
h
T]FPHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/ResponseListenerTest.phpnu�[���PKK1[K�(^��RITPHttpKernel/Symfony/Component/HttpKernel/Tests/EventListener/LocaleListenerTest.phpnu�[���PKK1[�o�M��W�dPHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/HIncludeFragmentRendererTest.phpnu�[���PKK1[�
��((W�uPHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/RoutableFragmentRendererTest.phpnu�[���PKK1[�v��UH�PHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/InlineFragmentRendererTest.phpnu�[���PKK1[;����
�
N��PHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/FragmentHandlerTest.phpnu�[���PKK1[�҃��	�	R%�PHttpKernel/Symfony/Component/HttpKernel/Tests/Fragment/EsiFragmentRendererTest.phpnu�[���PKK1[p����8X�PHttpKernel/Symfony/Component/HttpKernel/Tests/Logger.phpnu�[���PKK1[��m*����I��PHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTest.phpnu�[���PKK1[�t~		J��QHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/TestHttpKernel.phpnu�[���PKK1[`��uNNC$�QHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/EsiTest.phpnu�[���PKK1[���JJR�QHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/TestMultipleHttpKernel.phpnu�[���PKK1[�VPM��QHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/HttpCacheTestCase.phpnu�[���PKL1[����Z&Z&E3�QHttpKernel/Symfony/Component/HttpKernel/Tests/HttpCache/StoreTest.phpnu�[���PKL1[�`1H�QHttpKernel/Symfony/Component/HttpKernel/Tests/Config/FileLocatorTest.phpnu�[���PKL1[K�w��C��QHttpKernel/Symfony/Component/HttpKernel/Tests/Bundle/BundleTest.phpnu�[���PKL1[!�g���V�RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MemcacheProfilerStorageTest.phpnu�[���PKL1[�[���WRHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MemcachedProfilerStorageTest.phpnu�[���PKL1[T���
�
R{RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/FileProfilerStorageTest.phpnu�[���PKL1[�,���)�)V�RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/AbstractProfilerStorageTest.phpnu�[���PKL1[�.�\��MHARHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcachedMock.phpnu�[���PKL1[i�]��LoRRHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/MemcacheMock.phpnu�[���PKL1[e��K

IygRHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/Mock/RedisMock.phpnu�[���PKL1[`ej��U�yRHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/MongoDbProfilerStorageTest.phpnu�[���PKL1[p3hNNT.�RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/SqliteProfilerStorageTest.phpnu�[���PKL1[�FE��S�RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/RedisProfilerStorageTest.phpnu�[���PKL1[�&2TTG:�RHttpKernel/Symfony/Component/HttpKernel/Tests/Profiler/ProfilerTest.phpnu�[���PKL1[�Uu֝�?�RHttpKernel/Symfony/Component/HttpKernel/Tests/UriSignerTest.phpnu�[���PKL1[bҏ�^^W�RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/MemoryDataCollectorTest.phpnu�[���PKL1[�C���U��RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/TimeDataCollectorTest.phpnu�[���PKL1[���	�	Wf�RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/ConfigDataCollectorTest.phpnu�[���PKL1[�}#��Zz�RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/ExceptionDataCollectorTest.phpnu�[���PKL1[�J�֌�X��RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/RequestDataCollectorTest.phpnu�[���PKL1[���i	i	W��RHttpKernel/Symfony/Component/HttpKernel/Tests/DataCollector/LoggerDataCollectorTest.phpnu�[���PKL1[g�]�>*>*@��RHttpKernel/Symfony/Component/HttpKernel/Tests/HttpKernelTest.phpnu�[���PKL1[z*V%%S�SHttpKernel/Symfony/Component/HttpKernel/Tests/Controller/ControllerResolverTest.phpnu�[���PKL1[e�
֮�i=SHttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/MergeExtensionConfigurationPassTest.phpnu�[���PKL1[V���^^_ZESHttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/RegisterListenersPassTest.phpnu�[���PKL1[�C�hhbGZSHttpKernel/Symfony/Component/HttpKernel/Tests/DependencyInjection/ContainerAwareHttpKernelTest.phpnu�[���PKL1[��x998ApSHttpKernel/Symfony/Component/HttpKernel/phpunit.xml.distnu�[���PKL1[;�{��"�sSMail_Mime/tests/test_Bug_GH19.phptnu�[���PKL1[�E�oo#xSMail_Mime/tests/test_Bug_13962.phptnu�[���PKL1[Ԣ��``#�ySMail_Mime/tests/test_Bug_21255.phptnu�[���PKL1[i;���$�{SMail_Mime/tests/test_Bug_7561_1.phptnu�[���PKL1[e;�I#g~SMail_Mime/tests/test_Bug_21205.phptnu�[���PKL1[Y�����"؃SMail_Mime/tests/test_Bug_GH26.phptnu�[���PKL1[��RoUU#�SMail_Mime/tests/test_Bug_20226.phptnu�[���PKM1[g��+��#ňSMail_Mime/tests/test_Bug_13444.phptnu�[���PKM1[%��BB"��SMail_Mime/tests/test_Bug_GH16.phptnu�[���PKM1[�-7c77$J�SMail_Mime/tests/test_Bug_3513_2.phptnu�[���PKM1[�(V,��#ՔSMail_Mime/tests/test_Bug_12411.phptnu�[���PKM1[��qS��%��SMail_Mime/tests/test_Bug_10999_1.phptnu�[���PKM1[29r���"�SMail_Mime/tests/encoding_case.phptnu�[���PKM1[M�-\��#7�SMail_Mime/tests/test_Bug_17175.phptnu�[���PKM1[ّB�
�
%A�SMail_Mime/tests/qp_encoding_test.phptnu�[���PKM1[)#��pp#{�SMail_Mime/tests/test_Bug_18772.phptnu�[���PKM1[2!�B��'>�SMail_Mime/tests/test_linebreak_dot.phptnu�[���PKM1[B&���#-�SMail_Mime/tests/test_Bug_12466.phptnu�[���PKM1[�M�U..#=�SMail_Mime/tests/test_Bug_20273.phptnu�[���PKM1[[��b��.��SMail_Mime/tests/content_transfer_encoding.phptnu�[���PKM1[�k�0#��SMail_Mime/tests/test_Bug_20564.phptnu�[���PKM1[�a�[��#�SMail_Mime/tests/class-filename.phptnu�[���PKM1[���o		#^�SMail_Mime/tests/test_Bug_14529.phptnu�[���PKM1[Cz2�}}#��SMail_Mime/tests/test_Bug_12165.phptnu�[���PKM1[Ya�k!!3��SMail_Mime/tests/sleep_wakeup_EOL-bug3488-part1.phptnu�[���PKM1[@�/�NN#�SMail_Mime/tests/test_Bug_21206.phptnu�[���PKM1[�8��$��SMail_Mime/tests/test_Bug_3513_1.phptnu�[���PKM1[5����#��SMail_Mime/tests/test_Bug_21098.phptnu�[���PKM1[���v��$��SMail_Mime/tests/test_Bug_8541_1.phptnu�[���PKM1[Ui�E!E!-��SMail_Mime/tests/headers_without_mbstring.phptnu�[���PKM1[��#��SMail_Mime/tests/test_Bug_21027.phptnu�[���PKM1[`�~@%rTMail_Mime/tests/test_Bug_12385_1.phptnu�[���PKM1[�zŬ�#�TMail_Mime/tests/test_Bug_11731.phptnu�[���PKM1[X��b��#�TMail_Mime/tests/test_Bug_14779.phptnu�[���PKM1[�I�zz#TMail_Mime/tests/test_Bug_20563.phptnu�[���PKM1[ZX�Hww$�TMail_Mime/tests/test_Bug_3513_3.phptnu�[���PKM1[������#�TMail_Mime/tests/test_Bug_15320.phptnu�[���PKM1[�-b2#�TMail_Mime/tests/test_Bug_13032.phptnu�[���PKM1[%+2PP#D TMail_Mime/tests/test_Bug_18083.phptnu�[���PKM1[Qi�"--#�"TMail_Mime/tests/test_Bug_11381.phptnu�[���PKM1[�X�###g%TMail_Mime/tests/test_Bug_19497.phptnu�[���PKM1[�'�''$�'TMail_Mime/tests/test_Bug_8386_1.phptnu�[���PKM1[��1d��#X*TMail_Mime/tests/test_Bug_17025.phptnu�[���PKM1[e�@Q__#G,TMail_Mime/tests/test_Bug_14780.phptnu�[���PKM1[�
Ǟ		-�-TMail_Mime/tests/test_linebreak_larger_76.phptnu�[���PKM1[ܶg�hh$Y7TMail_Mime/tests/test_Bug_9722_1.phptnu�[���PKN1[�YcLYY#9TMail_Mime/tests/test_Bug_16539.phptnu�[���PKN1[��((%�VTMail_Mime/tests/test_Bug_10596_1.phptnu�[���PKN1[9��::%>XTMail_Mime/tests/test_Bug_10816_1.phptnu�[���PKN1[��᠗"�"*�ZTMail_Mime/tests/headers_with_mbstring.phptnu�[���PKN1[���|JJ3�}TMail_Mime/tests/sleep_wakeup_EOL-bug3488-part2.phptnu�[���PKN1[�{�	�	%k�TFile_MARC/tests/marc_xml_rsinger.phptnu�[���PKN1[a!�����TFile_MARC/tests/namespace.xmlnu�[���PKN1[44�-��#w�TFile_MARC/tests/marc_field_003.phptnu�[���PKN1[�c����#h�TFile_MARC/tests/marc_xml_16642.phptnu�[���PKN1[�è{{]�TFile_MARC/tests/marc_020.phptnu�[���PKN1[Ҕ��	�	%�TFile_MARC/tests/marc_16783.phptnu�[���PKN1[F�-//#.�TFile_MARC/tests/marc_field_002.phptnu�[���PKN1[��	\��"��TFile_MARC/tests/marc_lint_001.phptnu�[���PKN1[rP��!��TFile_MARC/tests/marc_xml_004.phptnu�[���PKN1[�0�S��&�TFile_MARC/tests/marc_subfield_001.phptnu�[���PKN1[x;��##9�TFile_MARC/tests/marc_006.phptnu�[���PKN1[}&�
GG"��TFile_MARC/tests/marc_lint_004.phptnu�[���PKN1[�cܯ�!BUFile_MARC/tests/marc_xml_006.phptnu�[���PKN1[���
��#BUFile_MARC/tests/marc_field_005.phptnu�[���PKN1[��%Hhh�UFile_MARC/tests/marc_003.phptnu�[���PKN1[(���NNAUFile_MARC/tests/camel.mrcnu�[���PKN1[�p�޸��7UFile_MARC/tests/marc_007.phptnu�[���PKN1[����1�1!�<UFile_MARC/tests/marc_xml_008.phptnu�[���PKN1[)�]�
�
�nUFile_MARC/tests/marc_005.phptnu�[���PKN1[	V�U,,%�|UFile_MARC/tests/marc_field_21246.phptnu�[���PKN1[�_|6	6	"-�UFile_MARC/tests/marc_lint_002.phptnu�[���PKN1[�=O	
	
��UFile_MARC/tests/sandburg.xmlnu�[���PKN1[�s}���.
�UFile_MARC/tests/marc_xml_namespace_prefix.phptnu�[���PKN1[!Ņ\��!#�UFile_MARC/tests/marc_xml_001.phptnu�[���PKN1[F;�Re%e%Q�UFile_MARC/tests/marc_004.phptnu�[���PKN1[�jS��UFile_MARC/tests/marc_015.phptnu�[���PKN1[7�\�UFile_MARC/tests/marc_009.phptnu�[���PKN1[(Y������UFile_MARC/tests/xmlescape.mrcnu�[���PKN1[�2�.ii�UFile_MARC/tests/marc_018.phptnu�[���PKN1[8��11$�VFile_MARC/tests/marc_record_001.phptnu�[���PKN1[2���
VFile_MARC/tests/skipif.incnu�[���PKN1[\.i�vv
VFile_MARC/tests/sandburg.mrcnu�[���PKN1[#c�����VFile_MARC/tests/onerecord.xmlnu�[���PKN1[�_X���#VFile_MARC/tests/marc_field_004.phptnu�[���PKN1[.%�``!VFile_MARC/tests/marc_010.phptnu�[���PKN1[B�1��
�
"�3VFile_MARC/tests/marc_lint_005.phptnu�[���PKN1[ye@��!�>VFile_MARC/tests/marc_xml_007.phptnu�[���PKN1[������BVFile_MARC/tests/marc_008.phptnu�[���PKN1[+W��
�
�DVFile_MARC/tests/bigarchive.xmlnu�[���PKN1[��ԛ�
�
�RVFile_MARC/tests/marc_014.phptnu�[���PKN1[�����'"aVFile_MARC/tests/marc_xml_namespace.phptnu�[���PKN1[f��~#IdVFile_MARC/tests/marc_field_001.phptnu�[���PKN1[���YY!hVFile_MARC/tests/marc_xml_009.phptnu�[���PKN1[~N0�::�lVFile_MARC/tests/example.mrcnu�[���PKO1[}۶\ppJtVFile_MARC/tests/bad_example.xmlnu�[���PKO1[9�DD	�VFile_MARC/tests/marc_017.phptnu�[���PKO1[�&��cc��VFile_MARC/tests/marc_002.phptnu�[���PKO1[�����!J�VFile_MARC/tests/marc_xml_005.phptnu�[���PKO1[�5;�-�-��VFile_MARC/tests/music.xmlnu�[���PKO1[��`��T�VFile_MARC/tests/marc_012.phptnu�[���PKO1[�S3��VFile_MARC/tests/marc_021.phptnu�[���PKO1[<��--&�WFile_MARC/tests/marc_subfield_002.phptnu�[���PKO1[�f==wWFile_MARC/tests/bad_example.mrcnu�[���PKO1[�kP�WFile_MARC/tests/marc_023.phptnu�[���PKO1[W��))lWFile_MARC/tests/marc_019.phptnu�[���PKO1[�泮��!WFile_MARC/tests/music.mrcnu�[���PKO1[E4kL�	�	�2WFile_MARC/tests/marc_001.phptnu�[���PKO1[�#"�
)
)�<WFile_MARC/tests/marc_022.phptnu�[���PKO1[�p̎u1u1HfWFile_MARC/tests/marc_016.phptnu�[���PKO1[O~iK!K!
�WFile_MARC/tests/marc_013.phptnu�[���PKO1[e����
�
��WFile_MARC/tests/marc_011.phptnu�[���PKP1[�>���!��WFile_MARC/tests/marc_xml_003.phptnu�[���PKP1[N���&&!��WFile_MARC/tests/marc_xml_002.phptnu�[���PKP1[y���
�
"S�WFile_MARC/tests/marc_lint_003.phptnu�[���PKP1[]�Q�� � M��WClassLoader/Symfony/Component/ClassLoader/Tests/ClassCollectionLoaderTest.phpnu�[���PKP1[h4A!AAJ�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Bar.phpnu�[���PKP1[��2[AAJlXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Baz.phpnu�[���PKP1[���	AAJ'XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike2/Foo.phpnu�[���PKP1[�Cq�""P�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeParent.phpnu�[���PKP1[�֡Z  S�	XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeInterface.phpnu�[���PKP1[KG9Ո�P'XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/multipleNs.phpnu�[���PKP1[�Қ[/XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/sameNsMultipleClasses.phpnu�[���PKP1[.~�oDDO�
XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/SomeClass.phpnu�[���PKP1[�R��O�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/notPhpFile.mdnu�[���PKP1[��iO1XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/classmap/notAClass.phpnu�[���PKP1[�{�tKKY�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/C/B/Bar.phpnu�[���PKP1[P�F\KKY�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/C/B/Foo.phpnu�[���PKP1[�Lk�KKYtXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/A/B/Bar.phpnu�[���PKP1[v�գKKYHXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/PrefixCollision/A/B/Foo.phpnu�[���PKP1[��cZZ\XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/C/B/Bar.phpnu�[���PKP1[LVAKZZ\XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/C/B/Foo.phpnu�[���PKP1[Ka�AA\�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/A/B/Bar.phpnu�[���PKP1[����AA\�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/beta/NamespaceCollision/A/B/Foo.phpnu�[���PKP1[��@OOL�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Bar.phpnu�[���PKP1[
Z3bOOLMXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Baz.phpnu�[���PKP1[d�0OOLXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced2/Foo.phpnu�[���PKP1[��55K�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Bar.phpnu�[���PKP1[ᒟ�55K�XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Baz.phpnu�[���PKP1[��R�55KCXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/Foo.phpnu�[���PKP1[�UX�T� XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Namespaced/WithComments.phpnu�[���PKP1[�d�L�#XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/includepath/Foo.phpnu�[���PKP1[l�@@I$XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Bar.phpnu�[���PKQ1[��q�@@I�$XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Baz.phpnu�[���PKQ1[�Ӽ�@@I�%XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/Foo.phpnu�[���PKQ1[5J�DDRJ&XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Pearlike/WithComments.phpnu�[���PKQ1[�>�X��H(XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/deps/traits.phpnu�[���PKQ1[:5T+JU)XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/php5.4/traits.phpnu�[���PKQ1[�
N�77V�*XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/ATrait.phpnu�[���PKQ1[��`�RRZ�+XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/CInterface.phpnu�[���PKQ1[��;;Qy,XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/A.phpnu�[���PKQ1[ ��LLQ5-XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/D.phpnu�[���PKQ1[t��LLQ.XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/E.phpnu�[���PKQ1[��HGGV�.XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/BTrait.phpnu�[���PKQ1[��LqGGQ�/XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/B.phpnu�[���PKQ1[[�"�77Vd0XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/CTrait.phpnu�[���PKQ1[���Z??Z!1XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/ClassesWithParents/GInterface.phpnu�[���PKQ1[�6S�IIX�1XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/C/Bar.phpnu�[���PKQ1[	���IIX�2XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/C/Foo.phpnu�[���PKQ1[&F�IIX�3XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/A/Bar.phpnu�[���PKQ1[���IIX]4XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/PrefixCollision/A/Foo.phpnu�[���PKQ1[�]�>XX[.5XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/C/Bar.phpnu�[���PKQ1[~�(XX[6XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/C/Foo.phpnu�[���PKQ1[99A??[�6XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/A/Bar.phpnu�[���PKQ1[���i??[�8XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/alpha/NamespaceCollision/A/Foo.phpnu�[���PKQ1[n��DDV�:XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Pearlike2/FooBar.phpnu�[���PKQ1[�gy�RRXR;XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Namespaced2/FooBar.phpnu�[���PKR1[[�“88W,<XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Namespaced/FooBar.phpnu�[���PKR1[x�wCCU�=XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/fallback/Pearlike/FooBar.phpnu�[���PKR1[>\oNNd�>XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Bar.phpnu�[���PKR1[���GNNd�?XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/ApcPrefixCollision/A/B/Foo.phpnu�[���PKR1[�F�EEdw@XClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Bar.phpnu�[���PKR1[]�[�EEdPBXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/beta/Apc/NamespaceCollision/A/B/Foo.phpnu�[���PKR1[/5�<<R)DXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/FooBar.phpnu�[���PKR1[ے�99O�EXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Bar.phpnu�[���PKR1[$�y99O�GXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Baz.phpnu�[���PKR1[0- +99OWIXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Namespaced/Foo.phpnu�[���PKR1[yQUmDDMKXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Bar.phpnu�[���PKR1[��&DDM�KXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Baz.phpnu�[���PKR1[���EDDM�LXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/Pearlike/Foo.phpnu�[���PKR1[�7LLcRMXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/ApcPrefixCollision/A/Bar.phpnu�[���PKR1[.��&LLc1NXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/ApcPrefixCollision/A/Foo.phpnu�[���PKR1[4���CCcOXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Bar.phpnu�[���PKR1[�qo�CCc�PXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/alpha/Apc/NamespaceCollision/A/Foo.phpnu�[���PKR1[/5�<<[�RXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/fallback/Namespaced/FooBar.phpnu�[���PKR1[���GG]�TXClassLoader/Symfony/Component/ClassLoader/Tests/Fixtures/Apc/fallback/Apc/Pearlike/FooBar.phpnu�[���PKR1[�M��� � CWUXClassLoader/Symfony/Component/ClassLoader/Tests/ClassLoaderTest.phpnu�[���PKR1[e:{a��O�vXClassLoader/Symfony/Component/ClassLoader/Tests/ApcUniversalClassLoaderTest.phpnu�[���PKR1[8`�##L��XClassLoader/Symfony/Component/ClassLoader/Tests/UniversalClassLoaderTest.phpnu�[���PKR1[\|����I��XClassLoader/Symfony/Component/ClassLoader/Tests/ClassMapGeneratorTest.phpnu�[���PKR1[�)mm:��XClassLoader/Symfony/Component/ClassLoader/phpunit.xml.distnu�[���PKS1[y�MV����X��XDependencyInjection/Symfony/Component/DependencyInjection/Tests/ContainerBuilderTest.phpnu�[���PKS1[�[��Q�aYDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterTest.phpnu�[���PKS1[~O�99f*eYDependencyInjection/Symfony/Component/DependencyInjection/Tests/LazyProxy/PhpDumper/NullDumperTest.phpnu�[���PKS1[I8�i��v�iYDependencyInjection/Symfony/Component/DependencyInjection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.phpnu�[���PKS1[���//W�oYDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/simple.phpnu�[���PKS1[G3G@��[<pYDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services10.phpnu�[���PKS1[E�))\M}YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services1-1.phpnu�[���PKS1[o�TbZ�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services1.phpnu�[���PKS1[,�j���Z��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9.phpnu�[���PKS1[$�oyy[�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services11.phpnu�[���PKS1[��:A!!c��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services9_compiled.phpnu�[���PKS1[��7/��Z��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services8.phpnu�[���PKS1[�(]

Z��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services1.xmlnu�[���PKS1[�ibĤ�Zd�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services5.xmlnu�[���PKS1[�![�[��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services10.xmlnu�[���PKS1[u�

Z)�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services4.xmlnu�[���PKS1[�_�+WWZ��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services7.xmlnu�[���PKS1[x'�	11\��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/withdoctype.xmlnu�[���PKT1[�w�zhhZ^�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services8.xmlnu�[���PKT1[���<ii[P�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services13.xmlnu�[���PKT1[p�Ԡ��ZD�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services6.xmlnu�[���PKT1[˕n%%Y��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/nonvalid.xmlnu�[���PKT1[��Pgge2�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services4_bad_import.xmlnu�[���PKT1[\_���Z.�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services3.xmlnu�[���PKT1[]2�
��d��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extension2/services.xmlnu�[���PKT1[	�Z�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services2.xmlnu�[���PKT1[������d��YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extension1/services.xmlnu�[���PKT1[B�X�

Z�YDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/services9.xmlnu�[���PKT1[�^����e	ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services1.xmlnu�[���PKT1[Ń����e�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services5.xmlnu�[���PKT1[җ'y��eZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services4.xmlnu�[���PKT1[��	eXZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services7.xmlnu�[���PKT1[ix�C��e�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services6.xmlnu�[���PKT1[>U���e�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services3.xmlnu�[���PKT1[�}��e�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/xml/extensions/services2.xmlnu�[���PKT1[��33`ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services10.dotnu�[���PKT1[h	�	�	_�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services9.dotnu�[���PKT1[Ձ1*,,bH(ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services10-1.dotnu�[���PKT1[&�WW_+ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services1.dotnu�[���PKT1[ŏD�;;`�,ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services13.dotnu�[���PKT1[��8BB`�/ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/graphviz/services14.dotnu�[���PKT1[�N�{rrt�1ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtensionInPhar.pharnu�[���PKT1[�
��Y�6ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/foo.phpnu�[���PKT1[��]���`�9ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/createphar.phpnu�[���PKT1[.Y<ҿ�f*?ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectExtension.phpnu�[���PKT1[Aov:ZZ]DZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/classes.phpnu�[���PKT1[RK:��hfHZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/schema/project-1.0.xsdnu�[���PKT1[��[[m�JZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/includes/ProjectWithXsdExtension.phpnu�[���PKT1[����[�LZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services8.ymlnu�[���PKT1[�|��DD[�MZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services3.ymlnu�[���PKT1[6�e3��[�NZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services6.ymlnu�[���PKT1[V�v�==[�SZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services4.ymlnu�[���PKT1[#�&#[�UZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/nonvalid1.ymlnu�[���PKT1[y��??f[VZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services4_bad_import.ymlnu�[���PKT1[�*_6��Y0WZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag3.ymlnu�[���PKT1[zb��nnY^XZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag1.ymlnu�[���PKT1[����''[UYZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services7.ymlnu�[���PKT1[�%/���\ZZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services10.ymlnu�[���PKT1[��2[![ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services1.ymlnu�[���PKT1[�MuA\�[ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services11.ymlnu�[���PKT1[}�>���YJ\ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/badtag2.ymlnu�[���PKU1[:�Ʋ��[a]ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services2.ymlnu�[���PKU1[W�%[�^ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/nonvalid2.ymlnu�[���PKU1[|�w���[C_ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services9.ymlnu�[���PKU1[����GG\YgZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/yaml/services13.ymlnu�[���PKU1[۴)�++Y,hZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/nonvalid.ininu�[���PKU1[pu��((\�hZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters2.ininu�[���PKU1[s4��''[�iZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters.ininu�[���PKU1[5l%%\FjZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/ini/parameters1.ininu�[���PKU1[�Fm��c�jZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/interfaces2.phpnu�[���PKU1[4h���b;nZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container8.phpnu�[���PKU1[�	Z��bhpZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container9.phpnu�[���PKU1[���33c}}ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container11.phpnu�[���PKU1[��|cCZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/interfaces1.phpnu�[���PKU1[C�ݲ;;c�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container10.phpnu�[���PKU1[BreOOc��ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container13.phpnu�[���PKU1[�*�EEc��ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container12.phpnu�[���PKU1[�1�v��cn�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Fixtures/containers/container14.phpnu�[���PKU1[
�^��g��ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterBag/FrozenParameterBagTest.phpnu�[���PKU1[$����9�9a�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/ParameterBag/ParameterBagTest.phpnu�[���PKU1[��
�
R�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/CrossCheckTest.phpnu�[���PKU1[2+`��	�	Y2�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/YamlDumperTest.phpnu�[���PKU1[v��]{�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/GraphvizDumperTest.phpnu�[���PKU1[�)���X�ZDependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/XmlDumperTest.phpnu�[���PKU1[�"��."."X�[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.phpnu�[���PKU1[����QG#[DependencyInjection/Symfony/Component/DependencyInjection/Tests/ReferenceTest.phpnu�[���PKU1[ł``\q'[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/ClosureLoaderTest.phpnu�[���PKU1[SR���\]-[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/PhpFileLoaderTest.phpnu�[���PKU1[�kV�0�0]�3[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/YamlFileLoaderTest.phpnu�[���PKU1[Q&I�8a8a\e[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/XmlFileLoaderTest.phpnu�[���PKU1[���
�
\��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Loader/IniFileLoaderTest.phpnu�[���PKU1['����	�	m�[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveInvalidReferencesPassTest.phpnu�[���PKV1[��'{{l��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckCircularReferencesPassTest.phpnu�[���PKV1[>�"��k��[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckReferenceValidityPassTest.phpnu�[���PKV1[]����o�[DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveDefinitionTemplatesPassTest.phpnu�[���PKV1[}1H@@s�
\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.phpnu�[���PKV1[��f00m�\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/InlineServiceDefinitionsPassTest.phpnu�[���PKV1[O����\W(\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/IntegrationTest.phpnu�[���PKV1[@|޵�}�5\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.phpnu�[���PKV1[@�w��l�=\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/CheckDefinitionValidityPassTest.phpnu�[���PKV1[�~�``m>J\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/AnalyzeServiceReferencesPassTest.phpnu�[���PKV1[��I�
�
l;W\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/RemoveUnusedDefinitionsPassTest.phpnu�[���PKV1[
T^�??ovb\DependencyInjection/Symfony/Component/DependencyInjection/Tests/Compiler/ResolveReferencesToAliasesPassTest.phpnu�[���PKV1[���e�5�5RTi\DependencyInjection/Symfony/Component/DependencyInjection/Tests/DefinitionTest.phpnu�[���PKV1[+��E�
�
[c�\DependencyInjection/Symfony/Component/DependencyInjection/Tests/DefinitionDecoratorTest.phpnu�[���PKV1[�K5��W�WQ��\DependencyInjection/Symfony/Component/DependencyInjection/Tests/ContainerTest.phpnu�[���PKV1[`��=�	�	[]DependencyInjection/Symfony/Component/DependencyInjection/Tests/Extension/ExtensionTest.phpnu�[���PKV1[���uuJ�]DependencyInjection/Symfony/Component/DependencyInjection/phpunit.xml.distnu�[���PK���u]